Ad Widget

Collapse

Добавление required string в web scenario используя pyzabbix

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Daikazahn
    Member
    • Nov 2016
    • 69

    #1

    Добавление required string в web scenario используя pyzabbix

    Добрый день!
    Имеется скрипт для конфигурирования zabbix хоста
    Code:
    #!/bin/env python
    # -*- coding: utf-8 -*-
    import sys
    import os
    import yaml
    from pyzabbix import ZabbixAPI
    config_path = "/etc/zabbix/zabbix-auto.yaml"
    # for local tests
    #config_path = "zabbix-auto.yaml"
    if os.path.isfile(config_path):
    yaml_file = open(config_path, "r")
    zbx_config = yaml.load(yaml_file)
    yaml_file.close()
    else:
    print('File /etc/zabbix/zabbix-auto.yaml not found!')
    sys.exit(1)
    zapi = ZabbixAPI(zbx_config["zabbix_api"]["url"])
    zapi.login(zbx_config["zabbix_api"]["user"], zbx_config["zabbix_api"]["password"])
    def get_hostgroups(p_hostgroups):
    ret_value = []
    for hostgroup in p_hostgroups:
    zbx_data = zapi.hostgroup.get(output="groupid", filter={"name":hostgroup})
    if len(zbx_data) > 0:
    ret_value.append({"groupid": zbx_data[0]["groupid"]})
    else:
    zbx_data = zapi.hostgroup.create(name=hostgroup)
    ret_value.append({"groupid": zbx_data["groupids"][0]})
    return ret_value
    def get_templates(p_templates):
    ret_value = []
    for template in p_templates:
    zbx_data = zapi.template.get(output="templateid", filter={"host": template})
    if len(zbx_data) > 0:
    ret_value.append({"templateid": zbx_data[0]["templateid"]})
    else:
    print("Template %s not found on zabbix server!" % (template))
    return ret_value
    def get_interfaces(p_hostid):
    zbx_data = zapi.hostinterface.get(
    output = ["interfaceid", "type"],
    hostids = p_hostid,
    sortfield = "interfaceid"
    )
    return zbx_data
    def get_proxy(proxy_name):
    zbx_data = zapi.proxy.get(output="proxyid", filter={"host": proxy_name })
    if len(zbx_data) > 0:
    return(zbx_data[0]["proxyid"])
    else:
    return 0
    pass
    def get_macros(p_macros):
    ret_value = []
    for macro_key, macro_value in p_macros.iteritems():
    ret_value.append({"macro": macro_key, "value": macro_value})
    return ret_value
    def get_applicationid(app_name, hostid):
    zbx_data = zapi.application.get(output="applicationid", filter={"name": app_name}, hostids=hostid )
    if len(zbx_data) > 0:
    return(zbx_data[0]["applicationid"])
    else:
    zbx_data = zapi.application.create(name = app_name, hostid = hostid)
    return(zbx_data["applicationids"][0])
    pass
    def trigger(trigdata, hostid):
    zbx_data = zapi.trigger.get(output=["triggerid"], filter={"description": trigdata["description"], "hostid": hostid })
    if len(zbx_data) > 0:
    zbx_data = zapi.trigger.update(
    description = trigdata["description"],
    expression = trigdata["expression"],
    priority = trigdata["priority"]
    )
    else:
    zbx_data = zapi.trigger.create(
    description = trigdata["description"],
    expression = trigdata["expression"],
    priority = trigdata["priority"]
    )
    pass
    
    hostname = zbx_config["host"]
    hostgroups = get_hostgroups(zbx_config["hostgroups"])
    ipaddr = zbx_config["ipaddress"]
    port = zbx_config["port"]
    templates = get_templates(zbx_config["templates"])
    zbx_interfaces = [
    {"type":"1", "main": "1", "useip": "0", "ip":ipaddr, "dns": hostname, "port": port}
    ]
    if zbx_config.has_key("zabbix_jmx_enable"):
    if zbx_config["zabbix_jmx_enable"] == 1:
    zbx_interfaces.append(
    {
    "type":"4",
    "main": "1",
    "useip": (zbx_config["zabbix_jmx_useip"] if zbx_config.has_key("zabbix_jmx_useip") else "0"),
    "ip": (zbx_config["zabbix_jmx_ip"] if zbx_config.has_key("zabbix_jmx_ip") else ipaddr),
    "dns": (zbx_config["zabbix_jmx_dns"] if zbx_config.has_key("zabbix_jmx_dns") else hostname),
    "port": (zbx_config["zabbix_jmx_port"] if zbx_config.has_key("zabbix_jmx_port") else "1234")
    }
    )
    proxy_id = 0
    if zbx_config.has_key("proxy"):
    proxy_id = get_proxy(zbx_config["proxy"])
    hostid = 0
    zbx_data = zapi.host.get(output="hostid", filter={"host": hostname})
    if len(zbx_data) > 0:
    hostid = zbx_data[0]["hostid"]
    macros = (get_macros(zbx_config["macros"]) if zbx_config.has_key("macros") and zbx_config["macros"] != None else [])
    # Пример host-mapping для назначения макросов конкретному узлу сети:
    # zabbix_host_macros:
    # - '"{$TEST1}": qwerty'
    # - '"{$TEST2}": asdf'
    if hostid == 0:
    zbx_data = zapi.host.create(
    host=hostname,
    interfaces=zbx_interfaces,
    groups=hostgroups,
    templates=templates,
    proxy_hostid=proxy_id,
    macros=macros
    )
    else:
    #update interfaces
    zbx_cur_interfaces = get_interfaces(hostid)
    for zbx_cur_interface in zbx_cur_interfaces:
    for zbx_interface in zbx_interfaces:
    if zbx_interface["type"] == zbx_cur_interface["type"]:
    zbx_data = zapi.hostinterface.update(
    interfaceid = zbx_cur_interface["interfaceid"],
    type = zbx_interface["type"],
    useip = zbx_interface["useip"],
    ip = zbx_interface["ip"],
    dns = zbx_interface["dns"],
    port = zbx_interface["port"]
    )
    break
    for zbx_interface in zbx_interfaces:
    zbx_new_interface = True
    for zbx_cur_interface in zbx_cur_interfaces:
    if zbx_cur_interface["type"] == zbx_interface["type"]:
    zbx_new_interface = False
    break
    if zbx_new_interface:
    zbx_data = zapi.hostinterface.create(
    hostid = hostid,
    type = zbx_interface["type"],
    main = zbx_interface["main"],
    useip = zbx_interface["useip"],
    ip = zbx_interface["ip"],
    dns = zbx_interface["dns"],
    port = zbx_interface["port"]
    )
    # Удаление неиспользуемых элементов данных
    templates_old = zapi.host.get(output="hostid", selectParentTemplates="templateid", hostids=hostid)
    old_template_list = []
    for o in templates_old[0]["parentTemplates"]:
    if o not in templates:
    old_template_list.append(o)
    if old_template_list: zapi.host.update(hostid=hostid, templates_clear=old_template_list)
    # Обновление хоста
    zbx_data = zapi.host.update(
    hostid=hostid,
    groups=hostgroups,
    templates=templates,
    proxy_hostid=proxy_id,
    macros=macros
    )
    # Веб-сценарии
    httptestlist = []
    if zbx_config.has_key("webcheck"):
    appid = get_applicationid("Web check", hostid)
    webcheck = zbx_config["webcheck"]
    for webcheckname in webcheck.keys():
    steps = []
    triggers = []
    for step in webcheck[webcheckname].keys():
    steps.append(
    {
    "name": step,
    "url": webcheck[webcheckname][step]["url"],
    "no": webcheck[webcheckname][step]["nom"],
    "required string": "OK"
    # "status_codes": "200"
    }
    )
    triggers.append(
    {
    "description": webcheckname+" не возвращает OK ("+step+")",
    "expression": "{"+hostname+":web.test.rspcode["+webcheckname+","+step+"].count(#5,200)}=0",
    "priority": 4
    }
    )
    # Обновляем или создаём веб-сценарии
    zbx_data = zapi.httptest.get(output="httptestid", filter={"name": webcheckname}, hostids=hostid )
    if len(zbx_data) > 0:
    httptestid = zbx_data[0]["httptestid"]
    zbx_data = zapi.httptest.update(
    httptestid = httptestid,
    name = webcheckname,
    steps = steps,
    applicationid = appid
    )
    httptestlist.append(httptestid)
    else:
    zbx_data = zapi.httptest.create(
    name = webcheckname,
    hostid = hostid,
    steps = steps,
    applicationid = appid
    )
    httptestlist.append(zbx_data["httptestids"][0])
    # Создаём триггеры
    for trstr in triggers:
    trigger(trstr, hostid)
    # Удаляем сценарии, которых нет в списке webcheck
    for httptestdelete in zapi.httptest.get(output="httptestid", hostids=hostid):
    if httptestdelete["httptestid"] in httptestlist:
    pass
    else:
    zbx_data = zapi.httptest.delete(httptestdelete["httptestid"])
    sys.exit(0)

    Если в steps.append добавляю "required string": "OK"
    Code:
            for step in webcheck[webcheckname].keys():
                steps.append(
                    {
                    "name": step,
                    "url": webcheck[webcheckname][step]["url"],
                    "no": webcheck[webcheckname][step]["nom"],
                    "required string": "OK"
                    # "status_codes": "200"
                    }
                )
    то у меня появляется ошибка:
    pyzabbix.ZabbixAPIException: ('Error -32602: Invalid params., Invalid parameter "/1/steps/1": unexpected parameter "required_string"

    Пробовал различные варианты:
    "regexp": "OK"
    "string": "OK"
    "web.page.regexp": "OK"



    Как добавить required string в web scenario используя pyzabbix ?

    Код zabbix-auto.yaml
    Code:
    host: dhdfhdfh
    port: 10050
    ipaddress: cxxxxdf
    
    
    hostgroups:
      - UKD
    
    zabbix_api:
      url: "http://fdghdfgh/zabbix/"
      user: "djhndfhdf"
      password: "dfhdfhdf"
    
    
    webcheck:
      dfghsfhsfhf:
        firststep:
          nom: "1"
          url: "http://cxdgsdfgsghshbs"
    Last edited by Daikazahn; 10-10-2019, 10:39.
  • Daikazahn
    Member
    • Nov 2016
    • 69

    #2
    Решилось все добавлением "required": "OK"

    Comment

    Working...