[原创] Pyzabbix 接口使用

pyzabbix 接口使用

pyzabbix github 地址: https://github.com/lukecyca/pyzabbix

zabbix 官方接口: https://www.zabbix.com/documentation/4.0/zh/manual/api


模块说明:直接调用 zabbix 的函数集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from pyzabbix import ZabbixAPI
from zabbixApi.api.constP import ZABBIX_SERVER, USER, PASSWD
"""
模块说明:直接调用zabbix的函数集合
"""

def loginZabbix():
'''登陆zabbix,返回登陆对象'''
user = ZabbixAPI(ZABBIX_SERVER)
user.login(USER, PASSWD)
return user

def hostAllInfo(user, host_name):
'''根据主机名,返回该主机的所有信息'''
host = user.host.get(search={"name": host_name}, output="extend")
if len(host) != 0:
return host
else:
return None

def hostIdInfo(user, host_name):
'''根据主机名,返回该主机id'''
host_id = user.host.get(search={"name": host_name}, output=["hostid"])
if len(host_id) != 0:
return host_id[0]["hostid"]
else:
return None

def hostItemAllInfo(user, host_name, item):
'''根据主机名和监控key,返回该监控项的数据'''
item = user.item.get(host=host_name, search={"key_": item}, output="extend")
if len(item) != 0:
return item
else:
return None

def hostItemIdInfo(user, host_name, item):
'''根据主机名和监控key,返回该监控项的数据'''
item_id = user.item.get(host=host_name, search={"key_": item}, output=["itemid"])
if len(item_id) != 0:
return item_id[0]["itemid"]
else:
return None

def timeProblemAllInfo(user, time_from):
'''获取某个时间点后面产生的告警问题'''
# problem.get的time_from用的是"YY-MM-DD HH:MM:SS"
return user.problem.get(time_from=time_from, output="extend")

def hostTimeProblemAllInfo(user, host_name, time_from):
'''查找某主机在某个时间点后面产生点告警问题'''
# problem.get的time_from用的是"YY-MM-DD HH:MM:SS"
host_id = hostIdInfo(user, host_name)
if host_id != None:
return user.problem.get(hostids=host_id, time_from=time_from, output="extend")
else:
return "该主机已被删除"

def timeAlertAllInfo(user, time_from):
'''获取某个时间点后面产生点告警问题'''
alert = user.alert.get(time_from=time_from, output="extend")
if len(alert) != 0:
return alert
else:
return None

def hostTimeAlertAllInfo(user, host_name, time_from):
'''查找某主机在某个时间点后面产生点告警问题'''
# alert.get的time_from用的是时间戳(1586012065)格式!!!
host_id = hostIdInfo(user, host_name)
if host_id != None:
return user.alert.get(hostids=host_id, time_from=time_from, output="extend")
else:
return "该主机已不存在"

def hostTimeHistoryInfo(user, host_name, item, time_from):
'''获取某主机点某个监控项在某个时间点后产生点历史数据'''
# history.get的time_from用的是时间戳(1586012065)格式!!!
host_id = hostIdInfo(user, host_name)
item_id = hostItemIdInfo(user, host_name, item)
if host_id != None and item_id != None:
return user.history.get(hostids=host_id, itemids=item_id, time_from=time_from)
else:
return "该主机活监控项不存在"

实例 :打印监控信息并生成 xls 表格

我研究了一下,自己写了一个用 pyzabbix 打印监控信息并生成 xls 表格的功能。现丑了,随便看看吧~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3
# Author: 思想就是武器 blog.zealot.top
# Mail: 18976787@qq.com
from pyzabbix import ZabbixAPI
import sys
import json
from re import compile,IGNORECASE
from openpyxl import Workbook
ZABBIX_SERVER = "http://x.x.x.x/zabbix"
USER = ""
PASSWORD = ""
#URL="163网址:http://www.163.com"
#URL1=URL.split(':',1)[1]

def login(ZABBIX_SERVER,USER,PASSWORD):
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.login(USER,PASSWORD)
return zapi

def itemid(auth,host_ip,item):
item = auth.item.get(host=host_ip, search={"key_": item}, output="extend")
if len(item) != 0:
print (item)
return item[0]["lastvalue"]
else:
return None

def host_names(auth,host_ip):
item = auth.item.get(host=host_ip, search={"key_": "system.uname"}, output="extend")
item1 = auth.item.get(host=host_ip, search={"key_": "system.sw.os"}, output="extend")
try:
if len(item) != 0:
host_name = item[0]["lastvalue"].split(' ')[1]
host_type = item[0]["lastvalue"].split(' ')[0]
if host_type == "Linux":
host_ver = item1[0]["lastvalue"]
else:
host_ver = item[0]["lastvalue"].split(' ',maxsplit=3)[3]
return host_name,host_type,host_ver
else:
return None
except IndexError:
print (host_ip,"未获取到主机名")
return "","",""


