问题描述:
知名企业A公司的运维人员小智,需要对zabbix发生的告警数量进行统计。
解决方案:
1、数据库查询方案,调整时间范围即可查询告警相应数据:
查询最近30天zabbix告警数据
SELECT
a.hostid ,
a.`host`,
a.`name` AS hostnname,
b.`name` AS groupname,
FROM_UNIXTIME( e.clock ) AS eventtime,
e.`name`,
e.severity
FROM
hosts a
JOIN hosts_groups c ON a.hostid = c.hostid
JOIN hstgrp b ON b.groupid = c.groupid
AND b.NAME LIKE '%***%'
JOIN items d ON a.hostid = d.hostid
AND d.flags <> 1
AND d.flags <> 2
JOIN ( SELECT itemid, triggerid FROM functions GROUP BY itemid, triggerid ) f ON d.itemid = f.itemid
JOIN events e ON f.triggerid = e.objectid
AND e.`value` = 1
AND e.clock in (select e.clock from events e where TIMESTAMPDIFF(day,from_unixtime(e.clock,'%Y-%m-%d'),current_date)<30)
ORDER BY e.clock
2、使用zabbix api获取
import requests
import json
from datetime import datetime
# Zabbix API相关信息
zabbix_url = 'http://your-zabbix-server/zabbix/api_jsonrpc.php'
zabbix_username = 'your_username'
zabbix_password = 'your_password'
# 登录Zabbix并获取认证令牌
def zabbix_login():
data = {
'jsonrpc': '2.0',
'method': 'user.login',
'params': {
'user': zabbix_username,
'password': zabbix_password,
},
'id': 1,
}
response = requests.post(zabbix_url, json=data, headers={'Content-Type': 'application/json'})
result = response.json()
if 'result' in result:
return result['result']
else:
raise Exception("Zabbix login failed")
# 获取指定日期范围内的告警数量
def get_alert_count(start_date, end_date):
token = zabbix_login()
data = {
'jsonrpc': '2.0',
'method': 'alert.get',
'params': {
'output': 'extend',
'time_from': datetime.strptime(start_date, '%Y-%m-%d').timestamp(),
'time_till': datetime.strptime(end_date, '%Y-%m-%d').timestamp(),
'selectAcknowledges': 'extend',
'sortfield': 'clock',
'sortorder': 'DESC',
},
'auth': token,
'id': 2,
}
response = requests.post(zabbix_url, json=data, headers={'Content-Type': 'application/json'})
#查询数据在此
result = response.json()
if 'result' in result:
return len(result['result'])
else:
raise Exception("Failed to retrieve alert count")
# 指定日期范围
start_date = '2024-01-01'
end_date = '2024-01-10'
# 获取告警数量
alert_count = get_alert_count(start_date, end_date)
print(f"Alert count from {start_date} to {end_date}: {alert_count}")
请确保替换代码中的以下值:
‘http://your-zabbix-server/zabbix/api_jsonrpc.php’:Zabbix服务器的API URL。
‘your_username’:用于登录Zabbix的用户名。
‘your_password’:用于登录Zabbix的密码。
此代码登录到Zabbix,获取认证令牌,然后使用alert.get方法获取指定日期范围内的告警数量。注意,Zabbix的API调用可能会受到Zabbix服务器配置和权限的影响,确保用户具有足够的权限执行相应的API调用。