Skip to content
SRE运维进阶之路SRE运维进阶之路
github icon

    7 用zabbix api批量添加web监控

    author iconClaycalendar icon2021年5月11日category icon
    • 监控
    tag icon
    • Zabbix
    timer icon大约 2 分钟

    # 7 用zabbix api批量添加web监控

    python脚本如下:

    vim zabbix_agent.py

    # ~*~ coding:utf-8 ~*~
    from zabbix_api import ZabbixAPI
    import sys
    import json
    
    ZABBIX_SREVER = "http://192.168.162.122"
    USERNAME = "Admin"
    PASSWORD = "zabbix"
    #HOSTNAME = "sh_ylf_15"
    #HOSTNAME = "h5_web_monitor"
    HOSTNAME = sys.argv[4]
    urlname = sys.argv[1]
    url = sys.argv[2]
    delay = sys.argv[3]
    
    
    # 登录
    def login(ZABBIX_SREVER, USERNAME, PASSWORD):
        zapi = ZabbixAPI(ZABBIX_SREVER)
        zapi.login(USERNAME, PASSWORD)
        return zapi
    
    
    # 获取主机id
    def gethostid(auth, HOSTNAME):
        json_obj = ZabbixAPI.json_obj(auth, 'host.get', params={"filter": {"host": HOSTNAME}})
        request = ZabbixAPI.do_request(auth, json_obj)
    
        if request['result']:
            return request['result'][0]['hostid']
        else:
            print("找不到该主机")
            sys.exit(1)
    
    
    # 获取应用级id
    def getapplicationid(auth, hostid):
        # try:
        #     json_obj = ZabbixAPI.json_obj(auth, 'application.create', params={"name": "Web监测","hostid": hostid})
        #     ZabbixAPI.do_request(auth, json_obj)
        # except Exception as e:
        #     print(e)
        json_obj = ZabbixAPI.json_obj(auth, 'application.get', params={"hostids": hostid})
        request = ZabbixAPI.do_request(auth, json_obj)
        for num in range(0, len(request['result'])):
            if request['result'][num]['name'] == 'Web':
                return request['result'][num]['applicationid']
    
    
    # 增加web监控
    def create_web_scenario(auth, urlname, url, hostid, applicationid, delay):
        json_obj = ZabbixAPI.json_obj(auth, 'httptest.get', params={"filter": {"name": urlname}})
        request = ZabbixAPI.do_request(auth, json_obj)
        if request['result']:
            print('该web监控已经添加过了')
        else:
            try:
                json_obj = ZabbixAPI.json_obj(auth, 'httptest.create',
                                              params={"name": urlname, "hostid": hostid, "applicationid": applicationid,
                                                      "delay": delay, "retries": '1', "steps": [
                                                      {'name': urlname, 'url': url, 'timeout': '10', 'status_codes': '200',
                                                       'no': '1'}]})
                ZabbixAPI.do_request(auth, json_obj)
            except Exception as e:
                print(e)
                sys.exit(1)
    
    
    # 增加触发器
    def create_trigger(auth, HOSTNAME, urlname, url):
        expression = "{" + "{0}:web.test.fail[{1}].avg(#3)".format(HOSTNAME, urlname) + "}" + ">=1"
        try:
            json_obj = ZabbixAPI.json_obj(auth, 'trigger.create',
                                          params={"description": "{0}访问失败".format(urlname), "expression": expression,
                                                  "priority": 5, "url": url})
            ZabbixAPI.do_request(auth, json_obj)
        except Exception as e:
            print(e)
            sys.exit(1)
    
        expression = "{" + "{0}:web.test.rspcode[{1},{1}].last(0)".format(HOSTNAME, urlname) + "}" + "<>200"
        try:
            json_obj = ZabbixAPI.json_obj(auth, 'trigger.create',
                                          params={"description": "{0}访问异常".format(urlname), "expression": expression,
                                                  "priority": 4, "url": url})
            ZabbixAPI.do_request(auth, json_obj)
        except Exception as e:
            print(e)
            sys.exit(1)
    
    
    # 获取监控项id
    def getitem(auth, hostid, urlname):
        json_obj = ZabbixAPI.json_obj(auth, 'item.get',
                                      params={"hostids": hostid, "webitems": "1",
                                              "filter": {"name": "Response code for step \"$2\" of scenario \"$1\".",
                                                         "key_": "web.test.rspcode[{0},{1}]".format(urlname, urlname)}})
        request = ZabbixAPI.do_request(auth, json_obj)
        return request["result"][0]["itemid"]
    
    
    # 增加图形
    def create_graph(auth, urlname, hostid):
        try:
            itemid = getitem(auth, hostid, urlname)
            json_obj = ZabbixAPI.json_obj(auth, 'graph.create',
                                          params={"name": "h5_{0}状态显示".format(urlname), "width": 900, "height": 200,
                                                  "gitems": [{"itemid": itemid, "color": "008800"}]})
            ZabbixAPI.do_request(auth, json_obj)
        except Exception as e:
            print(e)
            sys.exit(1)
    
    
    def main():
        auth = login(ZABBIX_SREVER, USERNAME, PASSWORD)
        hostid = gethostid(auth, HOSTNAME)
        applicationid = getapplicationid(auth, hostid)
    
        create_web_scenario(auth, urlname, url, hostid, applicationid, delay)
        create_trigger(auth, HOSTNAME, urlname, url)
        create_graph(auth, urlname, hostid)
    
    
    if __name__ == '__main__':
        main()
    
    # json_obj = ZabbixAPI.json_obj(auth, 'httptest.get', params={"applicationids": applicationid})
    # request = ZabbixAPI.do_request(auth, json_obj)
    # print(json.dumps(request, ensure_ascii=False, indent=4))
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131

    编写shell,调用python,打日志

    vim web_monitor.sh

    #!/bin/bash
    export LANG="en_US.UTF-8"
    
    arr_hostname=("192.168.165.115" "192.168.9.13")
    len=${#arr_hostname[@]}
    dir=$(cd $(dirname $0) && pwd)
    tdir="$dir/tmp"
    
    dt=`date "+%F %T"`
    
    [ -f $tdir/code_error.txt ] && true >$tdir/code_error.txt
    
    ## i: 项目信息   j: url   k:时间间隔
    while read i j k o;do
        if [[ ! x"$o" == x"" && $o -le $(($len-1)) ]];then
            curl -s -I "$j" > $tdir/curl.txt
            code=`grep 'HTTP/1.1' $tdir/curl.txt|awk '{print $2}'`
            #echo "$i $j $code" 
    
            if [ $code -eq 200 -o $code -eq 301 -o $code -eq 302 -o $code -eq 405 ];then
                python $dir/zabbix_agent.py $i $j $k ${arr_hostname[$o]}
                [ $? -eq 0 ] && echo "$dt $i $j $k $o create ok" >> $tdir/info || echo "$dt $i $j $k $o create fail" >>$tdir/info
            else
                echo "$i $j $k $o $code" >>$tdir/code_error.txt
                echo "$i $code"
            fi
        else
            echo "hostname参数传递错误"
            fi
    done <$dir/list
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30

    list文件内容格式如下:

    csp-web-syndata http://192.168.100.15:8085/csp-web-syndata/shop/synShopInfo/111 3m 0
    
    1

    参考链接:https://cloud.tencent.com/developer/article/1157571

    https://www.zabbix.com/documentation/current/manual/api

    https://segmentfault.com/a/1190000014241994

    edit icon编辑此页open in new window
    上次编辑于: 2022/4/27 15:33:00
    贡献者: clay-wangzhi
    备案号:冀ICP备2021007336号
    Copyright © 2023 Clay