基於zabbix api根據hostname管理多個template
阿新 • • 發佈:2018-05-12
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