开源的Zabbix监控解决方案有一个REST API,能够与现有的监控、日志记录和警报系统进行深度集成。

这促进了社区驱动模块的开发,例如py-zabbix 模块。

安装

我们将确保 python 和 pip 安装在我们的 Ubuntu 主机上,然后使用 pip 安装 py-zabbix 模块。

$ sudo apt-get install git software-properties-common python python-pip -y

$ pip install py-zabbix

验证 Web 访问

在继续之前,请确认您可以通过浏览器访问Zabbix server,并且知道正确的凭据。

转到 URL 时,您应该会看到如下所示的登录屏幕 http://<zabbixserver>/zabbix

使用 py-zabbix 模块自动化运维 Zabbix_python

Zabbix API 自动化

读取模板-ZabbixAPI.py

#!/usr/bin/python

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

from zabbix.api import ZabbixAPI


# 参数检查
if len(sys.argv)<3:
  print "USAGE: zabbixURL user pass"
  print "EXAMPLE: http://127.0.0.1/zabbix Admin zabbix"
  sys.exit(1)

# 参数的简单解析
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
print "Going to connect to {} as {}".format(url,user)


# 创建ZabbixAPI类实例
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])


# 获取所有已启用的主机
print "----------------------------"
enabledhosts = zapi.do_request('host.get',
                          {
                              'filter': {'status': '0'},
                              'output': 'extend'
                          })
hostnames = [host['host'] for host in enabledhosts['result']]
print "All enabled hosts: {}".format(hostnames)


# 获取包含“Linux”的所有模板
print "----------------------------"
templates = zapi.do_request('template.get', {'search': { 'host':'Linux'}, 'output':'extend'})
templates = [ template['host'] for template in templates['result']  ]
print "templates with Linux in their name: {}".format(templates)


# 获取最新的 5 个触发器问题
print "----------------------------"
triggers = zapi.do_request('trigger.get', { 'min_severity':'2', 'withUnacknowledgedEvents':'true','sortfield':['priority'], 'sortorder': 'DESC', 'limit':'5', 'output':'extend' })
for trigger in triggers['result']:
  print "TRIGGER PRIORITY {}: {}".format(trigger['priority'],trigger['description'])

该测试将连接到 Zabbix,检索所有启用的主机名,查找名称中带有“Linux”的任何模板,然后向您显示最新触发器问题的列表。

$ chmod 755 ZabbixAPI.py

$ ./ZabbixAPI.py http://127.0.0.1/zabbix Admin zabbix

输出应如下所示:

Going to connect to http://127.0.0.1/zabbix as Admin
Zabbix API version: 2.4.8
----------------------------
All enabled hosts: [u'zabbix2', u'grafana', u'trusty1']
----------------------------
templates with Linux in their name: [u'Template OS Linux', u'Template SNMP OS Linux']
----------------------------
TRIGGER PRIORITY 2: Lack of free swap space on {HOST.NAME}
TRIGGER PRIORITY 2: /etc/passwd has been changed on {HOST.NAME}
TRIGGER PRIORITY 2: Lack of free swap space on {HOST.NAME}
TRIGGER PRIORITY 2: Lack of free swap space on {HOST.NAME}
TRIGGER PRIORITY 3: Zabbix agent on {HOST.NAME} is unreachable for 5 minutes

您可以看到上面报告的触发器与 Web GUI 中报告的触发器匹配。

使用 py-zabbix 模块自动化运维 Zabbix_触发器_02

ZabbixAPI.py 感兴趣的是连接到Zabbix server:

zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

然后使用正确的参数(由Zabbix API定义)构造对'host.get'方法的REST调用。

enabledhosts = zapi.do_request('host.get',
{
'filter': {'status': '0'},
'output': 'extend'
})
hostnames = [host['host'] for host in enabledhosts['result']]

然后拉取最新的触发器,再次使用“trigger.get”的 API

triggers = zapi.do_request('trigger.get', { 'min_severity':'2', 'withUnacknowledgedEvents':'true','sortfield':['priority'], 'sortorder': 'ASC', 'limit':'5', 'output':'extend' })
for trigger in triggers['result']:
 print "TRIGGER PRIORITY {}: {}".format(trigger['priority'],trigger['description'])

删除主机-zabbixdelhost.py

#!/usr/bin/python
#
#警告!!!!该操作具有一定的风险
#这将从Zabbix中完全删除主机定义
#基于通配符进行搜索,因此如果只键入前几个字符,将获得多个命中
#
#每次删除前手动提示用户
#

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

from zabbix.api import ZabbixAPI


# 参数检查
if len(sys.argv)<4:
  print("Expecting 4 arguments, only got {}".format( len(sys.argv) ))
  print "USAGE: zabbixURL user pass zabbixHostname"
  print "EXAMPLE: https://127.0.0.1/zabbix myid P4ssword myHostname"
  sys.exit(1)

