zabbix auto add and delete screen
#!/usr/bin/env python#-*-coding:utf-8-*-# Author : SammyTan# Email : 729979966@qq.com# Last modified : 2016-04-25 16:24# Filename : zabbix_screens_automation.py# Description : Auto add delete and update zabbix screensimport osimport urllib2import jsonimport argparseurl='http://10.1.180.166/zabbix/api_jsonrpc.php'username='Admin'password='zabbix'def authenticate(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']print messagequit()return output['result']def getHost():values ={"jsonrpc":"2.0","method":"host.get","params":{"output":["host"]},"id":1,"auth":"2e92f0d30d878442533da77c15ae7cdd"}data = json.dumps(values)req = urllib2.Request(url, data,{'Content-Type':'application/json-rpc'})response = urllib2.urlopen(req, data)output = json.loads(response.read())return outputdef getGraph(hostid):values ={"jsonrpc":"2.0","method":"graph.get","params":{"output":["graphid"],"hostids": hostid},"auth":"2e92f0d30d878442533da77c15ae7cdd","id":1}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)#print json.dumps(output)return outputdef getScreentimeid(screenid):values ={"jsonrpc":"2.0","method":"screen.get","params":{"output":"extend","selectScreenItems":["screenitemid"],"screenids": screenid},"auth":"2e92f0d30d878442533da77c15ae7cdd","id":1}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)#print json.dumps(output)return outputdef getScreen():values ={"jsonrpc":"2.0","method":"screen.get","params":{"output":["name","screenid"]},"auth":"2e92f0d30d878442533da77c15ae7cdd","id":1}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)return outputdef screenDelete(screenid):values ={"jsonrpc":"2.0","method":"screen.delete","params":[screenid],"auth":"2e92f0d30d878442533da77c15ae7cdd","id":1}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)return output#os.system('python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 $each_host $each_host')def main():host_output=getHost()host_list =[]# add host to host listfor host in host_output['result']:#print hosthost_list.append(host['host'])screenname_list =[]screen_output=getScreen()# add screen name to saceen listfor name in screen_output['result']:screenname_list.append(name['name'])#Check host , if this host not have screen ,the self create screen .for host in host_list:if host notin screenname_list:# if this host not in screen list , the creend the host screenos.system('python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 %s %s'%(host,host))#### 该脚本在下面print'Create %s host screen'%(host)#Delete invalid screenfor name in screenname_list:for sid in screen_output['result']:if name in sid['name']:screenid = sid['screenid']if name notin host_list:delete_result = screenDelete(screenid)print'Delete %s host screen'%(name)#Check host graphs number, if graphs number grant than exsit screens graphs , the delete it after recreated.for screenid in screen_output['result']:#print screenidscreenGraphs = getScreentimeid(screenid['screenid'])for sid in screenGraphs['result']:for host in host_output['result']:if host['host']in screenid['name']:hostid = host['hostid']hostname = host['host']hostGraphs = getGraph(hostid)#print host['host'],len(hostGraphs['result']),len(sid['screenitems'])if len(hostGraphs['result'])> len(sid['screenitems']):delete_result = screenDelete(host['hostid'])os.system('python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 %s %s'%(hostname,hostname))print'Update %s host screen'%(hostname)else:print'All screen already sync .'if __name__ =='__main__':main()
#!/usr/bin/env pythonimport urllib2import jsonimport argparsedef authenticate(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']print messagequit()return output['result']def getGraph(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)# print json.dumps(output)graphs =[]if(graphtype ==0):for i in output['result'][0]['graphs']:graphs.append(i['graphid'])if(graphtype ==1):for i in output['result'][0]['items']:if int(i['value_type'])in(0,3):graphs.append(i['itemid'])graph_list =[]x =0y =0for graph in graphs:graph_list.append({"resourcetype": graphtype,"resourceid": graph,"width":"500","height":"200","x": str(x),"y": str(y),"colspan":"1","rowspan":"1","elements":"0","valign":"0","halign":"0","style":"0","url":"","dynamic": str(dynamic)})x +=1if x == columns:x =0y +=1return graph_listdef screenCreate(url, auth, screen_name, graphids, columns):# print graphidsif len(graphids)% columns ==0:vsize = len(graphids)/ columnselse:vsize =(len(graphids)/ columns)+1values ={"jsonrpc":"2.0","method":"screen.create","params":[{"name": screen_name,"hsize": columns,"vsize": vsize,"screenitems":[]}],"auth": auth,"id":2}for i in graphids: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']print json.dumps(message)def main():url ='http://10.1.180.166/zabbix/api_jsonrpc.php'username ="Admin"password ="zabbix"parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')parser.add_argument('hostname', metavar='H', type=str,help='Zabbix Host to create screen from')parser.add_argument('screenname', metavar='N', type=str,help='Screen name in Zabbix. Put quotes around it if you want spaces in the name.')parser.add_argument('-c', dest='columns', type=int, default=2,help='number of columns in the screen (default: 2)')parser.add_argument('-d', dest='dynamic', action='store_true',help='enable for dynamic screen items (default: disabled)')parser.add_argument('-t', dest='screentype', action='store_true',help='set to 1 if you want item simple graphs created (default: 0, regular graphs)')args = parser.parse_args()hostname = args.hostnamescreen_name = args.screennamecolumns = args.columnsdynamic =(1if args.dynamic else0)screentype =(1if args.screentype else0)auth = authenticate(url, username, password)graphids = getGraph(hostname, url, auth, screentype, dynamic, columns)print"Screen Name: "+ screen_nameprint"Total Number of Graphs: "+ str(len(graphids))screenCreate(url, auth, screen_name, graphids, columns)if __name__ =='__main__':main()
Growing old is mandatory, growing up is optional .

浙公网安备 33010602011771号