文章目录
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aa4f375dc005324be94828c5a0af2475.png)
1.zabbix监控平台主机确认
当前已有监控主机11台
http://server_ip/zabbix/api_jsonrpc.php: zabbix的api接口
使用grafana展示也是调用api接口获取数据展示图形
2.Python环境配置
3.Python编写调用api脚本
Python语言编写调用脚本
python 调用zabbix api实现查询主机信息,输出所有主机ip及hostid
#获取zabbix上所有主机的IP和主机名
#coding:utf-8
import requests
import json
import csv
import time
def get_token():
data = {
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": username,
"password": password
},
"id": 0
}
r = requests.get(zaurl, headers=header, data=json.dumps(data))
auth = json.loads(r.text)
return auth["result"]
def getHosts(token):
data = {
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 2,
"auth": token,
}
request = requests.post(zaurl, headers=header, data=json.dumps(data))
dict = json.loads(request.content)
print (dict['result'])
return dict['result']
if __name__ == "__main__":
zaurl="http://192.168.1.150/zabbix/api_jsonrpc.php"
header = {
"Content-Type": "application/json"}
username = "Admin"
password = "zabbix"
token = get_token()
hostlist = getHosts(token)
datafile = "zabbix_host_improt.cvs"
fdata = open(datafile,'w')
for i in hostlist:
hostid = i['hostid']
hostip = i['host']
fdata.write(hostip + ' ' + hostid + '\n')
fdata.close()
导出主机信息
shell> cat zabbix_host_improt.cvs
Zabbix server 10084
192.168.1.50 10435
aecf4d56-ddcd-7eef-b4ee-814af6201ef4 10440
564de793-f192-f439-f242-34e6a043f5dc 10441
sql server 10442
sql server1 10443
mssql02 10444
Test00 10462
Test01 10463
DESKTOP-GNKABFC 10464
nightingale 10465
4.使用zabbix的api接口调用zabbix监控主机
将zabbix_base.py脚本与zabbix_ip.py脚本放在同一个目录下,直接执行zabbix_ip.py即可,具体脚本如下所示
[root@server ~]# mkdir zabbix_host
[root@server ~]# cd zabbix_host
[root@server ~/zabbix_host]# vim zabbix_base.py
[root@server ~/zabbix_host]# vim zabbix_ip.py
[root@server ~/zabbix_host]# python3 zabbix_ip.py #执行以下脚本即可
11 #导出zabbix上的主机数量
[root@server ~/zabbix_host]# cat zabbix_ip_improt.cvs #查看导出数据
127.0.0.1 Zabbix server
192.168.1.50 192.168.1.50
192.168.1.50 aecf4d56-ddcd-7eef-b4ee-814af6201ef4
192.168.1.50 564de793-f192-f439-f242-34e6a043f5dc
sql server
192.168.1.5 sql server1
127.0.0.1 mssql02
114.114.114.114 Test00
114.114.114.115 Test01
192.168.1.1 DESKTOP-GNKABFC
192.168.1.3 nightingale
[root@server ~/zabbix_host]#
基础api接口脚本编写
shell> vi