欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

获取zabbix上所有主机的IP和主机名

程序员文章站 2022-07-05 11:20:32
1 #coding:utf-8 2 #获取zabbix上所有主机的IP和主机名 3 import requests 4 import json 5 import csv 6 import time 7 8 9 def get_token(): 10 data = { 11 "jsonrpc": "2... ......
 1 #coding:utf-8
 2 #获取zabbix上所有主机的ip和主机名
 3 import requests
 4 import json
 5 import csv
 6 import time
 7 
 8 
 9 def get_token():
10     data = {
11         "jsonrpc": "2.0",
12         "method": "user.login",
13         "params": {
14             "user": username,
15             "password": password
16         },
17         "id": 0
18     }
19     r = requests.get(zaurl, headers=header, data=json.dumps(data))
20     auth = json.loads(r.text)
21     return auth["result"]
22 
23 def gethosts(token):
24     data = {
25         "jsonrpc": "2.0",
26         "method": "host.get",
27         "params": {
28             "output": [
29                 "hostid",
30                 "host"
31             ],
32             "selectinterfaces": [
33                 "interfaceid",
34                 "ip"
35             ]
36         },
37         "id": 2,
38         "auth": token,
39 
40     }
41 
42     request = requests.post(zaurl, headers=header, data=json.dumps(data))
43     dict = json.loads(request.content)
44 #    print (dict['result'])
45     return dict['result']
46 
47 
48 if __name__ == "__main__":
49     zaurl="http://xx.xx.xx.xx/zabbix/api_jsonrpc.php"
50     header = {"content-type": "application/json"}
51     username = "xx"
52     password = "xx"
53 
54     token = get_token()
55     hostlist = gethosts(token)
56     datafile = "zabbix.txt"
57     fdata = open(datafile,'w')
58     for i in hostlist:
59         hostid = i['hostid']
60         hostip = i['host']
61         fdata.write(hostip + ' ' + hostid + '\n')
62     fdata.close()