python批量添加zabbix Screens的两个脚本分享
前言
在最初搭建公司监控系统的时候,最头疼的是需要把同类项目组的相同图形添加到一个Screens,由于只能一个一个的添加,非常耗时耗经历。
下面分享两个脚本来解决这个头疼的问题。
1.将单个主机的所有图形添加到一个Screens
使用方法
#更改main()函数里的url、username、password #参数一:主机名 #参数二:筛选图名称 pythonzabbix_screen_host.py'zabbixserver''zabbixserver'
zabbix_screen_host.py脚本内容
#!/usr/bin/envpython #zabbix_screen_host.py importurllib2 importjson importargparse defauthenticate(url,username,password): values={'jsonrpc':'2.0', 'method':'user.login', 'params':{ 'user':username, 'password':password }, 'id':'0' } data=json.dumps(values) req=urllib2.Request(url,data,{'Content-Type':'application/json-rpc'}) response=urllib2.urlopen(req,data) output=json.loads(response.read()) try: message=output['result'] except: message=output['error']['data'] printmessage quit() returnoutput['result'] defgetGraph(hostname,url,auth,graphtype,dynamic,columns): if(graphtype==0): selecttype=['graphid'] select='selectGraphs' if(graphtype==1): selecttype=['itemid','value_type'] select='selectItems' values={'jsonrpc':'2.0', 'method':'host.get', 'params':{ select:selecttype, 'output':['hostid','host'], 'searchByAny':1, 'filter':{ 'host':hostname } }, 'auth':auth, 'id':'2' } data=json.dumps(values) req=urllib2.Request(url,data,{'Content-Type':'application/json-rpc'}) response=urllib2.urlopen(req,data) host_get=response.read() output=json.loads(host_get) #printjson.dumps(output) graphs=[] if(graphtype==0): foriinoutput['result'][0]['graphs']: graphs.append(i['graphid']) if(graphtype==1): foriinoutput['result'][0]['items']: ifint(i['value_type'])in(0,3): graphs.append(i['itemid']) graph_list=[] x=0 y=0 forgraphingraphs: graph_list.append({ "resourcetype":graphtype, "resourceid":graph, "width":"500", "height":"100", "x":str(x), "y":str(y), "colspan":"1", "rowspan":"1", "elements":"0", "valign":"0", "halign":"0", "style":"0", "url":"", "dynamic":str(dynamic) }) x+=1 ifx==columns: x=0 y+=1 returngraph_list defscreenCreate(url,auth,screen_name,graphids,columns): #printgraphids iflen(graphids)%columns==0: vsize=len(graphids)/columns else: vsize=(len(graphids)/columns)+1 values={"jsonrpc":"2.0", "method":"screen.create", "params":[{ "name":screen_name, "hsize":columns, "vsize":vsize, "screenitems":[] }], "auth":auth, "id":2 } foriingraphids: values['params'][0]['screenitems'].append(i) data=json.dumps(values) req=urllib2.Request(url,data,{'Content-Type':'application/json-rpc'}) response=urllib2.urlopen(req,data) host_get=response.read() output=json.loads(host_get) try: message=output['result'] except: message=output['error']['data'] printjson.dumps(message) defmain(): url='http://zabbixip/zabbix/api_jsonrpc.php' username="***" password="***" parser=argparse.ArgumentParser(description='CreateZabbixscreenfromallofahostItemsorGraphs.') parser.add_argument('hostname',metavar='H',type=str, help='ZabbixHosttocreatescreenfrom') parser.add_argument('screenname',metavar='N',type=str, help='ScreennameinZabbix.Putquotesarounditifyouwantspacesinthename.') parser.add_argument('-c',dest='columns',type=int,default=3, help='numberofcolumnsinthescreen(default:3)') parser.add_argument('-d',dest='dynamic',action='store_true', help='enablefordynamicscreenitems(default:disabled)') parser.add_argument('-t',dest='screentype',action='store_true', help='setto1ifyouwantitemsimplegraphscreated(default:0,regulargraphs)') args=parser.parse_args() hostname=args.hostname screen_name=args.screenname columns=args.columns dynamic=(1ifargs.dynamicelse0) screentype=(1ifargs.screentypeelse0) auth=authenticate(url,username,password) graphids=getGraph(hostname,url,auth,screentype,dynamic,columns) print"ScreenName:"+screen_name print"TotalNumberofGraphs:"+str(len(graphids)) screenCreate(url,auth,screen_name,graphids,columns) if__name__=='__main__': main()
2.将同组主机的同一图形添加到一个Screens
使用方法
#更改main()函数里的url、username、password #-g:组名称 #-G:图形名称 #-n:筛选(screen)图名称 #-c:一行有多少图形 pythonzabbix_screen_group.py-g'zabbix'-G'icmp-ping'-n'zabbix-icmp-ping'-c2
zabbix_screen_group.py脚本内容
#!/usr/bin/envpython importurllib2 importsys importjson importargparse #定义通过HTTP方式访问API地址的函数,后面每次请求API的各个方法都会调用这个函数 defrequestJson(url,values): data=json.dumps(values) req=urllib2.Request(url,data,{'Content-Type':'application/json-rpc'}) response=urllib2.urlopen(req,data) output=json.loads(response.read()) #printoutput try: message=output['result'] except: message=output['error']['data'] printmessage quit() returnoutput['result'] #API接口认证的函数,登录成功会返回一个Token defauthenticate(url,username,password): values={'jsonrpc':'2.0', 'method':'user.login', 'params':{ 'user':username, 'password':password }, 'id':'0' } idvalue=requestJson(url,values) returnidvalue #定义更加主机分组名称获取各个hostid的函数 defgetHosts(groupname,url,auth): host_list=[] values={'jsonrpc':'2.0', 'method':'hostgroup.get', 'params':{ 'output':'extend', 'filter':{ 'name':groupname }, 'selectHosts':['hostid','host'], }, 'auth':auth, 'id':'2' } output=requestJson(url,values) forhostinoutput[0]['hosts']: host_list.append(host['hostid']) returnhost_list #定义获取graphid的函数 defgetGraphs(host_list,name_list,url,auth,columns,graphtype=0,dynamic=0): if(graphtype==0): selecttype=['graphid'] select='selectGraphs' if(graphtype==1): selecttype=['itemid','value_type'] select='selectItems' values=({'jsonrpc':'2.0', 'method':'graph.get', 'params':{ 'output':['graphid','name'], select:[selecttype,'name'], 'hostids':host_list, 'sortfield':'name', 'filter':{ 'name':name_list, }, }, 'auth':auth, 'id':3 }) output=requestJson(url,values) bb=sorted(output,key=lambdax:x['graphid']) graphs=[] if(graphtype==0): foriinbb: printi graphs.append(i['graphid']) if(graphtype==1): foriinbb: ifint(i['value_type'])in(0,3): graphs.append(i['itemid']) graph_list=[] x=0 y=0 forgraphingraphs: print"xis"+str(x) print"yis"+str(y) graph_list.append({ "resourcetype":graphtype, "resourceid":graph, "width":"500", "height":"100", "x":str(x), "y":str(y), "colspan":"1", "rowspan":"1", "elements":"0", "valign":"0", "halign":"0", "style":"0", "url":"", "dynamic":str(dynamic) }) x+=1 #printtype(x) #printtype(columns) ifx==int(columns): x=0 y+=1 #printgraph_list returngraph_list #定义创建screen的函数 defscreenCreate(url,auth,screen_name,graphids,columns): columns=int(columns) iflen(graphids)%columns==0: vsize=len(graphids)/columns else: vsize=(len(graphids)/columns)+1 #先使用screen.get判断给定的screenname是否存在 values0={ "jsonrpc":"2.0", "method":"screen.get", "params":{ "output":"extend", "filter":{ "name":screen_name, } }, "auth":auth, "id":2 } values={ "jsonrpc":"2.0", "method":"screen.create", "params":{ "name":screen_name, "hsize":columns, "vsize":vsize, "screenitems":[] }, "auth":auth, "id":2 } output0=requestJson(url,values0) printoutput0 #如果给定的screenname不存在则直接创建screen ifoutput0==[]: print"TheGivenScreenNameNotExists" print"CreatingScreen%s"%screen_name foriingraphids: values['params']['screenitems'].append(i) output=requestJson(url,values) else: #如果给定的screenname已经存在,直接创建screen是不行的, #要么先使用screen.delete把原来的screen删除掉,然后再创建, #要么直接使用screen.update更新原来那个screen, #使用screen.delete会产生新的screenid, #使用screen.update比较合理一点。 print"TheGivenScreenNameAlreadyExists" update_screenid=output0[0]["screenid"] printupdate_screenid print"UpdatingScreenName%sScreenID%s"%(screen_name,update_screenid) values1={ "jsonrpc":"2.0", "method":"screen.update", "params":{ "screenid":update_screenid, "screenitems":[] }, "auth":auth, "id":2 } output1=requestJson(url,values1) printoutput1 print"UpdatingScreenName%s"%screen_name foriingraphids: values1['params']['screenitems'].append(i) output=requestJson(url,values1) defmain(): url='http://zabbixip/zabbix/api_jsonrpc.php' username='****' password='****' auth=authenticate(url,username,password) host_list=getHosts(groupname,url,auth) printhost_list graph_ids=getGraphs(host_list,graphname,url,auth,columns) screenCreate(url,auth,screenname,graph_ids,columns) if__name__=='__main__': parser=argparse.ArgumentParser(description='CreateZabbixscreenfromallofahostItemsorGraphs.') parser.add_argument('-G',dest='graphname',nargs='+',metavar=('grahname'), help='ZabbixHostGraphtocreatescreenfrom') parser.add_argument('-H',dest='hostname',nargs='+',metavar=('10.19.111.145'), help='ZabbixHosttocreatescreenfrom') parser.add_argument('-g',dest='groupname',nargs='+',metavar=('linuxserver'), help='ZabbixGrouptocreatescreenfrom') parser.add_argument('-n',dest='screenname',type=str, help='ScreennameinZabbix.Putquotesarounditifyouwantspacesinthename.') parser.add_argument('-c',dest='columns',type=int, help='numberofcolumnsinthescreen') args=parser.parse_args() printargs hostname=args.hostname groupname=args.groupname screenname=args.screenname columns=args.columns graphname=args.graphname ifcolumnsisNone: columns=len(graphname) #printcolumns main()
总结
以上就是这篇文章的全部内容了,希望本文的内容的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。