本次批量添加針對監控**網絡設備**,監控介質經過snmp方式。 不須要再一次一次添加每一個網絡設備。 只須要編寫excel表格,便可一鍵添加監控。
yum -y install epel-release yum -y install python-pip pip install --upgrade pip pip install xlrd
表格列的信息依次爲: 主機名,主機顯示名,IP,主機所屬主,主機模板組,snmp團體名
表格名字爲:add-host-2.xlsx
#!/usr/bin/python #coding:utf-8 import json import urllib2 from urllib2 import URLError import sys,argparse import xlrd defaultencoding = 'utf-8' if sys.getdefaultencoding() != defaultencoding: reload(sys) sys.setdefaultencoding(defaultencoding) class zabbix_api: def __init__(self): self.url = 'http://zabbix服務器的IP/zabbix/api_jsonrpc.php' #修改zabbix服務器ip地址,或者域名 self.header = {"Content-Type":"application/json"} def user_login(self): data = json.dumps({ "jsonrpc": "2.0", "method": "user.login", "params": { "user": "admin", # 修改web頁面登陸用戶名 "password": "zabbix" # 修改web頁面登陸密碼 }, "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 用戶認證失敗,請檢查 !\033[0m", e.code else: response = json.loads(result.read()) result.close() #print response['result'] self.authID = response['result'] return self.authID def host_get(self,hostName=''): data=json.dumps({ "jsonrpc": "2.0", "method": "host.get", "params": { "output": "extend", "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 response result.close() # 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 Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']]) else: print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']]) return host['hostid'] def hostgroup_get(self, hostgroupName=''): data = json.dumps({ "jsonrpc":"2.0", "method":"hostgroup.get", "params":{ "output": "extend", "filter": { "name": hostgroupName } }, "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: #print result.read() response = json.loads(result.read()) result.close() #print response() for group in response['result']: if len(hostgroupName)==0: print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid']) else: print "hostgroup: \033[31m%s\033[0m\tgroupid : %s" %(group['name'],group['groupid']) self.hostgroupID = group['groupid'] return group['groupid'] 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 for template in response['result']: if len(templateName)==0: print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid']) else: self.templateID = response['result'][0]['templateid'] print "Template Name : \033[31m%s\033[0m "%templateName return response['result'][0]['templateid'] def hostgroup_create(self,hostgroupName): if self.hostgroup_get(hostgroupName): print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName sys.exit(1) data = json.dumps({ "jsonrpc": "2.0", "method": "hostgroup.create", "params": { "name": hostgroupName }, "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 "\033[042m 添加主機組:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids']) def host_create_andy(self,hostName,visibleName, hostip, hostgroupName, templateName, temp_count): count_add_host = temp_count # 用於記錄添加excel主機的數量 if self.host_get(hostip): print "\033[041m該主機已經添加! host_create_andy\033[0m" else: group_list=[] template_list=[] for i in hostgroupName.split(','): var = {} var['groupid'] = self.hostgroup_get(i) group_list.append(var) for i in templateName.split(','): var={} var['templateid']=self.template_get(i) template_list.append(var) data = json.dumps({ "jsonrpc":"2.0", "method":"host.create", "params":{ "host": hostName, "name": visibleName, "interfaces": [ { "type": 2, #1:表示IP;2表示SNMP "main": 1, "useip": 1, "ip": hostip, "dns": "", "port": "161" #IP端口10051;SNMP端口161 } ], "groups": group_list, "templates": template_list, "macros": [ { "macro": "{$SNMP_COMMUNITY}", "value": 'hc360tc' } ] }, "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() count_add_host +=1 print "添加主機%s : \033[42m%s\033[0m \tid :\033[31m%s\033[0m" % (count_add_host, hostip, response['result']['hostids']) return count_add_host def host_create(self, hostip, hostgroupName, templateName): if self.host_get(hostip): print "\033[041m該主機已經添加! host_create\033[0m" sys.exit(1) group_list=[] template_list=[] for i in hostgroupName.split(','): var = {} var['groupid'] = self.hostgroup_get(i) group_list.append(var) for i in templateName.split(','): var={} var['templateid']=self.template_get(i) template_list.append(var) data = json.dumps({ "jsonrpc":"2.0", "method":"host.create", "params":{ "host": hostip, "interfaces": [ { "type": 2, "main": 1, "useip": 1, "ip": hostip, "dns": "", "port": "161" } ], "groups": group_list, "templates": template_list, }, "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 "添加主機 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids']) def host_disable(self,hostip): data=json.dumps({ "jsonrpc": "2.0", "method": "host.update", "params": { "hostid": self.host_get(hostip), "status": 1 }, "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 '----主機如今狀態------------' print self.host_get(hostip) def host_delete(self,hostid): hostid_list=[] #print type(hostid) for i in hostid.split(','): var = {} var['hostid'] = self.host_get(i) hostid_list.append(var) data=json.dumps({ "jsonrpc": "2.0", "method": "host.delete", "params": hostid_list, "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 Exception,e: print e else: result.close() print "主機 \033[041m %s\033[0m 已經刪除 !"%hostid if __name__ == "__main__": zabbix=zabbix_api() parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]') parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查詢主機') parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查詢主機組') parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查詢模板信息') parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主機組') parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主機,多個主機組或模板使用分號') parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主機') parser.add_argument('-L','--allin',dest='allin',nargs='?',default='allin',help='從Excel批量導入主機') parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='刪除主機,多個主機之間用分號') parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0') if len(sys.argv)==1: print parser.print_help() else: args=parser.parse_args() if args.listhost != 'host' : if args.listhost: zabbix.host_get(args.listhost) else: zabbix.host_get() if args.listgroup !='group': if args.listgroup: zabbix.hostgroup_get(args.listgroup) else: zabbix.hostgroup_get() if args.listtemp != 'template': if args.listtemp: zabbix.template_get(args.listtemp) else: zabbix.template_get() if args.addgroup: zabbix.hostgroup_create(args.addgroup[0]) if args.addhost: zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2]) if args.disablehost: zabbix.host_disable(args.disablehost) if args.deletehost: zabbix.host_delete(args.deletehost[0]) if args.allin != 'allin': workbook = xlrd.open_workbook('add-host-2.xlsx') #Excel表名 count = 0 # 用於記錄添加excel主機的數量 for row in xrange(workbook.sheets()[0].nrows): hostname = workbook.sheets()[0].cell(row, 0).value visible = workbook.sheets()[0].cell(row, 1).value hostip = workbook.sheets()[0].cell(row, 2).value hostgroup = workbook.sheets()[0].cell(row, 3).value hosttemp = workbook.sheets()[0].cell(row, 4).value count = zabbix.host_create_andy(hostname,visible,hostip,hostgroup, hosttemp, count) print "經過excel一共添加主機 : \033[42m%s\033[0m臺!" % (count)
注意:
必須修改腳本三個部份內容:php
1. 'http://zabbix服務器的IP/zabbix/api_jsonrpc.php' #修改zabbix服務器ip地址,或者域名 2. "user": "admin", # 修改web頁面登陸用戶名 3. "password": "zabbix" # 修改web頁面登陸密碼
hong6.py文件爲腳本文件名。 運行腳本:python hong6.py -L
同時腳本也支持: python hong6.py -H 查看全部主機 python hong6.py -H --host 查看單個主機,如:python hong6.py -H --host 172.16.8.10 python hong6.py -G 查看全部主機組 python hong6.py -T 查看全部臨時模板 python hong6.py -A 添加主機組 python hong6.py -C 添加多個主機或者多個模板 python hong6.py -d 禁用主機 python hong6.py -L 批量添加excel主機 python hong6.py -D 批量刪除主機
參考:http://www.javashuo.com/article/p-atzdlznr-c.html
zabbix api:https://www.zabbix.com/documentation/4.0/manual/apihtml