python大量新增zabbix Screens的兩個指令碼分享,zabbixscreens

來源:互聯網
上載者:User

python大量新增zabbix Screens的兩個指令碼分享,zabbixscreens

前言

在最初搭建公司監控系統的時候,最頭疼的是需要把同類項目組的相同圖形添加到一個Screens,由於只能一個一個的添加,非常耗時耗經曆。

下面分享兩個指令碼來解決這個頭疼的問題。

1.將單個主機的所有圖形添加到一個Screens

使用方法

#更改main()函數裡的url、username、password#參數一:主機名稱#參數二:篩選圖名稱python zabbix_screen_host.py 'zabbixserver' 'zabbixserver'

zabbix_screen_host.py指令碼內容

#!/usr/bin/env python#zabbix_screen_host.pyimport 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 message quit() 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 = 0 y = 0 for graph in graphs: 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 if x == columns: x = 0 y += 1 return graph_listdef screenCreate(url, auth, screen_name, graphids, columns): # print graphids if len(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 } 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://zabbixip/zabbix/api_jsonrpc.php' username = "***" password = "***" 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=3,  help='number of columns in the screen (default: 3)') 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.hostname screen_name = args.screenname columns = args.columns dynamic = (1 if args.dynamic else 0) screentype = (1 if args.screentype else 0) auth = authenticate(url, username, password) graphids = getGraph(hostname, url, auth, screentype, dynamic, columns) print "Screen Name: " + screen_name print "Total Number of Graphs: " + 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 : 一行有多少圖形python zabbix_screen_group.py -g 'zabbix' -G 'icmp-ping' -n 'zabbix-icmp-ping' -c 2

zabbix_screen_group.py指令碼內容

#!/usr/bin/env pythonimport urllib2import sysimport jsonimport argparse #定義通過HTTP方式訪問API地址的函數,後面每次請求API的各個方法都會調用這個函數def requestJson(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())# print output try: message = output['result'] except: message = output['error']['data'] print message quit()  return output['result'] #API介面認證的函數,登入成功會返回一個Tokendef authenticate(url, username, password): values = {'jsonrpc': '2.0',  'method': 'user.login',  'params': {   'user': username,   'password': password  },  'id': '0'  } idvalue = requestJson(url,values) return idvalue #定義更加主機分組名稱擷取各個hostid的函數def getHosts(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) for host in output[0]['hosts']: host_list.append(host['hostid']) return host_list #定義擷取graphid的函數def getGraphs(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 = lambda x:x['graphid']) graphs = [] if (graphtype == 0): for i in bb:  print i  graphs.append(i['graphid']) if (graphtype == 1): for i in bb:  if int(i['value_type']) in (0, 3):  graphs.append(i['itemid'])  graph_list = [] x = 0 y = 0 for graph in graphs: print "x is " + str(x) print "y is " + 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# print type(x)# print type(columns) if x == int(columns):  x = 0  y += 1# print graph_list return graph_list #定義建立screen的函數def screenCreate(url, auth, screen_name, graphids, columns): columns = int(columns) if len(graphids) % columns == 0: vsize = len(graphids) / columns else: vsize = (len(graphids) / columns) + 1 #先使用screen.get判斷給定的screen name是否存在 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) print output0 #如果給定的screen name不存在則直接建立screen  if output0 == []: print "The Given Screen Name Not Exists" print "Creating Screen %s" %screen_name for i in graphids:  values['params']['screenitems'].append(i) output = requestJson(url,values) else:  #如果給定的screen name已經存在,直接建立screen是不行的,#要麼先使用screen.delete把原來的screen刪除掉,然後再建立,#要麼直接使用screen.update更新原來那個screen,#使用screen.delete會產生新的screenid,#使用screen.update比較合理一點。 print "The Given Screen Name Already Exists" update_screenid=output0[0]["screenid"] print update_screenid print "Updating Screen Name %s Screen ID %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) print output1 print "Updating Screen Name %s" %screen_name for i in graphids:  values1['params']['screenitems'].append(i) output = requestJson(url,values1) def main(): url = 'http://zabbixip/zabbix/api_jsonrpc.php' username = '****' password = '****' auth = authenticate(url, username, password) host_list = getHosts(groupname,url,auth) print host_list graph_ids = getGraphs(host_list,graphname, url, auth, columns) screenCreate(url, auth, screenname, graph_ids, columns)if __name__ == '__main__': parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.') parser.add_argument('-G', dest='graphname', nargs='+',metavar=('grah name'),   help='Zabbix Host Graph to create screen from') parser.add_argument('-H', dest='hostname', nargs='+',metavar=('10.19.111.145'),   help='Zabbix Host to create screen from') parser.add_argument('-g', dest='groupname', nargs='+',metavar=('linux server'),   help='Zabbix Group to create screen from') parser.add_argument('-n', dest='screenname', 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,   help='number of columns in the screen') args = parser.parse_args() print args hostname = args.hostname groupname = args.groupname screenname = args.screenname columns = args.columns graphname = args.graphname if columns is None: columns = len(graphname)# print columns main()

總結

以上就是這篇文章的全部內容了,希望本文的內容的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.