You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python调用Zabbix API输出纯净的单列站点列表

解决方案

直接在原有Zabbix API调用代码后追加数据处理逻辑即可,完整可运行代码如下:

import json
import re
from pyzabbix import ZabbixAPI

username = "user"
password = "*************"
servername = "https://<name of the site.com>/api_jsonrpc.php"

zapi = ZabbixAPI(servername)
zapi.session.verify = False
zapi.login(username, password)

hosts = zapi.host.get(
    output=["host"], groupids=[25, 41, 43], selectInventory=["site_notes"],
)

# 数据处理逻辑
valid_domains = set()
# 标准域名正则校验规则,可根据实际需求调整
domain_regex = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]\.[a-zA-Z.]{2,}$')

for host_item in hosts:
    site_notes_content = host_item.get('inventory', {}).get('site_notes', '')
    # 按换行符拆分所有条目
    for line in site_notes_content.strip().split('\n'):
        current_line = line.strip()
        # 过滤无效条目
        if not current_line: # 空行
            continue
        if current_line == '_': # 纯下划线
            continue
        if current_line.isdigit(): # 纯数字
            continue
        # 校验域名格式,匹配成功则加入去重集合
        if domain_regex.match(current_line):
            valid_domains.add(current_line)

# 逐行输出排序后的有效域名
for domain in sorted(valid_domains):
    print(domain)

逻辑说明

  • 用set集合存储域名,利用集合的特性自动完成去重
  • 逐层取值避免inventory或site_notes为空时报错
  • 先做简单无效内容过滤,再用正则校验域名格式,可过滤掉s_hash_bucket_size这类非域名的配置字段
  • 输出前做排序,方便后续查看和使用

如果不需要严格的域名格式校验,可以去掉正则匹配的逻辑,换成更简单的判断:

# 把正则匹配的部分替换为下面的代码即可
if '.' in current_line and '_' not in current_line:
    valid_domains.add(current_line)

如果你已经把API返回结果导出为了JSON文件,也可以用下面的独立脚本处理:

import json
import re

# 替换为你的JSON文件实际路径
with open('zabbix_result.json', 'r', encoding='utf-8') as f:
    hosts = json.load(f)

valid_domains = set()
domain_regex = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]\.[a-zA-Z.]{2,}$')

for host_item in hosts:
    site_notes_content = host_item.get('inventory', {}).get('site_notes', '')
    for line in site_notes_content.strip().split('\n'):
        current_line = line.strip()
        if not current_line or current_line == '_' or current_line.isdigit():
            continue
        if domain_regex.match(current_line):
            valid_domains.add(current_line)

for domain in sorted(valid_domains):
    print(domain)

内容的提问来源于stack exchange,提问作者hardr0m

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 11:51:03