标签:zabbix api
基于zabbix api根据hostname添加多个template之前写了一个关联模版的api但是考虑到每个添加一个template是有点复杂,而且最近有那么一个需求,所以改了一下方法,使得可以根据hostname添加多个template。
话不多说直接上脚本和效果:
(env1) ? ~ cat zabbix_add_template.py #!/usr/bin/python #-*- coding:utf-8 -*- #__author__ == 'chenmingle' import json import sys import urllib2 import argparse from urllib2 import URLError reload(sys) sys.setdefaultencoding('utf-8') class zabbix_api: def __init__(self): self.url = 'http://www.zabbix.com:8088/zabbix/api_jsonrpc.php' self.header = {"Content-Type":"application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "zabbix", "password": "zabbixpasswd" }, "id": 0 }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "\033[041m 认证失败,请检查URL !\033[0m",e.code except KeyError as e: print "\033[041m 认证失败,请检查用户名密码 !\033[0m",e else: response = json.loads(result.read()) result.close() #print response['result'] self.authID = response['result'] return self.authID def hostid_get_hostip(self, hostId=''): data = json.dumps({ "jsonrpc": "2.0", "method": "hostinterface.get", "params": { "output": "extend", "filter": {"hostid": hostId} }, "auth": self.user_login(), "id": 1 }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason elif hasattr(e, 'code'): print 'The server could not fulfill the request.' print 'Error code: ', e.code else: response = json.loads(result.read()) result.close() if not len(response['result']): print "\033[041m hostid \033[0m is not exist" return False for hostip in response['result']: return hostip['ip'] def host_get(self,hostName=''): data=json.dumps({ "jsonrpc": "2.0", "method": "host.get", "params": { "output": "extend", #"filter":{"host":""} "filter":{"host":hostName} }, "auth": self.user_login(), "id": 1 }) request = urllib2.Request(self.url,data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason elif hasattr(e, 'code'): print 'The server could not fulfill the request.' print 'Error code: ', e.code else: response = json.loads(result.read()) #print reqponse result.close() if not len(response['result']): print "\033[041m %s \033[0m is not exist" % hostName return False print "主机数量: \033[31m%s\033[0m"%(len(response['result'])) for host in response['result']: status={"0":"OK","1":"Disabled"} available={"0":"Unknown","1":"available","2":"Unavailable"} #print host if len(hostName)==0: print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :%s \t Available :%s"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']]) else: print "HostID : %s\t HostName : %s\t HostIp : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],self.hostid_get_hostip(hostId=host['hostid']),status[host['status']],available[host['available']]) return host['hostid'] def template_get(self,templateName=''): data = json.dumps({ "jsonrpc":"2.0", "method": "template.get", "params": { "output": "extend", "filter": { "name":templateName } }, "auth":self.user_login(), "id":1, }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) except URLError as e: print "Error as ", e else: response = json.loads(result.read()) result.close() #print response if not len(response['result']): print "\033[041m %s \033[0m is not exist" % templateName return False for template in response['result']: if len(templateName)==0: print "template : %s \t id : %s" % (template['name'], template['templateid']) else: self.templateID = response['result'][0]['templateid'] print "Template Name :%s"%templateName return response['result'][0]['templateid'] def template_massadd(self, templateName, hostName): template_list=[] for i in templateName.split(','): template_list = self.template_get(i) print template_list host_id = self.host_get(hostName) print host_id data = json.dumps({ "jsonrpc": "2.0", "method": "template.massadd", "params": { "templates": [ { "templateid": template_list, } ], "hosts": [ { "hostid": host_id } ] }, "auth": self.user_login(), "id":1 }) request = urllib2.Request(self.url, data) for key in self.header: request.add_header(key, self.header[key]) try: result = urllib2.urlopen(request) response = json.loads(result.read()) result.close() print "add %s to hosts: %s" % (templateName, hostName) except URLError as e: print "Error as ", e except KeyError as e: print "\033[041m 主机添加有误,请检查模板正确性或主机是否添加重复 !\033[0m",e print response if __name__ == "__main__": zabbix=zabbix_api() parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]') parser.add_argument('-t','--template_messadd',dest='template_massadd',nargs=2,metavar=('Template01,Template02', 'hostName'),help='添>加主机,多个主机组或模板使用逗号') args = parser.parse_args() zabbix.template_massadd(args.template_massadd[0], args.template_massadd[1])
执行脚本:
(env1) ? ~ python zabbix_add_template.py -t 'Template App HTTP Service','Template ICMP Ping' testServer_***_WEB Template Name :Template App HTTP Service 10094 主机数量: 1 HostID : 10477 HostName : testServer_***_WEB HostIp : 106.75.***.*** Status :OK Available :available 10477 add Template App HTTP Service,Template ICMP Ping to hosts: testServer_***_WEB Template Name :Template ICMP Ping 10104 主机数量: 1 HostID : 10477 HostName : testServer_***_WEB HostIp : 106.75.***.*** Status :OK Available :available 10477 add Template App HTTP Service,Template ICMP Ping to hosts: testServer_***_WEB
查看zabbix web上是否已经关联模版:
基于zabbix api根据hostname管理多个template
标签:zabbix api
原文地址:http://blog.51cto.com/legehappy/2115465