zabbix拥有完善的API,基于JSON RPC提供资产,主机,主机组,监控项,告警等方面的接口。在做运维自动化时,需要用API功能对zabbix二次开发。本文我将介绍如何用python信使用zabbix的API。
API地址, http://你的zabbix域名/api_jsonrpc.php
API请求方法,采用POST
API请求数据结构
{
"jsonrpc": "2.0", // 版本
"method": "user.login", // 接口方法名
"params": {
//接口参数
},
"auth": "", // 登录后的session,未登录为空
"id": 1 // 任意数
}
API常用的接口
import requests
import json
url = "http://xxxx/api_jsronrpc.php"
header = {"Content-Type": "application/json-rpc"}
username = zabbix
password = zabbix
def do_request(data):
try:
request = requests.post(url=url, headers=header, data=json.dumps(data), timeout=60)
if request.json()["result"]:
return request.json()["result"]
except requests.ConnectionError:
return None
else:
return None
def get_token():
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": username,
"password": password
},
"id": 0,
"auth": None
}
token = do_request(data)
if not token:
print("登录失败")
print(token)
def get_host(hostid):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
},
"id": 1,
"auth": auth()
})
resp = do_request(data)
print(resp)
def get_host(hostid):
data = json.dumps({
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "itemid",
"hostids": hostid,
"search": {
"key_": "system.cpu.load[,avg1]"
}
},
"id": 1,
"auth": auth()
})
resp = do_request(data)
print(resp)
def get_host(itemid):
ts = time.time() - 900 //获取最近900秒内的数据
data = json.dumps({
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 0,
"itemids": itemid,
"limit": 0,
"time_from": ts,
"sortfield": "clock",
"sortorder": "ASC",
# "hostids": hostid,
},
"id": 1,
"auth": auth()
})
resp = do_request(data)
print(resp)