mcpField
Z
zabbix

zabbix

github.com/julianobarbosa云与 DevOps14141 次安装2 天前更新
代码仓库

关于 zabbix

zabbix 是用于通过 Zabbix API 和官方 Python 库 zabbix_utils 自动化监控操作的技能,面向管理 Zabbix 环境的开发者和运维人员。内容包括资源管理、监控数据查询及批量操作示例。

主要功能

  1. 01通过 zabbix_utils 调用 API
  2. 02管理主机、模板和监控项
  3. 03管理触发器、主机组与维护窗口
  4. 04查询问题、事件和历史数据
  5. 05使用 Sender 推送数据
  6. 06提供批量管理脚本示例

适用场景

  1. 01从 CSV 批量创建主机
  2. 02为主机查找或关联模板
  3. 03创建维护窗口并检查问题
  4. 04导出主机或模板数据

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/julianobarbosa/claude-code-skills --skill zabbix

安装后在 Claude Code 中输入/zabbix确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE.txt
references/
api-reference.md
trigger-expressions.md
scripts/
zabbix-bulk-hosts.py
zabbix-export.py
zabbix-maintenance.py
zabbix-status.py

详细介绍

Zabbix 自动化技能

概述

本技能介绍如何通过 API 和官方 Python 库 zabbix_utils 自动执行 Zabbix 监控操作。

快速开始

安装
pip install zabbix-utils --break-system-packages
身份验证
from zabbix_utils import ZabbixAPI

# Option 1: Username/password
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(user="Admin", password="zabbix")

# Option 2: API token (Zabbix 5.4+, preferred)
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(token="your_api_token")

# Verify connection
print(api.api_version())
环境变量模式
import os
from zabbix_utils import ZabbixAPI

api = ZabbixAPI(url=os.environ.get("ZABBIX_URL", "http://localhost/zabbix"))
api.login(token=os.environ["ZABBIX_TOKEN"])

核心 API 方法

所有 API 均遵循以下模式:api.<object>.<method>(),方法包括:get、create、update、delete。

主机操作
# Get hosts
hosts = api.host.get(output=["hostid", "host", "name"],
                     selectInterfaces=["ip"])

# Create host
api.host.create(
    host="server01",
    groups=[{"groupid": "2"}],  # Linux servers
    interfaces=[{
        "type": 1,  # 1=agent, 2=SNMP, 3=IPMI, 4=JMX
        "main": 1,
        "useip": 1,
        "ip": "192.168.1.100",
        "dns": "",
        "port": "10050"
    }],
    templates=[{"templateid": "10001"}]
)

# Update host
api.host.update(hostid="10084", status=0)  # 0=enabled, 1=disabled

# Delete host
api.host.delete("10084")
模板操作
# Get templates
templates = api.template.get(output=["templateid", "host", "name"],
                             selectHosts=["hostid", "name"])

# Link template to host
api.host.update(hostid="10084",
                templates=[{"templateid": "10001"}])

# Import template from XML
with open("template.xml") as f:
    api.configuration.import_(
        source=f.read(),
        format="xml",
        rules={
            "templates": {"createMissing": True, "updateExisting": True},
            "items": {"createMissing": True, "updateExisting": True},
            "triggers": {"createMissing": True, "updateExisting": True}
        }
    )
监控项操作
# Get items
items = api.item.get(hostids="10084",
                     output=["itemid", "name", "key_"],
                     search={"key_": "system.cpu"})

# Create item
api.item.create(
    name="CPU Load",
    key_="system.cpu.load[percpu,avg1]",
    hostid="10084",
    type=0,  # 0=Zabbix agent
    value_type=0,  # 0=float, 3=integer, 4=text
    delay="30s",
    interfaceid="1"
)
触发器操作
# Get triggers
triggers = api.trigger.get(hostids="10084",
                          output=["triggerid", "description", "priority"],
                          selectFunctions="extend")

# Create trigger
api.trigger.create(
    description="High CPU on {HOST.NAME}",
    expression="last(/server01/system.cpu.load[percpu,avg1])>5",
    priority=3  # 0=not classified, 1=info, 2=warning, 3=average, 4=high, 5=disaster
)
主机组操作
# Get groups
groups = api.hostgroup.get(output=["groupid", "name"])

# Create group
api.hostgroup.create(name="Production/Web Servers")

# Add hosts to group
api.hostgroup.massadd(groups=[{"groupid": "5"}],
                      hosts=[{"hostid": "10084"}])
维护时段
import time

