zabbix问题事件统计/按月统计/生成表格/Python调用Zabbix3.4api
背景:
因业务需要,每月初需要为客户提供指定预警等级的事件,这里选择从evnet.get中进行获取。
发现的坑:
目前维护多套zabbix服务,并且版本不同.., POC进行时使用的是5.4.2, 正式环境3.4.x, 3.4版本中的event.get是没有name属性的,
最后我是通过trigger拿到的信息,但因为tigger中带着{HOST.NAME} 或 {HOST.CONN} 这块儿通过ip类的信息进行了正则替换,具体如代码,比较简单,主要是API使用思路。
目的:
获取事件名称、开始时间、 主机名称和IP信息,整理后以表格展示
调取结构图 :
代码环境:
Python3.8
代码依赖包:
pip install openpyxl
pip install pandas
pip install requests
代码:
1 import requests 2 import json 3 import pandas as pd 4 import time 5 import re 6 7 def stamp2time(timestamp): #时间戳转日期函数 8 time_local = time.localtime(int(timestamp)) 9 dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local) 10 return dt 11 12 class zabbix_api(object): 13 def __init__(self): 14 self.header = {"Content-Type": "application/json-rpc"} 15 self.url = 'https://zabbix.xxx.com.cn/zabbix/api_jsonrpc.php' 16 self.auth = self.zabbix_login() 17 18 def zabbix_login(self): 19 data = { 20 "jsonrpc": "2.0", 21 "method": "user.login", 22 "params": { 23 "user": "xxx", # zabbix登录用户名 24 "password": "xxxx" # zabbix登录密码 25 }, 26 "id": 1, 27 "auth": None, 28 } 29 return self.requestJson(data) 30 31 def getHostsip(self, hostid): 32 data = {'jsonrpc': '2.0', 33 'method': 'host.get', 34 'params': { 35 'output': ["hostid", "host", "name"], 36 'selectInterfaces': ["ip"], 37 'hostids': hostid 38 }, 39 'auth': self.auth, 40 'id': '10' 41 } 42 output = self.requestJson(data) 43 return {"hostname": output[0]['host'], "ip": output[0]['interfaces'][0]['ip']} 44 45 def getHosts(self): 46 hostsip = [] 47 data = host_data = { 48 "jsonrpc": "2.0", 49 "method": "host.get", 50 "params": {}, 51 "auth": self.auth, 52 "id": 1 53 } 54 output = self.requestJson(data) 55 for hosts in output[0:]: 56 hostsip.append(hosts['interfaces']) 57 return hostsip 58 59 def getEvents(self): 60 hostsip = [] 61 data = { 62 "jsonrpc": "2.0", 63 "method": "event.get", 64 "params": { 65 "output": ["clock"], # 输出内容, 这里原始数据只需要时间 66 "time_from": "1625760000", # 开始时间 67 "time_till": "1628438400", # 结束时间 68 "selectHosts": "extend", # 显示主机相关信息 69 "value": 1, # 只显示问题事件,不显示恢复时间(默认:都显示) 70 # "select_alerts": "extend", # 通过此参数获取次事件触发的报警信息 71 "selectRelatedObject": "extend", # 通过此参数扩展获得对应触发器信息 72 "severities": [2, 3, 4, 5], # 获取等级 73 "sortfield": ["clock", "eventid"], # 排序属性 74 "sortorder": "desc" 75 }, 76 "auth": self.auth, 77 "id": 2 78 } 79 output = self.requestJson(data) 80 return output 81 82 def getTriggers(self, triggerid): 83 data = { 84 "jsonrpc": "2.0", 85 "method": "trigger.get", 86 "params": { 87 "triggerids": triggerid, 88 "output": [ 89 "triggerid", 90 "description", 91 "name" 92 ], 93 "sortfield": "priority", 94 "sortorder": "DESC" 95 }, 96 "auth": self.auth, 97 "id": 1 98 } 99 output = self.requestJson(data) 100 return output 101 102 def requestJson(self, json_values): 103 r = json.loads(requests.post(self.url, data=json.dumps(json_values), headers=self.header).content.decode()) 104 return r["result"] 105 106 107 z = zabbix_api() 108 event_list = [] 109 print(len(z.getEvents())) 110 data_lens = 0 111 for event in z.getEvents(): 112 data_lens += 1 113 event_dict = {} 114 if event['hosts']: 115 # print(event) 116 hostid = event['hosts'][0]['hostid'] 117 event_dict['clock'] = event['clock'] 118 event_dict['hostname'] = z.getHostsip(hostid)['hostname'] 119 event_dict['ip'] = z.getHostsip(hostid)['ip'] 120 trigger_name = event['relatedObject']['description'] 121 if re.findall("{HOST.NAME}", trigger_name): 122 event_dict['name'] = trigger_name.replace("{HOST.NAME}", z.getHostsip(hostid)['hostname']) 123 elif re.findall("{HOST.CONN}", trigger_name): 124 event_dict['name'] = trigger_name.replace("{HOST.CONN}", z.getHostsip(hostid)['ip']) 125 else: 126 event_dict['name'] = trigger_name 127 print(event_dict) 128 # event_dict['name'] = event['name'] 129 event_list.append(event_dict) 130 131 df = pd.DataFrame(event_list) 132 print(df) 133 df['clock'] = df['clock'].apply(stamp2time) 134 df.to_excel("result_xlsx.xlsx", index=0)
有待改进:
- 各个参数的传递
- 事件数量过多的话,整个统计过程会非常缓慢,需要进行多线程优化
参考:
- 获取zabbix 所有的hostid
https://www.jianshu.com/p/7a8a765b5992?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
- zabbix3.4 event.get
https://www.zabbix.com/documentation/3.4/manual/api/reference/event/get
- zabbix3.4 host.get
https://www.zabbix.com/documentation/3.4/manual/api/reference/host/get
- pandas 时间戳与日期互转方法
https://zhuanlan.zhihu.com/p/138130809
- python写入数据到csv或xlsx文件的3种方法
https://www.jb51.net/article/168327.htm
- 在线时间戳转换工具
https://tool.lu/timestamp/