前言:
以下内容根据zabbix 3.2官方文档总结:https://www.zabbix.com/documentation/3.2/manual/api
此文档只是简单的介绍API的基本使用,关于一些完整功能或高级功能将在后续的博文中展现
调用Zabbix api使用的是HTTP的POST请求方式
其中请求的头部为:
{"Content-Type": "application/json-rpc"}
请求的URL为:
http://zabbix.aek.com/api_jsonrpc.php
如果url中包含目录需要把目录写上,如http://zabbix.aek.com/zabbix/api_jsonrpc.php,最后就是请求的数据(data),比如获取Token,创建主机,获取主机ID,获取模板ID,获取组ID,删除主机等。
接下以以Python调用 API为例,例出用法案例:
测试连接是否成功
#!/usr/bin/python #coding:utf:8 import requests import json url = "http://zabbix.aek.com/zabbix/api_jsonrpc.php" header = {"Content-Type": "application/json-rpc"} data = {"jsonrpc":"2.0","method":"apiinfo.version","id":1,"auth":None,"params":{}} request = requests.post(url=url, headers=header, data=json.dumps(data)) print(request.content)
上面的data用来测试是否可连接成功,官方文档中auth的值为null,但在python中null用None表示,所以需要改成None。
成功后返回值大概如下:会显示zabbix版本
{"jsonrpc":"2.0","result":"3.2.3","id":1}
获取Token
#!/usr/bin/python #coding:utf:8 import requests import json url = "http://zabbix.aek.com/zabbix/api_jsonrpc.php" header = {"Content-Type": "application/json-rpc"} data = {"jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": None } request = requests.post(url=url, headers=header, data=json.dumps(data)) print(request.content)
成功后返回值如下:会返回一个Token
{"jsonrpc":"2.0","result":"391277f070a3ebc5b2afe9cf466cb74c","id":1}
最后以一个完整的Python脚本通过zabbix API获取所有主机的信息为例:
#!/usr/bin/python #coding:utf:8 import requests import json class Zabbix: def __init__(self, url, header, username, password): self.url = url self.header = header self.username = username self.password = password def getToken(self): #获取Token并返回字符Token字符串 data = {"jsonrpc": "2.0", "method": "user.login", "params": { "user": self.username, "password": self.password }, "id": 1, "auth": None } token = requests.post(url=self.url, headers=self.header, data=json.dumps(data)) return json.loads(token.content)["result"] def getAllHost(self): #获取所有主机信息 data = {"jsonrpc": "2.0", "method": "host.get", "params": { "output": [ "hostid", "host", ], "selectGroups": "extend", "selectInterfaces": [ "interfaceid", "ip" ] }, "id": 2, "auth": self.getToken() } hosts = requests.post(url=self.url, headers=self.header, data=json.dumps(data)) return json.loads(hosts.content)["result"] if __name__ == "__main__": header = {"Content-Type": "application/json-rpc"} url="http://zabbix.aek.com/zabbix/api_jsonrpc.php" test = Zabbix(url=url, header=header, username="Admin", password="zabbix") print(test.getAllHost())
通过以上的学习相信大家对Zabbix API已经有一个初步的认识,后面将会通过API去完成主机的自动添加,自动化报表等使用
时间: 2024-08-29 09:50:25