# Create maintenance
api.maintenance.create(
    name="Server Maintenance",
    active_since=int(time.time()),
    active_till=int(time.time()) + 3600,  # 1 hour
    hostids=["10084"],
    timeperiods=[{
        "timeperiod_type": 0,  # One-time
        "period": 3600
    }]
)
事件和问题
# Get current problems
problems = api.problem.get(output=["eventid", "name", "severity"],
                          recent=True)

# Get events
events = api.event.get(hostids="10084",
                       time_from=int(time.time()) - 86400,
                       output="extend")
历史数据
# Get history (value_type must match item's value_type)
# 0=float, 1=character, 2=log, 3=integer, 4=text
history = api.history.get(
    itemids="28269",
    history=0,  # float
    time_from=int(time.time()) - 3600,
    output="extend",
    sortfield="clock",
    sortorder="DESC"
)

Zabbix Sender(Trapper 监控项)

from zabbix_utils import Sender

sender = Sender(server="zabbix.example.com", port=10051)

# Send single value
response = sender.send_value("hostname", "trap.key", "value123")
print(response)  # {"processed": 1, "failed": 0, "total": 1}

# Send multiple values
from zabbix_utils import ItemValue
values = [
    ItemValue("host1", "key1", "value1"),
    ItemValue("host2", "key2", 42),
]
response = sender.send(values)

Zabbix Getter(Agent 查询)

from zabbix_utils import Getter

agent = Getter(host="192.168.1.100", port=10050)
response = agent.get("system.uname")
print(response.value)

常见模式

从 CSV 批量创建主机
import csv
from zabbix_utils import ZabbixAPI

api = ZabbixAPI(url="https://zabbix.example.com")
api.login(token="your_token")

with open("hosts.csv") as f:
    for row in csv.DictReader(f):
        try:
            api.host.create(
                host=row["hostname"],
                groups=[{"groupid": row["groupid"]}],
                interfaces=[{
                    "type": 1, "main": 1, "useip": 1,
                    "ip": row["ip"], "dns": "", "port": "10050"
                }]
            )
            print(f"Created: {row['hostname']}")
        except Exception as e:
            print(f"Failed {row['hostname']}: {e}")
查找未关联模板的主机
# Get all hosts
all_hosts = api.host.get(output=["hostid", "host"],
                         selectParentTemplates=["templateid"])

# Filter hosts without specific template
template_id = "10001"
hosts_without = [h for h in all_hosts
                 if not any(t["templateid"] == template_id
                           for t in h.get("parentTemplates", []))]
按模式禁用触发器
triggers = api.trigger.get(
    search={"description": "test"},
    output=["triggerid"]
)
for t in triggers:
    api.trigger.update(triggerid=t["triggerid"], status=1)  # 1=disabled

监控项类型参考

类型值描述
Zabbix agent0主动检查
Zabbix trapper2被动,通过 sender 推送数据
简单检查3ICMP、TCP 等
Zabbix internal5服务端内部指标
Zabbix agent(主动)7由 Agent 发起
HTTP agent19HTTP/REST API 监控
依赖监控项18从主监控项派生
脚本21自定义脚本

值类型参考

类型值描述
浮点数0数值(浮点数)
字符1字符串
日志2日志文件
无符号整数3数值(整数)
文本4文本

触发器严重性参考

严重性值颜色
未分类0灰色
信息1浅蓝色
警告2黄色
一般3橙色
严重4浅红色
灾难5红色

错误处理

from zabbix_utils import ZabbixAPI
from zabbix_utils.exceptions import APIRequestError

try:
    api.host.create(host="duplicate_host", groups=[{"groupid": "2"}])
except APIRequestError as e:
    print(f"API Error: {e.message}")
    print(f"Code: {e.code}")

调试

import logging
logging.basicConfig(level=logging.DEBUG)
# Now all API calls will be logged

脚本参考

可在 scripts/ 目录中找到可直接使用的自动化脚本:

  • zabbix-bulk-hosts.py - 从 CSV 批量管理主机
  • zabbix-maintenance.py - 创建/管理维护时段
  • zabbix-export.py - 将主机/模板导出为 JSON/XML

最佳实践

  1. 尽可能使用 API 令牌,而非用户名/密码
  2. 限制输出字段——始终指定 output=["field1", "field2"],而不是 output="extend"
  3. 使用搜索/筛选——切勿获取所有对象后再用 Python 筛选
  4. 处理分页——大型结果集可能需要 limit 和 offset
  5. 批量操作——批量更改时使用 massadd、massupdate
  6. 错误处理——始终使用 try/except 包装 API 调用
  7. 幂等性——创建对象前检查对象是否已存在

评论

支持 Markdown