Z-api生成聚合图形py

简单的报表
https://github.com/geekwolf/sa-scripts/blob/master/ops-scripts/zabbix/zabbix_report.py

screen_hosts.py --生成单台主机的所有聚合图形
create_screen.py --生成某个监控项的聚合图形
disk_create_screen.py --生成磁盘监控的聚合图形
两个脚本(create_screen.py and disk_create_screen.py)唯一不同的就是width和height的值不一样。


screen_hosts.py --生成单台主机的所有聚合图形
执行命令
python screen_hosts.py '主机名' '自定义名'
输出结果
Screen Name: 10.0.1.4
Total Number of Graphs: 10
{"screenids": ["47"]}

#!/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://ip/api_jsonrpc.php'
  username = "username"
  password = "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=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.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()

create_screen.py --生成某个监控项的聚合
执行命令
python create_screen.py -g 'Linux servers' -G '内存使用率[Memory usage]' -c 2 -n '内存'
python create_screen.py -g 'Linux servers' -G '网卡流量[Network traffic on eth1]' -c 2 -n '网卡流量'
python create_screen.py -g '主机群组名' -G '图形名称全称' -c(列/单位) 2 -n '自定义名'
'width': ,'height': 参数来设置大小。
脚本运行后没有输出结果
//出现个别主机绘图失败并抛出错误--解决:主机名称和接口地址一致


Z-api生成聚合图形py_第1张图片
image.png
#!/bin/env python
import json
import urllib2
import argparse
import re
  
re_digits = re.compile(r'(\d+)')
  
def emb_numbers(s):
    pieces=re_digits.split(s)
    pieces[1::2]=map(int,pieces[1::2])
    return pieces
  
def sort_strings_with_emb_numbers2(alist):
    return sorted(alist, key=emb_numbers)
  
def requestjson(url, values):
    data = json.dumps(values)
    req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
    res = urllib2.urlopen(req, data)
    output = json.loads(res.read())
  
    return output
  
  
def authenticate(url, username, password):
    values = {'jsonrpc': '2.0',
              'method': 'user.login',
              'params': {
                  'user': username,
                  'password': password
              },
              'id': '0'
    }
    output = requestjson(url, values)
  
    return output['result']
  
def gethosts(groupname, url, auth):
    host_list = {}
    values = {'jsonrpc': '2.0',
              'method': 'hostgroup.get',
              'params': {
                  'output': 'extend',
                  'filter': {'name': groupname},
                  'selectHosts': ['host']
              },
              'auth': auth,
              'id': '2'
    }
    output = requestjson(url, values)
    for host in output['result'][0]['hosts']:
        host_list[host['host']]=(host['hostid'])
  
    #return host_list
    hosts_sort = []
    for host in sort_strings_with_emb_numbers2(host_list.keys()):
        hosts_sort.append(host_list[host])
    return  hosts_sort
  
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'
  
    graphs = []
    for host in host_list:
        values = ({'jsonrpc': '2.0',
                   'method': 'graph.get',
                   'params': {
                       select: [selecttype, 'name'],
                       'output': ['graphid', 'name'],
                       'hostids': host,
                       'filter': {'name': name_list},
                       'sortfield': 'name'
                   },
                   'auth': auth,
                   'id': '3'
                   })
        output = requestjson(url, values)
        bb = sorted(output['result'])
        if (graphtype == 0):
            for i in bb:
                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:
        graph_list.append({
            'resourcetype': graphtype,
            'resourceid': graph,
            'width': '500',
            'height': '100',
            'x': str(x),
            'y': str(y),
            'colspan': '1',
            'rowspan': '1',
        })
        x += 1
        if x == int(columns):
            x = 0
            y += 1
  
    return graph_list
  
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
  
    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)
    output = requestjson(url, values)
  
