zabbix扩展 | 批量添加 Screens(2.x-3.x通用版本)

由于时间比较久,脚本的出处已经记不清了,在这里感谢共享出来此方法的网友。


此脚本并笔者原创,但亲测可用,并且在前期解决了笔者大量的时间。
在最初搭建公司监控系统的时候,最头疼的是需要把同类项目组的相同图形添加到一个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.py
import urllib2
import json
import argparse
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 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_list
def 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 python
import urllib2
import sys
import json
import 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接口认证的函数,登录成功会返回一个Token
def 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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,948评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,371评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,490评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,521评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,627评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,842评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,997评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,741评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,203评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,534评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,673评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,339评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,955评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,770评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,000评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,394评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,562评论 2 349

推荐阅读更多精彩内容