zabbix
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseZabbix Automation Skill
Zabbix自动化技能
Overview
概述
This skill provides guidance for automating Zabbix monitoring operations via the API and official Python library .
zabbix_utils本技能提供了通过API和官方Python库实现Zabbix监控操作自动化的指导。
zabbix_utilsQuick Start
快速开始
Installation
安装
bash
pip install zabbix-utils --break-system-packagesbash
pip install zabbix-utils --break-system-packagesAuthentication
身份验证
python
from zabbix_utils import ZabbixAPIpython
from zabbix_utils import ZabbixAPIOption 1: Username/password
Option 1: Username/password
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(user="Admin", password="zabbix")
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(user="Admin", password="zabbix")
Option 2: API token (Zabbix 5.4+, preferred)
Option 2: API token (Zabbix 5.4+, preferred)
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(token="your_api_token")
api = ZabbixAPI(url="https://zabbix.example.com")
api.login(token="your_api_token")
Verify connection
Verify connection
print(api.api_version())
undefinedprint(api.api_version())
undefinedEnvironment Variables Pattern
环境变量模式
python
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"])python
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"])Core API Methods
核心API方法
All APIs follow pattern: with methods: , , , .
api.<object>.<method>()getcreateupdatedelete所有API遵循以下模式:,支持的方法包括:、、、。
api.<对象>.<方法>()getcreateupdatedeleteHost Operations
主机操作
python
undefinedpython
undefinedGet hosts
Get hosts
hosts = api.host.get(output=["hostid", "host", "name"],
selectInterfaces=["ip"])
hosts = api.host.get(output=["hostid", "host", "name"],
selectInterfaces=["ip"])
Create host
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"}]
)
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
Update host
api.host.update(hostid="10084", status=0) # 0=enabled, 1=disabled
api.host.update(hostid="10084", status=0) # 0=enabled, 1=disabled
Delete host
Delete host
api.host.delete("10084")
undefinedapi.host.delete("10084")
undefinedTemplate Operations
模板操作
python
undefinedpython
undefinedGet templates
Get templates
templates = api.template.get(output=["templateid", "host", "name"],
selectHosts=["hostid", "name"])
templates = api.template.get(output=["templateid", "host", "name"],
selectHosts=["hostid", "name"])
Link template to host
Link template to host
api.host.update(hostid="10084",
templates=[{"templateid": "10001"}])
api.host.update(hostid="10084",
templates=[{"templateid": "10001"}])
Import template from XML
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}
}
)
undefinedwith 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}
}
)
undefinedItem Operations
监控项操作
python
undefinedpython
undefinedGet items
Get items
items = api.item.get(hostids="10084",
output=["itemid", "name", "key_"],
search={"key_": "system.cpu"})
items = api.item.get(hostids="10084",
output=["itemid", "name", "key_"],
search={"key_": "system.cpu"})
Create item
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"
)
undefinedapi.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"
)
undefinedTrigger Operations
触发器操作
python
undefinedpython
undefinedGet triggers
Get triggers
triggers = api.trigger.get(hostids="10084",
output=["triggerid", "description", "priority"],
selectFunctions="extend")
triggers = api.trigger.get(hostids="10084",
output=["triggerid", "description", "priority"],
selectFunctions="extend")
Create trigger
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
)
undefinedapi.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
)
undefinedHost Group Operations
主机组操作
python
undefinedpython
undefinedGet groups
Get groups
groups = api.hostgroup.get(output=["groupid", "name"])
groups = api.hostgroup.get(output=["groupid", "name"])
Create group
Create group
api.hostgroup.create(name="Production/Web Servers")
api.hostgroup.create(name="Production/Web Servers")
Add hosts to group
Add hosts to group
api.hostgroup.massadd(groups=[{"groupid": "5"}],
hosts=[{"hostid": "10084"}])
undefinedapi.hostgroup.massadd(groups=[{"groupid": "5"}],
hosts=[{"hostid": "10084"}])
undefinedMaintenance Windows
维护窗口
python
import timepython
import timeCreate maintenance
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
}]
)
undefinedapi.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
}]
)
undefinedEvents and Problems
事件与问题
python
undefinedpython
undefinedGet current problems
Get current problems
problems = api.problem.get(output=["eventid", "name", "severity"],
recent=True)
problems = api.problem.get(output=["eventid", "name", "severity"],
recent=True)
Get events
Get events
events = api.event.get(hostids="10084",
time_from=int(time.time()) - 86400,
output="extend")
undefinedevents = api.event.get(hostids="10084",
time_from=int(time.time()) - 86400,
output="extend")
undefinedHistory Data
历史数据
python
undefinedpython
undefinedGet history (value_type must match item's value_type)
Get history (value_type must match item's value_type)
0=float, 1=character, 2=log, 3=integer, 4=text
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"
)
undefinedhistory = api.history.get(
itemids="28269",
history=0, # float
time_from=int(time.time()) - 3600,
output="extend",
sortfield="clock",
sortorder="DESC"
)
undefinedZabbix Sender (Trapper Items)
Zabbix Sender(Trapper监控项)
python
from zabbix_utils import Sender
sender = Sender(server="zabbix.example.com", port=10051)python
from zabbix_utils import Sender
sender = Sender(server="zabbix.example.com", port=10051)Send single value
Send single value
response = sender.send_value("hostname", "trap.key", "value123")
print(response) # {"processed": 1, "failed": 0, "total": 1}
response = sender.send_value("hostname", "trap.key", "value123")
print(response) # {"processed": 1, "failed": 0, "total": 1}
Send multiple values
Send multiple values
from zabbix_utils import ItemValue
values = [
ItemValue("host1", "key1", "value1"),
ItemValue("host2", "key2", 42),
]
response = sender.send(values)
undefinedfrom zabbix_utils import ItemValue
values = [
ItemValue("host1", "key1", "value1"),
ItemValue("host2", "key2", 42),
]
response = sender.send(values)
undefinedZabbix Getter (Agent Query)
Zabbix Getter(Agent查询)
python
from zabbix_utils import Getter
agent = Getter(host="192.168.1.100", port=10050)
response = agent.get("system.uname")
print(response.value)python
from zabbix_utils import Getter
agent = Getter(host="192.168.1.100", port=10050)
response = agent.get("system.uname")
print(response.value)Common Patterns
常见模式
Bulk Host Creation from CSV
从CSV批量创建主机
python
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}")python
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}")Find Hosts Without Template
查找未关联模板的主机
python
undefinedpython
undefinedGet all hosts
Get all hosts
all_hosts = api.host.get(output=["hostid", "host"],
selectParentTemplates=["templateid"])
all_hosts = api.host.get(output=["hostid", "host"],
selectParentTemplates=["templateid"])
Filter hosts without specific template
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", []))]
undefinedtemplate_id = "10001"
hosts_without = [h for h in all_hosts
if not any(t["templateid"] == template_id
for t in h.get("parentTemplates", []))]
undefinedDisable Triggers by Pattern
按模式禁用触发器
python
triggers = api.trigger.get(
search={"description": "test"},
output=["triggerid"]
)
for t in triggers:
api.trigger.update(triggerid=t["triggerid"], status=1) # 1=disabledpython
triggers = api.trigger.get(
search={"description": "test"},
output=["triggerid"]
)
for t in triggers:
api.trigger.update(triggerid=t["triggerid"], status=1) # 1=disabledItem Types Reference
监控项类型参考
| Type | Value | Description |
|---|---|---|
| Zabbix agent | 0 | Active checks |
| Zabbix trapper | 2 | Passive, data pushed via sender |
| Simple check | 3 | ICMP, TCP, etc. |
| Zabbix internal | 5 | Server internal metrics |
| Zabbix agent (active) | 7 | Agent-initiated |
| HTTP agent | 19 | HTTP/REST API monitoring |
| Dependent item | 18 | Derived from master item |
| Script | 21 | Custom scripts |
| 类型 | 值 | 描述 |
|---|---|---|
| Zabbix agent | 0 | 主动检查 |
| Zabbix trapper | 2 | 被动模式,通过sender推送数据 |
| Simple check | 3 | ICMP、TCP等 |
| Zabbix internal | 5 | 服务器内部指标 |
| Zabbix agent (active) | 7 | Agent主动发起 |
| HTTP agent | 19 | HTTP/REST API监控 |
| Dependent item | 18 | 从主监控项派生 |
| Script | 21 | 自定义脚本 |
Value Types Reference
值类型参考
| Type | Value | Description |
|---|---|---|
| Float | 0 | Numeric (float) |
| Character | 1 | Character string |
| Log | 2 | Log file |
| Unsigned | 3 | Numeric (integer) |
| Text | 4 | Text |
| 类型 | 值 | 描述 |
|---|---|---|
| Float | 0 | 数值(浮点型) |
| Character | 1 | 字符串 |
| Log | 2 | 日志文件 |
| Unsigned | 3 | 数值(整数) |
| Text | 4 | 文本 |
Trigger Severity Reference
触发器严重级别参考
| Severity | Value | Color |
|---|---|---|
| Not classified | 0 | Gray |
| Information | 1 | Light blue |
| Warning | 2 | Yellow |
| Average | 3 | Orange |
| High | 4 | Light red |
| Disaster | 5 | Red |
| 严重级别 | 值 | 颜色 |
|---|---|---|
| Not classified | 0 | 灰色 |
| Information | 1 | 浅蓝色 |
| Warning | 2 | 黄色 |
| Average | 3 | 橙色 |
| High | 4 | 浅红色 |
| Disaster | 5 | 红色 |
Error Handling
错误处理
python
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}")python
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}")Debugging
调试
python
import logging
logging.basicConfig(level=logging.DEBUG)python
import logging
logging.basicConfig(level=logging.DEBUG)Now all API calls will be logged
Now all API calls will be logged
undefinedundefinedScripts Reference
脚本参考
See directory for ready-to-use automation:
scripts/- - Bulk host management from CSV
zabbix-bulk-hosts.py - - Create/manage maintenance windows
zabbix-maintenance.py - - Export hosts/templates to JSON/XML
zabbix-export.py
查看目录获取可直接使用的自动化脚本:
scripts/- - 从CSV批量管理主机
zabbix-bulk-hosts.py - - 创建/管理维护窗口
zabbix-maintenance.py - - 将主机/模板导出为JSON/XML
zabbix-export.py
Best Practices
最佳实践
- Use API tokens over username/password when possible
- Limit output fields - Always specify instead of
output=["field1", "field2"]output="extend" - Use search/filter - Never fetch all objects and filter in Python
- Handle pagination - Large result sets may need and
limitoffset - Batch operations - Use ,
massaddfor bulk changesmassupdate - Error handling - Always wrap API calls in try/except
- Idempotency - Check if object exists before creating
- 优先使用API令牌:尽可能使用API令牌而非用户名/密码
- 限制输出字段:始终指定而非
output=["field1", "field2"]output="extend" - 使用搜索/过滤:切勿获取所有对象后在Python中过滤
- 处理分页:大型结果集可能需要使用和
limitoffset - 批量操作:使用、
massadd执行批量变更massupdate - 错误处理:始终将API调用包裹在try/except块中
- 幂等性:创建对象前先检查其是否已存在