zabbix api使用
zabbix api使用例子
#!/usr/bin/python env
# -*- coding: utf-8 -*-
# Author:cc
# date: 2020/9/9
from pyzabbix import ZabbixAPI, ZabbixAPIException
from bson import ObjectId
ZABBIX_API = {'url':"http://10.255.0.109/zabbix", "username":"Admin", "password":"zabbix"}
class ZabbixAPIWithLogout(ZabbixAPI):
def __init__(self, *args, **kwargs):
print('zabbix api init')
super(ZabbixAPIWithLogout, self).__init__(*args, **kwargs)
def __del__(self):
print('zabbix api close')
try:
self.do_request('user.logout')
except Exception as e:
print("zabbix api exception. {}".format(str(e)))
zapi = ZabbixAPIWithLogout(url=ZABBIX_API['url'], user=ZABBIX_API['username'], password=ZABBIX_API['password'])
# hosts = zapi.host.get(10256)
# print(hosts)
def gethostid(host):
"""
`return`: True, hosts[0]['hostid']
`failed`: False, errmsg
"""
try:
# hosts = zapi.host.get(filter={'host': host}, output=['hostid'])
hosts = zapi.host.get(filter={'host': host})
if not hosts:
errmsg = f"未找到主机{host}"
print(errmsg)
return False, errmsg
return True, hosts[0]['hostid']
except Exception as e:
errmsg = f"ZabbixAPI调用异常: {e}"
print(errmsg)
return False, errmsg
def gettrigger(host):
"""
:param host:
:return:
"""
try:
trigger = zapi.trigger.get(filter={"host": host})
if not trigger:
errmsg = f"未找到trigger"
print(errmsg)
return False, errmsg
return True, trigger
except Exception as e:
errmsg = f"Zabbix API调用异常:{e}"
print(errmsg)
return False, errmsg
print(gethostid("10.255.0.33"))
print(gettrigger("10.255.0.33"))
def gen_obj_id():
oid = ObjectId()
oid_str = str(oid)
return oid_str
# print(gen_obj_id())

浙公网安备 33010602011771号