阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

创建zabbix screen的脚本

149次阅读
没有评论

共计 5043 个字符,预计需要花费 13 分钟才能阅读完成。

zabbix 之所以能成为比较优秀的监控工具,个人觉得是因为两个特点:一个是数据的存放方式,方便做数据处理,容量规划,归档等,这个之前说过。另一个是其强大的 api,利用其 api 可以方便的和其他的组件进行整合,比如 cmdb 可以通过 zabbix api 来实现监控的添加,更新和禁用等,zabbix 的官方文档提供了比较详细的 api 列表。

因为最近添加 screen 的需求比较多,就简单写了一个 python 脚本用来自动化添加 screen,有兴趣的可以借鉴下。

使用方式如下:

python ./screen_host.py  -H 主机列表 -n screen 名称 -G graph 名称

具体的脚本:

#!/usr/bin/env python
import urllib2
import sys
import json
import argparse
def requestJason(url,values):
    data = json.dumps(values)
    req = urllib2.Request(url, data, {‘Content-Type’: ‘application/json-rpc’})
    response = urllib2.urlopen(req, data)
    data_get = response.read()
    output = json.loads(data_get)
    print output
    try:
        message = output[‘result’]
    except:
        message = output[‘error’][‘data’]
        quit()
    print json.dumps(message) 
    return output
           
def authenticate(url, username, password):
    values = {‘jsonrpc’: ‘2.0’,
              ‘method’: ‘user.login’,
              ‘params’: {
                  ‘user’: username,
                  ‘password’: password
              },
              ‘id’: ‘0’
              }
    idvalue = requestJason(url,values)
    return idvalue[‘result’]
def getHosts(hostname,url,auth):
    host_list = []
    values = {‘jsonrpc’: ‘2.0’,
              ‘method’: ‘host.get’,
              ‘params’: {
                  ‘output’: [“hostid”,”host”],
                  ‘filter’: {
                      ‘host’: hostname
                  }
              },
              ‘auth’: auth,
              ‘id’: ‘2’
              }
    output = requestJason(url,values)
    for host in output[‘result’]:
        host_list.append(host[‘hostid’])
    return host_list
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”: {
                select: [selecttype,”name”],
                “output”: [“graphid”,”name”],
                “hostids”: host_list,                   
                “filter”:{‘name’:name_list},
                “sortfield”:”name”,
            },
            “auth”: auth,
            “id”: ‘3’
        })
    print values
    output = requestJason(url,values)
    bb = sorted(output[‘result’],key = lambda x:x[‘hosts’][0][‘hostid’])
    output[‘result’] = bb
    graphs = []
    if (graphtype == 0):
        for i in output[‘result’]:
            print i
            graphs.append(i[‘graphid’])
    if (graphtype == 1):
        for i in output[‘result’]:
            if int(i[‘value_type’]) in (0, 3):
                graphs.append(i[‘itemid’])
    graph_list = []
    x = 0
    y = 0
    print graphs
    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”: “0”,
            “rowspan”: “0”,
            “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
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 = requestJason(url,values)
def main():
    url = ‘http://xxxx/api_jsonrpc.php’
    username = ‘xxxx’
    password = ‘xxxx’
    auth = authenticate(url, username, password)
    host_list = getHosts(hostname,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(‘-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
    screenname = args.screenname
    columns = args.columns
    graphname = args.graphname
    if columns is None:
        columns = len(graphname)
    print columns
    main()

一些 Zabbix 相关教程集合

Ubuntu 14.04 下 Zabbix2.4.5 源码编译安装  http://www.linuxidc.com/Linux/2015-05/117657.htm

CentOS 7 LNMP 环境搭建 Zabbix3.0  http://www.linuxidc.com/Linux/2017-02/140134.htm

Ubuntu 16.04 安装部署监控系统 Zabbix2.4  http://www.linuxidc.com/Linux/2017-03/141436.htm

Zabbix 监控安装部署及警报配置  http://www.linuxidc.com/Linux/2017-03/141611.htm

Ubuntu 16.04 下安装部署 Zabbix3.0  http://www.linuxidc.com/Linux/2017-02/140395.htm

CentOS 6.3 下 Zabbix 监控 apache server-status http://www.linuxidc.com/Linux/2013-05/84740.htm

CentOS 7 下 Zabbix 3.0 安装详解 http://www.linuxidc.com/Linux/2017-03/141716.htm

64 位 CentOS 6.2 下安装 Zabbix 2.0.6   http://www.linuxidc.com/Linux/2014-11/109541.htm

ZABBIX 的详细介绍:请点这里
ZABBIX 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-03/141922.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计5043字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中