zabbix拥有完善的API,基于JSON
RPC提供资产,主机,主机组,监控项,告警等方面的接口。在做运维自动化时,需要用API功能对zabbix二次开发。本文我将介绍如何用python信使用zabbix的API。

API介绍

*
API地址, http://你的zabbix域名/api_jsonrpc.php

*
API请求方法,采用POST

*
API请求数据结构
{ "jsonrpc": "2.0", // 版本 "method": "user.login", // 接口方法名 "params": { //接口参数
},"auth": "", // 登录后的session,未登录为空 "id": 1 // 任意数 }
*
API常用的接口

* user.login,用户登录
* host.get(create|delete|update),主机操作
* hostgroup.get(create|delete|update),主机组操作
* item.get(create|delete|update),监控项目操作
* history.get,历史数据查询
* event.get,事件查询
* trigger.get,触发器查询
API调用

* zabbix的接口调用前需要先进行登录验证,获取sessionid
* 构造某个接口的请求参数,并将sessionid加入到参数的auth字段,POST请求即可
登录
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)

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信