分布式监控系统Zabbix-批量添加聚合图形

之前部署了Zabbix(3.4.4版本)监控环境,由于主机比较多,分的主机组也比较多,添加聚合图形比较麻烦,故采用python脚本进行批量添加聚合图形。脚本下载地址:https://pan.baidu.com/s/1bpApIPp   (密码:wpts)脚本操作如下:

[root@zabbix01 ~]# cd /opt/
[root@zabbix01 opt]# ls
create_Disk_space_usage_screen.py  create_screen.py

======================================================================================
[root@zabbix01 opt]# cat create_screen.py 
#!/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': '600',
            '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://10.0.8.40/api_jsonrpc.php'
    username = 'Admin'
    password = 'qwkg@monitor'
    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()


======================================================================================
[root@zabbix01 opt]# cat create_Disk_space_usage_screen.py 
#!/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': '400',
            'height': '400',
            '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://10.0.8.40/api_jsonrpc.php'
    username = 'Admin'
    password = 'qwkg@monitor'
    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()


======================================================================================
上面两个脚本create_screen.py和create_Disk_space_usage_screen.py,脚本中只需要按照自己的实际zabbix访问情况修改三处:
url
username
password

前者用于批量生成负载、带宽、IO等监控的聚合图形,后者用于生成磁盘监控的聚合图形。
两个脚本唯一不同的就是width和height的值不一样。


批量生成聚合图形的操作如下:
[root@zabbix01 opt]# python create_screen.py  -g '财务系统'  -G 'Network traffic on bond0' -c 2 -n '财务系统---Network traffic on bond0'
[root@zabbix01 opt]# python create_screen.py  -g '财务系统'  -G 'CPU load' -c 2 -n '财务系统---CPU load'
[root@zabbix01 opt]# python create_screen.py  -g '财务系统'  -G 'CPU utilization' -c 2 -n '财务系统---CPU utilization'
[root@zabbix01 opt]# python create_screen.py  -g '财务系统'  -G 'Memory usage' -c 2 -n '财务系统---Memory usage'
[root@zabbix01 opt]# python create_screen.py  -g '财务系统'  -G 'Read and Write speed on /' -c 2 -n '财务系统---Read and Write speed on /'
[root@zabbix01 opt]# python create_screen.py  -g '财务系统'  -G 'Read and Write speed on /data' -c 2 -n '财务系统---Read and Write speed on /data'
[root@zabbix01 opt]# python create_Disk_space_usage_screen.py  -g '财务系统'  -G 'Disk space usage /' -c 3 -n '财务系统---Disk space usage /'
[root@zabbix01 opt]# python create_Disk_space_usage_screen.py  -g '财务系统'  -G 'Disk space usage /data' -c 3 -n '财务系统---Disk space usage /data'


对于以上命令中的参数解释:
-g    要显示zabbix的群组。
-G    要显示的zabbix图形。
-c    显示几列,注意要调整脚本里的:'width': ,'height':  参数来设置大小。
-n    在screen 里面显示的名称。

上面的命令的意思就是:把"财务系统"组里面每个服务器的bond0网卡、load负载、磁盘等监控图形,接每列4个图形(磁盘的按美3个图形)的显示在聚合图形里。

同理:如果添加其他主机组,即将上面的"财务系统" 统一替换掉即可!

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏北京马哥教育

黑客常用linux入侵常用命令,有你不知道的没?

[jobcruit@wa64-054 rankup_log]$ echo -e "<?php @eval(\$_POST[md5])?>" >rankuplog...

27630
来自专栏Youngxj

判断网站是否被百度收录

39350
来自专栏腾讯云数据库(TencentDB)

如何防范和应对Redis勒索,腾讯云教你出招

9月10日下午,又一起规模化利用Redis未授权访问漏洞攻击数据库的事件发生,此次黑客以勒索钱财作为目的,猖狂至极,甚至直接删除数据库数据。由于腾讯云早在17年...

801270
来自专栏点点滴滴

Centos7通过yum快速安装Transmission

70820
来自专栏IT技术精选文摘

Kafka消费者架构

Kafka消费者组 您可以通过用例或功能将消费者组合成消费者组。一个消费者组可能负责将记录传送到高速的、基于内存的微服务,而另一个消费者组将这些记录传输到Ha...

27090
来自专栏前端之路

CSS3实现流星动画

32040
来自专栏腾讯NEXT学位

【干货】加强 web 静态资源安全方法之SRI

我们通常会用CSP加强站点JS资源的执行限制,有效降低XSS攻击;我们通过HTTPS链接加密资源,减少站点资源劫持风险等等大量的前端安全方案。但你可能还没听说...

8K30
来自专栏月色的自留地

Mac版AppStore无法下载、升级错误处理

16140
来自专栏北京马哥教育

25个常用的Linux iptables规则

一些常用的 Linux iptables 规则,请根据自己的具体需要再修改。 # 1. 删除所有现有规则 # 2. 设置默认的 chain 策略 # 3. 阻止...

36570
来自专栏linux驱动个人学习

linux内核完全剖析——基于0.12内核-笔记(2)-统一编址和独立编址

IO是什么 ? IO(Input and Output)是输入输出接口。是CPU和其他外部设备(如串口、LCD、触摸屏、LED等)之间通信的接口。一般的,我们说...

39060

扫码关注云+社区

领取腾讯云代金券