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

自動添加ACTION功能代碼已經添加,只要把API研究透,每個字段知道什麼意思其餘就很簡單了

#!/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 = "10050"
GROUPNAME = "Zabbix servers"
TEMPLATENAME = "Linux-OS-system"
ACTIONNAME = "WebPagesMonitorAction"
MEDIATYPE = "MailScript"
TRIGGER = "WebPages Monitoring"
# 要添加的監控頁面地址
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}] WebPages Monitoring".format(URL), "expression": expression,
                                     "priority": 4})
    except Exception as e:
        print(e)


def getusrid(auth, ZABBIXUSER):
    """獲取用戶ID"""
    request = ZabbixAPI.do_request(auth, 'user.get', params={"output": "extend"})
    if request['result']:
        for usr in request['result']:
            if usr.get("alias") == ZABBIXUSER:
                return usr.get("userid")


def getmediatypeid(auth, MEDIATYPE):
    """獲取媒介類型ID"""
    request = ZabbixAPI.do_request(auth, 'mediatype.get', params={"output": "extend"})
    if request['result']:
        for media in request['result']:
            if media.get("description") == MEDIATYPE:
                return media.get("mediatypeid")


def create_trigger_action(auth, ACTIONNAME, TRIGGER, USRID, MEDIATYPEID):
    """創建觸發器動作"""
    try:
        ZabbixAPI.do_request(auth, 'action.create',
                             params={
                                 "name": ACTIONNAME,
                                 "eventsource": 0,
                                 "status": 0,
                                 "esc_period": "2m",
                                 "def_shortdata": "{TRIGGER.NAME}: {TRIGGER.STATUS}",
                                 "def_longdata": "{TRIGGER.NAME}: {TRIGGER.STATUS}\r\nLast value: {ITEM.LASTVALUE}\r\n\r\n{TRIGGER.URL}",
                                 "filter": {
                                     "evaltype": 0,# and/or
                                     "conditions": [
                                         {
                                             # 條件一:觸發器名稱包含TRIGGER
                                             "conditiontype": 3,# 2:trigger,3:trigger name,4:trigger severity
                                             "operator": 2,# 0:equals,1:does not equal,2:contains,3:does not contain
                                             "value": TRIGGER

                                         },
                                         {
                                             # 條件二:觸發器示警度爲嚴重
                                             "conditiontype": 4,
                                             "operator": 0,# 0:not classified,1:information,2:warning,3:average,4:high,5:disaster
                                             "value": "4"
                                         }
                                     ]
                                 },
                                 "operations": [
                                     {
                                         "operationtype": 0,# 發送消息
                                         "esc_period": "0s",
                                         "esc_step_from": 1,
                                         "esc_step_to": 1,
                                         "evaltype": 0,
                                         "opmessage_usr": [
                                             {
                                                 "userid": USRID
                                             }
                                         ],
                                         "opmessage": {
                                             "default_msg": 1,# 0:使用默認的信息,1:發送的信息是自己定義的
                                             "mediatypeid": MEDIATYPEID,
                                         }
                                     }
                                 ]
                             })
    except Exception as e:
        print(e)


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)
    usrid = getusrid(auth, USER)
    mediatypeid = getmediatypeid(auth, MEDIATYPE)
    create_trigger_action(auth, ACTIONNAME, TRIGGER, usrid, mediatypeid)
    """添加頁面監控"""""""""""""""""

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