def main():
    url = 'http://ip/api_jsonrpc.php'
    username = 'username'
    password = 'password'
    auth = authenticate(url, username, password)
    host_list = gethosts(groupname, url, auth)
    graph_ids = getgraphs(host_list, graphname, url, auth, columns)
    screencreate(url, auth, screen_name, graph_ids, columns)
  
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-g', dest='groupname', nargs='+', metavar='groupname', type=str, help='which group you want to select')
    parser.add_argument('-G', dest='graphname', nargs='+', metavar='graphname', type=str, help='which graph you want to select')
    parser.add_argument('-c', dest='columns', metavar='columns', type=int, help='the screen columns')
    parser.add_argument('-n', dest='screen_name', metavar='screen_name', type=str, help='the screen name')
    args = parser.parse_args()
  
    groupname = args.groupname
    graphname = args.graphname
    columns = args.columns
    screen_name = args.screen_name
  
    main()


disk_create_screen.py --生成磁盘监控的聚合图形
执行命令
python disk_create_screen.py -g 'Linux servers' -G '磁盘使用情况[Disk space usage /home]' -c 3 -n 'Serve_disk'
python disk_create_screen.py -g '要显示的群组' -G '要显示的图形' -c 3 -n '在screen 里面显示的名称'
脚本运行后没有输出结果

#!/bin/env python
import json
import urllib2
import argparse
import re
  
re_digits = re.compile(r'(\d+)')
  
def emb_numbers(s):
    pieces=re_digits.split(s)
    pieces[1::2]=map(int,pieces[1::2])
    return pieces
  
def sort_strings_with_emb_numbers2(alist):
    return sorted(alist, key=emb_numbers)
  
def requestjson(url, values):
    data = json.dumps(values)
    req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
    res = urllib2.urlopen(req, data)
    output = json.loads(res.read())
  
    return output
  
  
def authenticate(url, username, password):
    values = {'jsonrpc': '2.0',
              'method': 'user.login',
              'params': {
                  'user': username,
                  'password': password
              },
              'id': '0'
    }
    output = requestjson(url, values)
  
    return output['result']
  
def gethosts(groupname, url, auth):
    host_list = {}
    values = {'jsonrpc': '2.0',
              'method': 'hostgroup.get',
              'params': {
                  'output': 'extend',
                  'filter': {'name': groupname},
                  'selectHosts': ['host']
              },
              'auth': auth,
              'id': '2'
    }
    output = requestjson(url, values)
    for host in output['result'][0]['hosts']:
        host_list[host['host']]=(host['hostid'])
  
    #return host_list
    hosts_sort = []
    for host in sort_strings_with_emb_numbers2(host_list.keys()):
        hosts_sort.append(host_list[host])
    return  hosts_sort
  
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'
  
    graphs = []
    for host in host_list:
        values = ({'jsonrpc': '2.0',
                   'method': 'graph.get',
                   'params': {
                       select: [selecttype, 'name'],
                       'output': ['graphid', 'name'],
                       'hostids': host,
                       'filter': {'name': name_list},
                       'sortfield': 'name'
                   },
                   'auth': auth,
                   'id': '3'
                   })
        output = requestjson(url, values)
        bb = sorted(output['result'])
        if (graphtype == 0):
            for i in bb:
                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:
        graph_list.append({
            'resourcetype': graphtype,
            'resourceid': graph,
            'width': '500',
            'height': '100',
            'x': str(x),
            'y': str(y),
            'colspan': '1',
            'rowspan': '1',
        })
        x += 1
        if x == int(columns):
            x = 0
            y += 1
  
    return graph_list
  
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
  
    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)
    output = requestjson(url, values)
  
def main():
    url = 'http://ip/api_jsonrpc.php'
    username = 'user'
    password = 'pass'
    auth = authenticate(url, username, password)
    host_list = gethosts(groupname, url, auth)
    graph_ids = getgraphs(host_list, graphname, url, auth, columns)
    screencreate(url, auth, screen_name, graph_ids, columns)
  
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-g', dest='groupname', nargs='+', metavar='groupname', type=str, help='which group you want to select')
    parser.add_argument('-G', dest='graphname', nargs='+', metavar='graphname', type=str, help='which graph you want to select')
    parser.add_argument('-c', dest='columns', metavar='columns', type=int, help='the screen columns')
    parser.add_argument('-n', dest='screen_name', metavar='screen_name', type=str, help='the screen name')
    args = parser.parse_args()
  
    groupname = args.groupname
    graphname = args.graphname
    columns = args.columns
    screen_name = args.screen_name
  
    main()

你可能感兴趣的:(Z-api生成聚合图形py)