# 参数的简单解析
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
zhost = sys.argv[4]
print "Going to connect to {} as {}".format(url,user)
print ("Will try to delete zabbix host {}".format(zhost))


# 创建ZabbixAPI类实例
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])

# 获取主机
print "----------------------------"
enabledhosts = zapi.do_request('host.get',
                          {
                              'search': {  'host': [zhost], 'searchWildcardsEnabled': 1   }
                          })
hostnames = [host['host'] for host in enabledhosts['result']]
print("Found candidate hosts for deletion: {}".format(hostnames))
print("")
print("")

# 只需要单主机操作
if len(hostnames)==0:
  print("No hosts match that criteria, no deletions made")
  exit(1)


for host in enabledhosts['result']:
   answer = raw_input("delete {} with id {} [y/n]".format(host['host'],host['hostid']))
   if answer == "y":
     deleteRes = zapi.do_request('host.delete',
                          [
                              host['hostid']
                          ])
     print deleteRes
     print("deleted {} with id {}".format(host['host'],host['hostid']))
   else:
     print("skipped {}".format(host['hostid']))

发送数据-zabbixsender.py

#!/usr/bin/python

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

from pyzabbix import ZabbixMetric, ZabbixSender


if len(sys.argv)<4:
  print "USAGE: zabbixServer hostId key value"
  print "EXAMPLE: 127.0.0.1 myhost mystr1 testvalue"
  sys.exit(1)


zserver = sys.argv[1]
if zserver.lower().startswith("http"):
  print "Do not prefix the zabbix server name with 'http' or 'https', just specify the hostname or IP"
  sys.exit(1)
hostId = sys.argv[2]
key = sys.argv[3]
value = sys.argv[4]
port = 10051


# 将指标发送到zabbix trapper
packet = [
  ZabbixMetric(hostId, key, value)
  # 可以在同一个调用中发送多个变量,以提高效率
  #,ZabbixMetric(hostId, 'anotherkey', 'anothervalue')
]

result = ZabbixSender(zserver,port,use_config=None).send(packet)
print result

当您将指标发送到Zabbix时,这是通过端口10051(默认情况下)完成的,并且是使用简单的二进制协议完成的。无需身份验证即可发送值。您须创建两个类型为“zabbix trapper”的自定义字段。

在 Web 界面中,选择“配置”>“主机”,然后在要试验的主机上选择“项目”,它将列出它正在监视的项目。

按“create item”,使用数据类型为“text”的“zabbix trapper”类型的名称“mystr1”,然后按“add”。然后创建另一个名称为“myint1”、类型为“zabbix trapper”、数据类型为“numeric unsigned”的项目,然后按“add”。

执行上面的zabbixsender.py代码

$ chmod 755 ZabbixSender.py

$ ./ZabbixSender.py 127.0.0.1 myhost mystr1 testvalue1
{"failed": 0, "chunk": 1, "total": 1, "processed": 1, "time": "0.000097"}

$ ./ZabbixSender.py 127.0.0.1 myhost mystr1 testvalue2
{"failed": 0, "chunk": 1, "total": 1, "processed": 1, "time": "0.000095"}

在 Web 界面中,转到“监视>最新数据”,然后按所选主机进行筛选。如果您按照上述步骤操作,您应该会看到“mystr1”字段填充了“testvalue2”。

更新主机描述-zabbixupdatedesc.py

#!/usr/bin/python
#
#更新zabbix中主机的描述
# 

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

from zabbix.api import ZabbixAPI



if len(sys.argv)<5:
  print("Expecting 5 arguments, only got {}".format( len(sys.argv) ))
  print "USAGE: zabbixURL user pass host newDescrip"
  print "EXAMPLE: http://127.0.0.1/zabbix myid P4ssword myHostname 'new-visible-name'"
  sys.exit(1)

url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
zhost = sys.argv[4]
name = sys.argv[5]
print "Going to connect to {} as {}".format(url,user)
print ("Will try to update zabbix host {} with a visible name of {}".format(zhost,name))



use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])


print "----------------------------"
enabledhosts = zapi.do_request('host.get',
                          {
                              'filter': {'host': zhost}
                          })
print enabledhosts
print ("==========")
hostnames = [host['host'] for host in enabledhosts['result']]
print "Found hosts: {}".format(hostnames)


if len(hostnames)>1:
  print("This name update is only meant for single hosts.")
  exit(1)
elif len(hostnames)==0:
  print("No hosts match that criteria, no updates made")
  exit(1)


for host in enabledhosts['result']:
   print("About to update {} with visible name {}".format(host['host'],name))
   updateRes = zapi.do_request('host.update',
                          {
                              'hostid': host['hostid'], 'host': host['host'], 'name': name 
                          })
   print updateRes