要获取 Prometheus API 中的主机名,可以使用以下查询:
up{job="prometheus"}
这将返回所有已注册到 Prometheus 的活动目标列表,其中包括其主机名、IP 地址和运行状况。从该列表中选择任何一个目标并提取其主机名即可。
例如,在 Python 中,您可以使用以下代码来获取 Prometheus API 的主机名:
import requests
url = "http://localhost:9090/api/v1/query"
querystring = {"query":"up{job=\"prometheus\"}"}
response = requests.request("GET", url, params=querystring)
data = response.json()
hostname = data['data']['result'][0]['metric']['instance']
print(hostname)
此代码通过发送 GET 请求到 Prometheus API 并传递上述查询参数来获取数据。然后从响应数据中提取第一个结果的 instance 属性作为主机名,并将其打印出来。
请注意,此方法假定您正在运行 Prometheus 服务器并且它已正确配置以监视本地计算机。如果要获取其他主机的名称,则需要相应地更改查询参数。




