1、python获取zabbix apiinfo.version信息:
import requests
import json
data = {"jsonrpc":"2.0","method":"apiinfo.version","id":1,"auth":None,"params":{}}
header = {"Content-Type":"application/json-rpc"}
url = 'https://zabbix.cn/api_jsonrpc.php'
response = requests.post(url,data=json.dumps(data),headers=header)
print(response.content.decode())
- `jsonrpc` - API使用的JSON-RPC协议的版本; Zabbix API实现的JSON-RPC版本是2.0;
- `method` - 被调用的API方法名;
- `params` - 将被传递给API方法的参数;
- `id` - 请求的任意标识符;
- `auth` -用户认证令牌; 因为我们还没有一个,它的设置null。
在访问Zabbix中的任何数据之前,需要登录并获取身份验证令牌,python连接zabbix api获取身份验证令牌:
import requests
import json
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "username",
"password": "password"
},
"id": 1,
"auth": None,
}
header = {"Content-Type":"application/json-rpc"}
url = 'https://zabbix.cn/api_jsonrpc.php'
response = requests.post(url,data=json.dumps(data),headers=header)
r = response.content.decode()
r_json = json.loads(r)
print("身份令牌为:",r_json["result"])
1、获取所有主机ID及主机名称信息
import requests
import json
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "username", #zabbix登录用户名
"password": "password" #zabbix登录密码
},
"id": 1,
"auth": None,
}
header = {"Content-Type":"application/json-rpc"}
url = 'https://myzabbix.cn/api_jsonrpc.php' #zabbix api接口
response = requests.post(url,data=json.dumps(data),headers=header)
r = response.content.decode()
r_json = json.loads(r)
# print("身份令牌为:",r_json["result"])
token = r_json["result"]
host_data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": token
}
host_info = json.loads(requests.post(url,data=json.dumps(host_data),headers=header).content.decode())
host_list = host_info["result"]
# print(host_list)
# print(host_list[0])
for i in host_list:
print(i["hostid"],i["host"]) # 打印所有主机id及主机名称信息
2.根据key查找监控项,从ID为10265的主机获取key带有“ nginx”的监控项,并以名称排序。
nginx_data = {
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": "10265",
"search": {
"key_": "nginx"
},
"sortfield": "name"
},
"auth": token,
"id": 3
}
nginx_item = json.loads(requests.post(url,data=json.dumps(nginx_data),headers=header).content.decode())
# print(nginx_item['result'])
for i in nginx_item['result']:
print(i['itemid'],i['name'],i['key_']) #打印itemid、监控项名称及key
3.获取监控项ID为113480数字(浮点)监控项中获取最近10条数据
history_data = {
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 0,
"itemids": "113480",
"sortfield": "clock",
"sortorder": "DESC",
"limit": 10
},
"auth": token,
"id": 4
}
history_item = json.loads(requests.post(url,data=json.dumps(history_data),headers=header).content.decode())
print(history_item)
更多用法参见zabbix官方文档。