標籤:token imp dict pytho app 主機 ken eid passwd
之前發現搜尋出來的主機調用zabbix api資訊都不是那麼明確,後來通過zabbix官方文檔,查到想要的api資訊,隨後寫一篇自己這次項目中用到的api。
#!/usr/bin/env python#coding:utf8import requestsimport jsonheaders = {‘Content-Type‘: ‘application/json-rpc‘}server_ip = ‘10.37.149.109‘url = ‘http://%s/zabbix/api_jsonrpc.php‘ %server_ip#擷取tokendef getToken(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) return dict[‘result‘]# 從api擷取主機資訊,def getHosts(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‘] return dict[‘result‘]#整理資訊,輸出想要的資訊,組合成字典,我這邊提出ip。def getProc(data): dict = {} list = data for i in list: host = i[‘host‘] inter = i[‘interfaces‘] for j in inter: ip = j[‘ip‘] dict[host] = ip return dict #排序ip列表def getData(dict): data = dict ip_list = [ ] for key in data.keys(): ip = data[key] ip_list.append(ip) ip_list = list(set(ip_list)) ip_list.sort() return ip_list #整理輸出ipdef getGroup(ip_list): ip_group = { } ips = ip_list for i in ips: print i if __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 調用zabbix api實現查詢主機資訊,輸出所有主機ip