公司需要监控一批web场景,并在访问时状态码不等于200的时候告警
url的格式为http://xxx.com:1234/selfupdate
本次使用zabbix API的接口去实现
zabbix 5.0 API地址 传送门
代码如下
【因本次监控不要求网页的文本内容,故代码中没体现。如有需要可以在steps中添加required属性及相应的值】
# -*- coding: utf-8 -*-
# @File : utils.py
from pyzabbix import ZabbixAPI, ZabbixAPIException
import sys,time,datetime
class Zabbix(object):
def __init__(self):
ZABBIX_SERVER = 'http://XXXX.COM/zabbix'
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.login('XXXX', 'XXXX')
self.zapi = zapi
def logout_2(self):
zapi.logout()
def get_templates(self, name):
# 获取模板信息
templates = self.zapi.template.get(
output="templateid",
filter={
"name": name
}
)
return templates
def create_web(self,url, hostid=10935): ##批量添加web场景,在id为10935的模板上监控,并且添加触发器。上面的get_templates并没有体现巨大作用
name=' '.join(url.split('/')[2:]).replace(' ','-') ##拆分url,只获取url的域名+端口
steps=[{"name":name,"url":url,"status_codes":"200","no":1}]##步骤,如有需要,可用设置多个步骤.
print(name)
print(steps)
try:
item = self.zapi.httptest.create(
name=name, ##场景的名字
hostid=hostid, ##所在模板或主机
delay='10m', ##执行间隔
steps=steps ##步骤
)
except ZabbixAPIException as e:
print(e)
sys.exit()
exp="{Templates web status:web.test.rspcode["+name+\
","+name+"].last()}<>200 or {Templates web status:web.test.fail["+name+"].last()}=1" ##问题触发器
exp2="{Templates web status:web.test.fail["+name+"].last()}=0" ##恢复触发器
print(exp2)
print(exp)
description = name + " is wrong"
print(description)
self.zapi.trigger.create(description=description,priority=4,expression=exp,recovery_mode=1,recovery_expression=exp2) ##添加触发器
def time_to_stamp(date_time):
# 时间转为时间戳
import time
a_time = time.strptime(date_time, '%Y-%m-%d %H:%M:%S')
return int(time.mktime(a_time))
test=Zabbix()
###所有交换机修改代理
host_list=test.get_templates('Templates web status')###取得模板id
hosts_ids=[]
close_triggers=[]
#print(host_list)
for host in host_list:
print(host) ##去数据库验证id是否一致,若熟悉数据库,无需用api接口取id,直接可以从数据库hosts表中取得模板的hostid,此处为无用代码。
t1= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
t2= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
t=datetime.datetime.strptime(t2,"%Y-%m-%d %H:%M:%S")-datetime.datetime.strptime(t1,"%Y-%m-%d %H:%M:%S")
print("开始时间:",t1," 结束时间:",t2," 执行时长为:",str(t))
url_list=['http://aaa.com','http://bbb.com/abc',https://acd.com']
for web_url in url_list:
test.create_web(web_url) ##批量添加监控
下面是本人的完整代码【包含很多没用到的方法】
# -*- coding: utf-8 -*-
# @File : utils.py
from pyzabbix import ZabbixAPI, ZabbixAPIException
import sys,time,datetime
class Zabbix(object):
def __init__(self):
ZABBIX_SERVER = 'http://XXXX.COM/zabbix'
zapi = ZabbixAPI(ZABBIX_SERVER)
zapi.login('XXXX', 'XXXX')
self.zapi = zapi
def logout_2(self):
zapi.logout()
def get_hosts(self, host):
# 获取主机
host_list = self.zapi.host.get(
output=['hostid','name','ip'],
selectGroups=['group_ids'], ###打印出主机组ID,方便后面搜索主机组
search={'host': host}
)
return host_list
def add_host(self, ip,host, group_ids, template_ids, tag=None,tag_values=None,port=10050, dns='', useip=1, main=1, type=1):
# 添加主机监控
interfaces = {
"type": type,
"main": main,
"useip": useip,
"ip": ip,
"dns": dns,
"port": port
}
tags={
"tag":tag,
"value":tag_values,
}
if type == 2:
interfaces['details'] = {
'version': 2,
'community': 'hikvision'
}
groups_list = {"groupid":group_ids}
template_ids_list = {"templateid":template_ids}
if not template_ids_list:
template_ids_list=[{}]
print(ip)
print(interfaces)
print(groups_list)
print(template_ids_list)
data = self.zapi.host.create(
host=host,
interfaces=[interfaces],
groups=[groups_list],
templates=[template_ids_list],
tags=[tags]
)
print(data)
return data
def get_hostgroups(self, name):
# 获取主机群组
hostgroups = self.zapi.hostgroup.get(
output='extend',
search={
'name': name
}
)
return hostgroups
def add_hostgroups(self, name):
# 添加主机群组
hostgroups = self.zapi.hostgroup.create(
name=name
)
return hostgroups
def get_proxy(self, name):
# 添加主机群组
proxies = self.zapi.proxy.get(
output='extend',
search={
'host': name
}
)
return proxies
def update_proxy(self, hosts,proxyid):
# 添加主机群组
success_ids = []
fail_ids = []
self.zapi.proxy.update(hosts= hosts,proxyid=proxyid)
success_ids.append(hosts)
return success_ids
def get_templates(self, name):
# 获取主机群组
templates = self.zapi.template.get(
output="templateid",
filter={
"name": name
}
)
return templates
def add_item(self, host):
# 添加监控项
hosts = self.zapi.host.get(filter={"host": host}, selectInterfaces=["interfaceid"])
if hosts:
host_id = hosts[0]["hostid"]
print("Found host id {0}".format(host_id))
try:
item = self.zapi.item.create(
hostid=host_id,
name='Used disk space on $1 in %',
key_='vfs.fs.size[/,pused]',
type=0,
value_type=3,
interfaceid=hosts[0]["interfaces"][0]["interfaceid"],
delay=30
)
except ZabbixAPIException as e:
print(e)
sys.exit()
print("Added item with itemid {0} to host: ".format(item["itemids"][0]))
else:
print("No hosts found")
def add_item_ping(self,dst_ip, host='VPC-MGMT4'):
# 添加监控项
hosts = self.zapi.host.get(filter={"host": host}, selectInterfaces=["interfaceid"])
if hosts:
host_id = hosts[0]["hostid"]
print("Found host id {0}".format(host_id))
try:
item = self.zapi.item.create(
hostid=host_id,
name='ping server $1 ', ##拼接监控项的名字
key_='icmpping['+dst_ip+']', ##拼接监控项的key
type=3,##3为简单检查
value_type=3,
interfaceid=hosts[0]["interfaces"][0]["interfaceid"],
delay=30
)
except ZabbixAPIException as e:
print(e)
sys.exit()
print("Added item with itemid {0} to host: ".format(item["itemids"][0]))
exp=r"{"+host+":"+'icmpping['+dst_ip+']'+".last()}<>1" ##告警表达式
exp2=r"{"+host+":"+'icmpping['+dst_ip+']'+".last()}=1" ##恢复表达式
print(exp2)
self.zapi.trigger.create(description="server "+dst_ip+" cannot ping",priority=3,expression=exp,recovery_mode=1,recovery_expression=exp2)
else:
print("No hosts found")
def get_triggers(self, groupids=None, hostids=None):
# 获取触发器标记
params = {
'output': 'extend'
}
if groupids:
params['groupids'] = groupids.split(',')
if hostids:
params['hostids'] = hostids.split(',')
result = self.zapi.trigger.get(**params)
return result
def update_triggers(self, triggerid, tag, value):
# 更新触发器
success_ids = []
fail_ids = []
try:
self.zapi.trigger.update(
triggerid=triggerid,
tags=[
{
'tag': tag,
'value': value
}
]
)
success_ids.append(triggerid)
except Exception:
fail_ids.append(triggerid)
return success_ids, fail_ids
def create_web(self,url, hostid=10935): ##批量添加web场景,在id为10935的模板上监控,并且添加触发器
name=' '.join(url.split('/')[2:]).replace(' ','-') ##url的域名+端口
steps=[{"name":name,"url":url,"status_codes":"200","no":1}]
print(name)
print(steps)
try:
item = self.zapi.httptest.create(
name=name, ##场景的名字
hostid=hostid, ##所在模板或主机
delay='10m', ##执行间隔
steps=steps ##第几步
)
except ZabbixAPIException as e:
print(e)
sys.exit()
exp="{Templates web status:web.test.rspcode["+name+\
","+name+"].last()}<>200 or {Templates web status:web.test.fail["+name+"].last()}=1" ##问题触发器
exp2="{Templates web status:web.test.fail["+name+"].last()}=0" ##恢复触发器
print(exp2)
print(exp)
description = name + " is wrong"
print(description)
self.zapi.trigger.create(description=description,priority=4,expression=exp,recovery_mode=1,recovery_expression=exp2)
def time_to_stamp(date_time):
# 时间转为时间戳
import time
a_time = time.strptime(date_time, '%Y-%m-%d %H:%M:%S')
return int(time.mktime(a_time))
test=Zabbix()
###所有交换机修改代理
host_list=test.get_templates('Templates web status')###获取模板id
hosts_ids=[]
close_triggers=[]
#print(host_list)
for host in host_list:
print(host)
t1= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
t2= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
t=datetime.datetime.strptime(t2,"%Y-%m-%d %H:%M:%S")-datetime.datetime.strptime(t1,"%Y-%m-%d %H:%M:%S")
print("开始时间:",t1," 结束时间:",t2," 执行时长为:",str(t))
url_list=['http://aaa.com','http://bbb.com/abc',https://acd.com']
for web_url in url_list:
test.create_web(web_url)