1、python访问zabbix api
from urllib import parse, request import json, requests class Zabbix_api(object): def __init__(self, ip): self.url = 'http://%s/zabbix/api_jsonrpc.php' % ip self.headers = {'User-Agent': 'Python Chrome', "Content-Type": "application/json-rpc"} self.auth_data = { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "admin", "password": "zabbix" }, "id": 1, "auth": None } self.token = requests.post(url=self.url, data=json.dumps(self.auth_data).encode(encoding='utf-8'), headers=self.headers).json()['result'] def result(self, data): data['auth'] = self.token res = requests.post(url=self.url, data=json.dumps(data).encode(encoding='utf-8'), headers=self.headers).json() # req = request.Request(url=self.url, data=json.dumps(data).encode(encoding='utf-8'), headers=self.headers) # res = request.urlopen(req) # res=json.loads(res.read()) return res['result'] if __name__ == '__main__': data = { "jsonrpc": "2.0", "method": "host.get", "params": { # 'output': ['hostid', 'host', 'name', 'templateid', ], 'output': 'extend', 'search': { "name": 'BJ_Sw*' }, 'searchWildcardsEnabled': True, }, "auth": "038e1d7b1735c6a5436ee9eae095879e", "id": 1 } host_get = Zabbix_api('x.x.x.x') res = host_get.result(data) print(res)
2、ajax调用zabbix的api示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7/css/bootstrap.css"> <script src="/static/js/jquery-3.2.1.js"></script> <script src="/static/plugins/bootstrap-3.3.7/js/bootstrap.js"></script> <script src="/static/js/echarts.min.js"></script> </head> <body> <input type="button" class="btn btn-primary" value="view_zabbix" id="zabbix"> </body> <script> $("#zabbix").click(function () { var par = { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "admin", "password": "zabbix" }, "id": 1, "auth": null }; $.ajax({ url: "http://ip/api_jsonrpc.php", type: "POST", headers: { "Content-Type": "application/json" }, dataType: "json", data: JSON.stringify(par), //这里必须将对象转成string类型 success: function (data) { console.log(data) } }) }) </script>