python调用zbbix的api实现批量添加域名监控脚本

一、这里分成了三个文件,一个是主文件:zbxHttp.py ,一个是zbbix相关登录信息文件:zbxHttp_settings.py ,一个需要监控域名的列表文件:url_file (三个配置文件需要都放在一个目录下面)

1、主配置文件:

vim  zbxHttp.py 

 

#!/usr/bin/env python
# Version = zabbix 4.2

import json
from urllib import request, parse
import zbxHttp_settings



url = "{}/api_jsonrpc.php".format(zbxHttp_settings.ZABBIX_URL)
header = {"Content-Type": "application/json"}


def ZbxAuth():
    print(zbxHttp_settings.ZABBIX_URL,zbxHttp_settings.ZABBIX_USERNAME)

    data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": zbxHttp_settings.ZABBIX_USERNAME,
            "password": zbxHttp_settings.ZABBIX_PASSWORD
        },
        "id": 1,
    }

    value = json.dumps(data).encode('utf-8')
    req = request.Request(url, headers=header, data=value)

    try:
        result = request.urlopen(req)
    except Exception as e:
        print("Auth Failed, Please Check Your Name And Password:", e)
    else:
        response = result.read()
        page = response.decode('utf-8')
        page = json.loads(page)
        result.close()
        status_list = str(page.get('result'))
        return status_list


def ZbxGetHost():
    data={
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": [
                    "hostid",
                    "host"
                ],
                "selectInterfaces": [
                    "interfaceid",
                    "ip"
                ]
            },
            "id": 1,
            "auth": token,
        }

    value = json.dumps(data).encode('utf-8')

    req = request.Request(url, headers=header, data=value)
    try:
        result = request.urlopen(req)
    except Exception as e:
        print("Auth Failed, Please Check Your Name And Password:", e)
    else:
        response = result.read()
        page = response.decode('utf-8')
        page = json.loads(page)
        for hostid in page['result']:
            zbxHttp_settings.HOSTID_LIST.append(hostid['hostid'])
            zbxHttp_settings.HOSTNAME_LIST.append(hostid['host'])
        result.close()
        status_list=str(page.get('result'))


def ZbxCreateHttp():
    """添加http监控"""
    with open(zbxHttp_settings.INPUT_FILE, 'r', encoding="utf-8") as file:
        count = 1
        for domain in file.readlines():
            if not domain.startswith("#"):
                method = domain.split()[0]
                as_name = domain.split()[1]
                web_url = domain.split()[2]
                web_name = domain.split()[2].split("//")[1]
                web_name_length = len(as_name + "-" + web_name)
                if int(web_name_length) > 65:
                    new_web_name_all = as_name + "-" + web_name
                    new_web_name = (new_web_name_all[0:64])
                else:
                    new_web_name = as_name + "-" + web_name
                if method == "GET":
                    data_1 = ""
                    print(method, as_name, web_name, web_url)
                elif method == "POST":
                    print(method, as_name, web_name, web_url)
                    data_1 = zbxHttp_settings.SOURCE_DATA
                for host_id in zbxHttp_settings.HOSTID_LIST:
                    print("Web场景-域名:%s,URL:%s"%(new_web_name,web_name))
                    data = {
                        "jsonrpc": "2.0",
                        "method": "httptest.create",
                        "params": {
                            "name": "%s" % (new_web_name),
                            "agent": zbxHttp_settings.CLIENT_AGENT,
                            "hostid": host_id,
                            # "applicationid": "1308",
                            "delay": zbxHttp_settings.UPDATE_TIME,
                            "retries": zbxHttp_settings.TRY_NUMBER,
                            "steps": [
                                {
                                    "name": "%s" % (web_name),
                                    "url": "%s" % (web_url),
                                    "status_codes": zbxHttp_settings.STATUS_CODE,
                                    "timeout": zbxHttp_settings.TIMEOUT,
                                    "headers": zbxHttp_settings.HEADER,
                                    "posts":"%s"%(data_1),
                                    "retrieve_mode": "2",
                                    "no": count
                                }
                            ]
                        },
                        "auth": token,
                        "id": 1
                    }

                    value = json.dumps(data).encode('utf-8')
                    req = request.Request(url, headers=header, data=value)
                    try:
                        result = request.urlopen(req)
                    except Exception as e:
                        print("Auth Failed, Please Check Your Name And Password:", e)
                    else:
                        response = result.read()
                        page = response.decode('utf-8')
                        page = json.loads(page)
                        print(page)
                        result.close()
                        status_list = str(page.get('result'))
                        print(status_list)

