python 通过zabbix api获得所有主机的ip

烈酒焚心 提交于 2021-01-13 08:49:21

 

 

#!/usr/bin/env python3

#coding=utf-8

import json
import requests
#from urllib import requests, parse,error

# based url and required header

#url = "http://sg-zabbix.upliveapp.com/zabbix/api_jsonrpc.php"

class zabbixapi:
'''获得token'''
def __init__(self):
self.url = 'http://xxxxxxxx/zabbix/api_jsonrpc.php'
self.headers = {'Content-Type': 'application/json'}
auth = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "xxxxx", ###验证
"password": "xxxxx"
},
"id": 1,
"auth": None,
}
response = requests.post(self.url, data=json.dumps(auth), headers=self.headers)
self.authid = json.loads(response.text)['result']
#print(self.authid)

###得到所有服务器和ip信息
def get_hosts(self):
#print("12313")
neirong={
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": self.authid
}
data = json.dumps(neirong)
#print(data)
response = requests.post(self.url, data=json.dumps(neirong), headers=self.headers)
dict = json.loads(response.content)
#print(dict['result'])
data = dict['result']
return dict['result']
#print(response.text)
###整理信息,输出想要的信息,组合成字典
def getProc(data):
dict = {}
list = data
print(list)
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


# 整理输出ip
def getGroup(ip_list):
ip_group = {}
ips = ip_list
for i in ips:
print(i)

if __name__ == "__main__":
p = zabbixapi()
data = p.get_hosts()
hosts = getProc(data)
#print(hosts)
ip_list = getData(hosts)
getGroup(ip_list)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!