Zabbix API event.get接口间歇性失败,报JSONDecodeError
搭建了本地Zabbix监控系统,用Python调用Zabbix API时,host.get、problem.get等接口都能正常拉取数据,但event.get接口仅偶尔能正常工作导出CSV,多数时候会抛出json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)错误,捕获到请求响应返回<Response [500]>。以下是完整报错栈和代码,请求排查该接口间歇性工作及报错的原因:
报错栈
Traceback (most recent call last): File "c:\Users\lachlan.ballard\Corp Projects\MapDisplayAllScripts\eventget.py", line 9, in <module> geteventlist = r.json()['result'] File "C:\Users\lachlan.ballard\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\lachlan.ballard\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Users\lachlan.ballard\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\lachlan.ballard\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
调用代码
import requests import pandas as pd url = 'http://localzabbixhost' payload = '{"jsonrpc": "2.0", "method": "event.get", "params": {"output": "extend", "selectAcknowledges": "extend", "selectTags": "extend", "selectSuppressionData": "extend", "selectHosts": ["hostid", "host", "name"], "recent": "true", "sortorder": "DESC"}, "auth": "specialpasskey", "id": 1 }' headers = {'content-type': 'application/json-rpc'} r = requests.post(url, data=payload, headers=headers, ) geteventlist = r.json()['result'] df = pd.DataFrame(geteventlist) df = pd.json_normalize(geteventlist, record_path='hosts', meta=['eventid'], errors='ignore') df.to_csv('expandedhosts.csv') #converting the dataframe into a csv
核心原因
HTTP 500是服务器内部错误,说明Zabbix Server在处理event.get请求时偶尔出现异常,无法返回合法JSON响应,导致客户端解析失败。
具体排查方向
数据量过载
recent: "true"会拉取近期所有事件,若监控主机多、事件量大,单次请求数据可能超出Zabbix Server处理能力,触发超时或内存溢出。建议添加time_from/time_till时间范围参数缩小数据范围,或减少select*类关联查询字段,降低请求负载。Zabbix Server性能瓶颈
检查Zabbix Server的CPU、内存使用率,查看服务端日志(默认路径/var/log/zabbix/zabbix_server.log),寻找500错误对应的数据库查询超时、内存不足等报错信息。API参数格式问题
Zabbix API部分布尔参数需传入布尔值而非字符串,尝试将"recent": "true"改为"recent": true,避免服务端解析参数异常。同时确认auth令牌是否在请求间隙过期。网络与超时设置
原代码未设置请求超时,若服务端处理过慢导致连接中断,会返回空响应引发解析错误。建议在requests.post中添加timeout参数(如timeout=30),并捕获超时异常。
代码优化建议
import requests import pandas as pd import json url = 'http://localzabbixhost' # 调整参数格式、添加时间范围过滤 payload = { "jsonrpc": "2.0", "method": "event.get", "params": { "output": "extend", "selectAcknowledges": "extend", "selectTags": "extend", "selectSuppressionData": "extend", "selectHosts": ["hostid", "host", "name"], "recent": True, "sortorder": "DESC", "time_from": 1690000000 # 替换为实际起始时间戳 }, "auth": "specialpasskey", "id": 1 } headers = {'content-type': 'application/json-rpc'} try: r = requests.post(url, json=payload, headers=headers, timeout=30) r.raise_for_status() # 主动抛出HTTP错误 geteventlist = r.json()['result'] df = pd.DataFrame(geteventlist) df = pd.json_normalize(geteventlist, record_path='hosts', meta=['eventid'], errors='ignore') df.to_csv('expandedhosts.csv') except requests.exceptions.HTTPError as e: print(f"HTTP错误: {e}, 响应内容: {r.text}") except json.decoder.JSONDecodeError as e: print(f"JSON解析错误: {e}, 响应内容: {r.text}") except Exception as e: print(f"其他错误: {e}")
内容的提问来源于stack exchange,提问作者Lachlan

