Python3通过Zabbix API获取数据
Zabbix API官方文档:https://www.zabbix.com/documentation/2.0/manual/appendix/api/api
#!/usr/bin/env python #For Python3 import urllib.request,urllib.parse,json,sys,importlib,argparse importlib.reload(sys) class zbxAPI(): def __init__(self): self.url = "http://10.10.2.2/zabbix/api_jsonrpc.php" self.headers = { 'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Content-Type':'application/json' } self.authdata = { "jsonrpc":"2.0", "method":"user.login", "params": { "user":"uname", "password":"password" }, "id":0 } #获取Token(auth data) def get_token(self): res = self.post_request(self.authdata) if 'result' in res: token = res['result'] return token else: return res['error']['data'] #发送参数到Zabbix服务器端请求数据 def post_request(self,postdata): postdata = bytes(json.dumps(postdata),'utf8') try: request = urllib.request.Request(self.url,postdata,headers=self.headers) reponse = urllib.request.urlopen(request).read() content = json.loads(reponse.decode('utf8')) return content except Exception as ErrorMsg: return ErrorMsg exit() #获取host列表 def list_hosts(self): host_list=[] get_data = { "jsonrpc":"2.0", "method":"host.get", "params":{ "output": "extend", }, "auth":self.get_token(), "id":1, } res = self.post_request(get_data) reslist = res['result'] for res in reslist: host_list.append(res['host']) return(host_list) #获取template列表 def list_templates(self): template_list=[] get_data = { "jsonrpc":"2.0", "method":"template.get", "params":{ "output": "extend", }, "auth":self.get_token(), "id":1, } res = self.post_request(get_data) reslist = res['result'] for res in reslist: print(res['templateid'] + ',' + res['host']) #测试认证是否成功,成功则打印auth data def Auth_test(self): print(self.get_token()) m=zbxAPI() # m.Auth_test() # print(m.list_hosts()) m.list_templates()