previously found that the search for host calls Zabbix API information is not so clear, and then through the Zabbix official documents to find the desired API information, and then write an article of their own this project used in the API.
#!/usr/bin/env python#Coding:utf8ImportRequestsImportjsonheaders= {'Content-type':'Application/json-rpc'}server_ip='10.37.149.109'URL='http://%s/zabbix/api_jsonrpc.php'%server_ip#Get tokendefGetToken (username,passwd):#url = ' http://%s/zabbix/api_jsonrpc.php '%server_ip #headers = {' Content-type ': ' Application/json-rpc '}username='Admin'passwd='Zabbix'Data= { "Jsonrpc":"2.0", "Method":"User.login", "params": { "User": Username,"Password": passwd},"ID": 0} request= Requests.post (url=url,headers=headers,data=json.dumps (data)) Dict=json.loads (Request.text)returndict['result']#get host information from the API,defgethosts (token_num): Data= { "Jsonrpc":"2.0", "Method":"Host.get", "params": { "Output": [ "HostID", "Host" ], "selectinterfaces": [ "InterfaceID", "IP" ] }, "ID": 2, "Auth": Token_num,} request= Requests.post (url=url,headers=headers,data=json.dumps (data)) Dict=json.loads (request.content)#print dict[' result ' returndict['result']#organize the information, output the information you want, combine it into a dictionary, I propose IP here. defGetproc (data): Dict={} list=Data forIinchList:host= i['Host'] Inter= i['Interfaces'] forJinchInter:ip= j['IP'] Dict[host]=IPreturndict #排序ip列表defGetData (dict): Data=dict ip_list= [ ] forKeyinchData.keys (): IP=Data[key] Ip_list.append (IP) ip_list=list (set (ip_list)) Ip_list.sort ()returnip_list #整理输出ipdefGetgroup (ip_list): Ip_group={} ips=ip_list forIinchIPs:PrintIif __name__=="__main__": #server_ip = ' 10.37.149.109 'Username ='Admin'passwd='Zabbix'Token_num=GetToken (username,passwd) data=gethosts (token_num) hosts=getproc (data) ip_list=GetData (Hosts) Getgroup (ip_list)
Python calls the Zabbix API for querying host information, outputting all host IPs