#导入所需模块和库
import pandas as pd
import matplotlib.pyplot as plt
from pyzabbix import ZabbixAPI
from datetime import datetime, timedelta
#连接zabbix API
zabbix_server = 'http://ip/zabbix/api_jsonrpc.php'
zabbix_user = 'apitest'
zabbix_password = 'xxx'
zabbix = ZabbixAPI(zabbix_server)
zabbix.login(zabbix_user, zabbix_password)
# 获取当前时间并减去一个月,以计算上个月的起始和结束时间戳
now = datetime.now()
last_month_start = datetime(now.year, now.month - 1, 1)
last_month_end = datetime(now.year, now.month, 1) - timedelta(days=1)
# 获取上个月的告警事件
events = zabbix.event.get(output=['eventid', 'name', 'severity', 'hosts', 'clock'], selectHosts=['host'], time_from=last_month_start.timestamp(), time_till=last_month_end.timestamp() ,sortfield='eventid', sortorder='ASC')
# 定义一个空的pandas数据表,只包含标题
df = pd.DataFrame(columns=['EventName', 'HostName', 'HostID', 'IP_ADD'])
# 提取告警事件信息到pandas数据表df
# events是一个嵌套字典,event是一个一元字典
for event in events:
EventName = event['name']
HostName = event['hosts'][0]['host']
HostID = event['hosts'][0]['hostid']
IP_ADD = zabbix.hostinterface.get(hostids=HostID, output=['ip'])[0]['ip']
# 将'EventName', 'HostName', 'HostID', 'IP_ADD'增加到pandas数据表
df = df.append({'EventName': EventName, 'HostName': HostName, 'HostID': HostID, 'IP_ADD': IP_ADD}, ignore_index=True)
# 只输出EventName、IP_ADD
df = df[['EventName', 'IP_ADD']]
# #按照告警事件名称和IP进行分组统计
result = df.groupby(['EventName', 'IP_ADD']).size().reset_index(name='count')
# 按照告警事件的次数进行排序,然后输出报表
result = result.sort_values('count', ascending=False)
# 判断次数大于2的告警事件-->输出的是布尔值
result_filter = result['count'] > 2
# 利用上述的判断条件过滤出大于2的告警事件
new_result = result[result_filter]
print(new_result)
# 将result结果写入excel
new_result.to_excel('zabbix_month_report.xlsx', sheet_name='sheet1', index=False)