zabbix利用API添加Web頁面監控代碼實現(3)

又進一步優化了下,添加了自動創建主機步驟,後期會考慮自動添加動作:

#!/usr/bin/env python
# coding:utf-8
import sys

from pyzabbix import ZabbixAPI

reload(sys)
sys.setdefaultencoding('utf8')

ZABBIX_SERVER = "http://10.131.171.37/zabbix"
USER = "Admin"
PASSWORD = "zabbix"
HOSTNAME = "10.131.171.36"
PORT = PORT = "10050"
GROUPNAME = "Zabbix servers"
TEMPLATENAME = "Linux-OS-system"
# 要添加的監控頁面地址
URL = "http://10.131.88.110:18080/lens"


def login(ZABBIX_SERVER, USER, PASSWORD):
    zapi = ZabbixAPI(ZABBIX_SERVER)
    zapi.login(USER, PASSWORD)
    return zapi


def getgroupid(auth, GROUPNAME):
    """獲取主機羣組ID"""
    request = ZabbixAPI.do_request(auth, 'hostgroup.get', params={"output": "extend", "filter": {"name": GROUPNAME}})
    if request['result']:
        return request['result'][0]['groupid']
    else:
        print("Can not find this hostgroup!")
        sys.exit(1)


def gettemplateid(auth, TEMPLATENAME):
    """獲取模板ID"""
    request = ZabbixAPI.do_request(auth, 'template.get', params={"output": "extend", "filter": {"host": TEMPLATENAME}})
    if request['result']:
        return request['result'][0]['templateid']
    else:
        print("Can not find this template!")
        sys.exit(1)


def create_host(auth, HOSTNAME, PORT, groupid, templateid):
    """創建主機"""
    request = ZabbixAPI.do_request(auth, 'host.get', params={"filter": {"host": HOSTNAME}})
    if request['result']:
        print("This host has already added!")
    try:
        ZabbixAPI.do_request(auth, 'host.create', params={"host": HOSTNAME,
                                                          "interfaces": [{"type": 1, "main": 1, "useip": 1,
                                                                          "ip": HOSTNAME, "dns": "",
                                                                          "port": PORT}],
                                                          "groups": [{"groupid": groupid}],
                                                          "templates": [{"templateid": templateid}],
                                                          # 可選字段
                                                          # "macros": [{"macro": "{$USER_ID}", "value": "123321"}],
                                                          # "inventory_mode": 0,
                                                          # "inventory": {"macaddress_a": "01234",
                                                          #               "macaddress_b": "56768"}
                                                          })
    except Exception as e:
        print(e)


def gethostid(auth, HOSTNAME):
    """獲取主機ID"""
    request = ZabbixAPI.do_request(auth, 'host.get', params={"filter": {"host": HOSTNAME}})
    if request['result']:
        return request['result'][0]['hostid']
    else:
        print("Can not find this host!")
        sys.exit(1)


def getapplicationid(auth, hostid):
    """獲取應用集ID"""
    try:
        request = ZabbixAPI.do_request(auth, 'application.create', params={"name": u"WebMonitor", "hostid": hostid})
    except Exception as e:
        print(e)
    request = ZabbixAPI.do_request(auth, 'application.get', params={"hostids": hostid})
    for num in xrange(0, len(request['result'])):
        if request['result'][num]['name'] == "WebMonitor":
            print(request)
            return request['result'][num]['applicationid']


def create_web_scenario(auth, URL, hostid, applicationid):
    """創建場景"""
    request = ZabbixAPI.do_request(auth, 'httptest.get', params={"filter": {"name": URL}})
    if request['result']:
        print('This web monitor has already added!')
    else:
        try:
            ZabbixAPI.do_request(auth, 'httptest.create',
                                 params={"name": URL, "hostid": hostid, "applicationid": applicationid,
                                         "steps": [{'name': URL, 'url': URL, 'status_codes': '200', 'no': '1'}]})
        except Exception as e:
            print(e)


def create_trigger(auth, HOSTNAME, URL):
    """創建觸發器"""
    expression = "{" + "{0}:web.test.rspcode[{1},{1}].last()".format(HOSTNAME, URL) + "}" + "<>200"
    try:
        ZabbixAPI.do_request(auth, 'trigger.create',
                             params={"description": "[{0}] Pages Monitor".format(URL), "expression": expression,
                                     "priority": 4})
    except Exception as e:
        print(e)


def create_trigger_action():
    """創建觸發器動作"""
    pass


if __name__ == '__main__':
    auth = login(ZABBIX_SERVER, USER, PASSWORD)
    """創建主機"""""""""""""""""""""
    groupid = getgroupid(auth, GROUPNAME)
    templateid = gettemplateid(auth, TEMPLATENAME)
    create_host(auth, HOSTNAME, PORT, groupid, templateid)
    """創建主機"""""""""""""""""""""

    """添加頁面監控"""""""""""""""""
    hostid = gethostid(auth, HOSTNAME)
    applicationid = getapplicationid(auth, hostid)
    create_web_scenario(auth, URL, hostid, applicationid)
    create_trigger(auth, HOSTNAME, URL)
    """添加頁面監控"""""""""""""""""


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章