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()