def disk(auth,host_ip):
b=0
a=auth.item.get(host=host_ip, search={"key_": "vfs.fs.size"}, output="extend")
c=["C","D","E","F","G","H","I","J","K","/","/home","/data","/boot","/var"]
d=0
e=0
for x in a:
# print (x["key_"])
for y in c:
if x["key_"]=="vfs.fs.size["+y+":,total]":
b=b+int(x["lastvalue"])
elif x["key_"]=="vfs.fs.size["+y+",total]":
b=b+int(x["lastvalue"])
elif x["key_"]=="vfs.fs.size["+y+":,free]":
d=d+int(x["lastvalue"])
elif x["key_"]=="vfs.fs.size["+y+",free]":
d=d+int(x["lastvalue"])
elif x["key_"]=="vfs.fs.size["+y+":,used]":
e=e+int(x["lastvalue"])
elif x["key_"]=="vfs.fs.size["+y+",used]":
e=e+int(x["lastvalue"])
return b,d,e

def bytes_to_human(n):
symbols = ('KB','MB','GB','TB','PB','EB','ZB','YB')
prefix = {
}
for i,s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value,s)
return '%sB' % n



auth = login(ZABBIX_SERVER,USER,PASSWORD)
wb = Workbook()
sheet = wb.active
sheet.cell(1,1).value = "IP地址"
sheet.cell(1,2).value = "主机名"
sheet.cell(1,3).value = "操作系统"
sheet.cell(1,4).value = "操作系统版本"
sheet.cell(1,5).value = "cpu核心数"
sheet.cell(1,6).value = "CPU使用率"
sheet.cell(1,7).value = "总内存"
sheet.cell(1,8).value = "内存使用率"
sheet.cell(1,9).value = "总硬盘容量"
sheet.cell(1,10).value = "硬盘剩余容量"
sheet.cell(1,11).value = "硬盘使用容量"
sheet.cell(1,12).value = "硬盘使用率"
sheet.cell(1,13).value = "备注"
with open('./desktop/checkip.txt','r') as f:
for index,value in enumerate(f.readlines()):
# host_list = auth.host.get(output="extend") #获取主机信息
# print (auth.hostgroup.get()) #获取zabbix分组信息
# print (auth.apiinfo.version()) #获取ZABBIX API版本
# print (auth.host.get(search={"host": "10.160.1.50"}, output=["hostid"])) # 返回主机名为10.160.1.50的HOSTID号
host_ip = value.strip()
print (host_ip)
cpu_num = itemid(auth,host_ip,"system.cpu.num")
print (cpu_num)
if cpu_num == None or cpu_num == "0":
sheet.cell(index+2,1).value = host_ip
if cpu_num == None:
sheet.cell(index+2,13).value = "ZABBIX中没有这台主机"
else:
sheet.cell(index+2,13).value = "ZABBIX中已禁用或这台主机已离线"
continue
print (cpu_num)
memory=itemid(auth,host_ip,"vm.memory.size[total]")
print (memory)
memusd=itemid(auth,host_ip,"vm.memory.size[pused]")
print (memusd)
cpu_use=itemid(auth,host_ip,"system.cpu.util")
host_name=itemid(auth,host_ip,"system.uname")
totile,shenyu,used=disk(auth,host_ip)
host_name,host_type,host_ver = host_names(auth,host_ip)
if totile == 0:
z = 0
else:
z = '%.2f'%(used/totile)
sheet.cell(index+2,1).value = host_ip
sheet.cell(index+2,5).value = cpu_num + "核"
sheet.cell(index+2,6).value = cpu_use + "%"
sheet.cell(index+2,7).value = bytes_to_human(int(memory))
sheet.cell(index+2,8).value = memusd
sheet.cell(index+2,9).value = bytes_to_human(totile)
sheet.cell(index+2,10).value = bytes_to_human(shenyu)
sheet.cell(index+2,11).value = bytes_to_human(used)
sheet.cell(index+2,12).value = z
sheet.cell(index+2,2).value = host_name
sheet.cell(index+2,3).value = host_type
sheet.cell(index+2,4).value = host_ver
# except IndexError:
# print (host_ip,"未获取到主机名")
# print (host_ip + " CPU:" + str(cpu_num) + "核" + " CPU使用率:" + str(cpu_use) + "% 总内存:" + str(bytes_to_human(int(memory))) + " 硬盘大小:" + str(bytes_to_human(totile)) + " 剩余空间:" + str(bytes_to_human(used)))
wb.save('./desktop/zabbix.xlsx')
  • 生成的 xls 文件效果