zabbix api 獲取圖形

藍藍發表於2020-06-24

一.背景

因為介面壓測平臺需要獲取介面伺服器的效能資料,所以找了一圈zabbix api獲取資料的方式,以此記錄下來。

zabbix api地址:https://www.zabbix.com/documentation/3.4/zh/manual/api 功能還真挺多,挺詳細的。

二.zabbix api獲取方式

1.獲取token

url = "http://ip/zabbix/api_jsonrpc.php"
header = {
"Content-Type": "application/json"
}

def get_token():
data = {"jsonrpc": "2.0", "method": "user.login", "params": {"user": "xxx", "password": "xxx"},
"id": 1, "auth": None}
resp = requests.post(url, json=data, headers=header)
print(resp.status_code)
print(resp.text)
if resp.status_code == 200:
json_data = json.loads(resp.text)
return json_data['result']
return None

2.獲取伺服器ip,這個可以獲取到hostid

def get_machine():
auth = get_token()
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": auth
}
resp = requests.post(url, json=data, headers=header)
print(resp.status_code)
print(resp.text)

3.獲取graphid

def get_graph():
auth = get_token()
data = {
"jsonrpc": "2.0",
"method": "graph.get",
"params": {
"output": "extend",
"hostids": 10351,
"sortfield": "name"
},
"auth": auth,
"id": 1
}
resp = requests.post(url, json=data, headers=header)
print(resp.status_code)
print(resp.text)

4.獲取圖形寫入檔案

def get_png():
token = get_token()
print(token)
header = {
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Cookie": "PHPSESSID=2bvctu9rva99ppd74gaopb8i42; zbx_sessionid=" + token,
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1"
}
charUrl = "http://ip/zabbix/chart2.php?graphid=3396&period=120&stime=20200624103155&isNow=0&profileIdx=web.graphs&profileIdx2=3396&width=682&sid=96b019eb208dec18&screenid=&curtime=1592965915667"
resp = requests.get(charUrl, headers=header)
with open("test_img.png", 'wb') as f:
f.write(resp.content)

關鍵引數:

charUrl可以從graphs查詢的圖片,然後右擊-複製圖片地址獲取到

graphid=3396這個就是graph下拉那塊的id,有CPU、流量等,上面有方法通過hostid可以獲取到

period=120這個單位秒,即獲取2分鐘的圖形,可以隨便改

stime=20200624103155開始時間,意思很明朗;所以其實獲取的圖形,就是從stime到stime+period這段的圖形

width=682這個是圖片寬度

isNow=0預設是1,就是5分鐘時長的圖形,改為0後,period就起作用了

總結:簡單記錄api獲取方式,但是其實我是想獲取CPU的資料,不是圖形,還在琢磨能不能獲取到一段時間的平均值。有知道的請告訴我哇~~

有問題請指出哦~~

相關文章