def ZbxCreateTrigger():
    """添加触发器"""
    with open(zbxHttp_settings.INPUT_FILE, 'r', encoding="utf-8") as file:
        count = 0
        for domain in file.readlines():
            if not domain.startswith("#"):
                as_name = domain.split()[1]
                web_name = domain.split()[2].split("//")[1]
                web_name_length = len(as_name + "-" + web_name)
                if int(web_name_length) > 65:
                    new_web_name_all = as_name + "-" + web_name
                    new_web_name = (new_web_name_all[0:64])
                else:
                    new_web_name = as_name + "-" + web_name
                for host in zbxHttp_settings.HOSTNAME_LIST:
                    print("触发器-域名:%s,URL:%s"%(new_web_name,web_name))
                    data = {
                        "jsonrpc": "2.0",
                        "method": "trigger.create",
                        "params": [
                            {
                                "description": "%s" % (new_web_name),
                                "expression": "{%s:web.test.rspcode[%s,%s].last()}<>200 or {%s:web.test.fail[%s].last()}<>0"% (host,new_web_name,web_name,host,new_web_name),
                                "priority": zbxHttp_settings.PRIORITY,
                            }
                        ],
                        "auth": token,
                        "id": 1
                    }
                    value = json.dumps(data).encode('utf-8')
                    req = request.Request(url, headers=header, data=value)
                    try:
                        result = request.urlopen(req)
                    except Exception as e:
                        print("Auth Failed, Please Check Your Name And Password:", e)
                    else:
                        response = result.read()
                        page = response.decode('utf-8')
                        page = json.loads(page)
                        print(page)
                        result.close()
                        status_list = str(page.get('result'))
                        print(status_list)


def main():
    if zbxHttp_settings.HOSTID_LIST and zbxHttp_settings.HOSTNAME_LIST:
        ZbxCreateHttp()
        ZbxCreateTrigger()
    else:
        ZbxGetHost()
        ZbxCreateHttp()
        ZbxCreateTrigger()

if __name__ == "__main__":
    token=ZbxAuth()
    print(token)
    main()

 

 

 

2、zbxHttp_settings.py

#!/usr/bin/env python
# Version = zabbix 4.2

#域名文件名称,同脚本目录下
INPUT_FILE= "url_file"

ZABBIX_URL = 'http://127.0.0.1:8080/zabbix'

ZABBIX_USERNAME="Admin"

ZABBIX_PASSWORD="zabbix"

#默认为所有服务器添加《hostid》,如果需要选择性添加,以[,]区分多个,例如: hostid_list = ['10084']
HOSTID_LIST=[]

#默认为所有服务器添加《主机名称》,如果需要选择性添加,以[,]区分多个,例如: host_list=['Zabbix server']
HOSTNAME_LIST=[]

#更新间隔时间(秒)
UPDATE_TIME="30"

# 尝试次数(次)
TRY_NUMBER="2"

# 模拟客户端
CLIENT_AGENT="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"

# 要求状态码多个[,]
STATUS_CODE="200"

# 访问超时时间(秒)
TIMEOUT="15"

#严重性级别  0 未分类  1信息  2警告  3一般严重  4严重  5灾难
PRIORITY="4"

 3、你需要监控的URL的地址列表文件

url_file

例如:https://www.baidu.com

............... 需要监控的在这个文件里面添加好

注意:zbxHttp_settings.py文件中根据自己zbbix相关登录信息进行修改,修改完成后使用Python3进行运行即可;

 添加完成后:如图查看相关web监控是否正常:

 

posted @ 2020-07-09 17:22  小毅哥博客  阅读(315)  评论(0编辑  收藏  举报