在配置 zabbix的过程中或者通过zabbix获取数据是,总是需要获取各个组建的id号,有时候需要添加几十上百个item或者trigger。所以就自己写了下面的类。如果以后有需要会再完善。不过估计是不需要了,因为做了一个月监控,终于做完了。代码如下,已经给出简单的注释。有问题可留言。
#!/usr/bin/python #-*- coding:utf8 -*- from zabbix_api import ZabbixAPI class zabbix_tools: ''' 从zabbixweb端获取,Item,host,等列表并添加host及trigger。 ''' def __init__(self,server,username,password): self.server=server self.zapi = ZabbixAPI(server=self.server, path="", log_level=0) self.zapi.login(username,password) self.item_dict={} self.app_dict={} self.host_dict={} self.group_dict={} def get_item_list(self,hostname): #获取指定host的item列表 search={"filter":{"host":[hostname]}} for application_id in ['2311','2312']: search["applicationids"]=application_id for item_info in self.zapi.item.get(search): self.item_dict[item_info["name"]]=[item_info["itemid"],item_info["key_"]] return self.item_dict def get_host_list(self): #获取整个zabbix的host列表 for host in zapi.host.get({}): self.host_dict[host['name']]=host['hostid'] return self.host_dict def get_group_list(self): #获取整个zabbix的hostgroup列表 for group in zapi.hostgroup.get({}): self.group_dict[group['name']]=group['groupid'] return self.group_dict def get_host_info(self,hostname): #获取指定host的信息 host_info = self.zapi.host.get({"selectInterfaces":["interfaceid"],"filter":{"host":[hostname]}}) hostid = host_info[0]['hostid'] interfaceid = host_info[0]['interfaces'][0]['interfaceid'] return (hostid,interfaceid) def get_aplication_list(self,hostname): #获取指定host的application列表 search={"filter":{"host":[hostname]}} for app in self.zapi.application.get(search): self.app_dict[app['name']]=app['applicationid'] return self.app_dict def create_item(name,key,hostname,appname): #在指定host下添加一个item并指定appname。 a = self.get_host_info(hostname) hostid = a[0] interfaceid = a[1] applicationid=self.get_aplication_list[hostname][appname] create_item=self.zapi.item.create( { "name":name, "key_":key, "hostid":hostid, "type":0, "value_type":0, "interfaceid":interfaceid, "date_type":0, "delay":60, "history":7, "trends":90, "status":0, "applications":[ applicationid ] } ) return "item create success" def create_trigger(self,expression,description,hostname): #为某个host添加trigger a = self.get_host_info(hostname) hostid = a[0] self.zapi.trigger.create({"description":description,"expression":expression,"hostid":hostid,'priority':2}) print "trigger create success" if __name__ == '__main__': server = "zabbix web server url" username = "youusername" password = "yourpassword" app=zabbix_tools(server,username,password) print app.get_group_list()