Ad Widget

Collapse

Скрипт python для обработки cisco traps

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Chai
    Junior Member
    • Aug 2020
    • 5

    #1

    Скрипт python для обработки cisco traps

    Есть известный скрипт cisco-psec-traphandler.py , с помощью которого производится обработка "сырого" сообщения с устройства cisco. Вот его начало.

    PHP Code:
    import sys, os, re, subprocess
    import logging
    .handlers, shlex
    from pysnmp
    .hlapi import *
    from configparser import ConfigParser
    from ipaddress import IPv4Address
    , AddressValueError
    from pyzabbix import ZabbixAPI


    def read_config
    (filename, section):
    """ Read a configuration file and return a dictionary object
    aram filename: name of the configuration file
    aram section: section of a configuration
    :return: a dictionary of a configfile section parameters
    """
    # create parser and read ini configuration file
    parser = ConfigParser()
    parser.read(filename)

    # get section
    db = {}
    if 
    parser.has_section(section):
    items = parser.items(section)
    for 
    item in items:
    db[item[0]] = item[1]
    else:
    raise Exception('{0} not found in the {1} file'.format(section, filename))

    return 
    db

    def find_ifDesc_from_ifIndex
    (hostname, ifIndex, community="public"):
    errorIndication, errorStatus, errorIndex, varBinds = next(
    getCmd(SnmpEngine(),
    CommunityData(community),
    UdpTransportTarget((hostname, 161)),
    ContextData(),
    ObjectType(ObjectIdentity('IF-MIB', 'ifDescr', ifIndex)))
    )

    if 
    errorIndication:
    logging.error(errorIndication)
    elif errorStatus:
    logging.error('%s at %s', errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
    exit(
    1)
    else:
    ifDescr = varBinds[0][1].prettyPrint()
    return 
    ifDescr

    # find the path where the script is located to find a config.ini nearby
    dir_path = os.path.dirname(os.path.realpath(__file__))
    conf_file_name = dir_path + '/config.ini'

    # fetch config parameters
    snmp_config = read_config(conf_file_name, section = 'snmp')
    api_config = read_config(conf_file_name, section = 'api')
    logging_config = read_config(conf_file_name, section = 'logging')
    zabbix_config = read_config(conf_file_name, section='zabbix')
    #db_config = read_config(section = 'mysql')

    # set logging handler
    handler = logging.handlers.WatchedFileHandler(os.environ.get ("LOGFILE", logging_config['logfile']))
    #formatter = logging.Formatter(logging.BASIC_FORMAT)
    formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    root = logging.getLogger()
    root.setLevel(os.environ.get("LOGLEVEL", logging_config['loglevel']))
    root.addHandler(handler)

    # now parse the stdin
    inp = sys.stdin

    # the first line is alwats hostname
    hostname = inp.readline().strip()

    # the second line contains an IP address that should be fetched by regexp
    trapstr = inp.readline()
    m = re.search("\[(.*)\]:[0-9]+->", trapstr)
    ip = m.group(1) 

    Не могу понять, откуда берется вводная часть для обработки
    # now parse the stdin
    inp = sys.stdin

    Это вроде как стандартный ввод , по-умолчанию, с клавиатуры. Но мы же не с клавиатуры получаем материал, а как говорит теория, согласно настройке config.ini парится лог
    logfile = /var/log/cisco-errdisable-traphandler.log

    Но несмотря на то, что из сети идет много трапов, время последнего изменения этого файла - несколько дней назад.
    Объясните, пожалуйста, что за ввод со стандартного ввода имеется здесь в виду?
  • Navoyenok
    Senior Member
    • Dec 2011
    • 101

    #2
    Доброе утро! Если быть точнее, то это не стандартный ввод, а стандартный поток ввода. Так вот при запуске этого скрипта, в стандартный поток ввода будут сохранены 7 строк данных: hostname, ip, uptime, oid, address, community, enterprise. Так что всё верно не переживайте.

    Comment

    • Chai
      Junior Member
      • Aug 2020
      • 5

      #3
      Спасибо за ответ!
      Я не просто так "переживаю", пытаюсь понять механизм обработки трапов на нашем сервере. На нем настроена обработка трапов для сетевых устройств семейства Cisco, а еще нам всучили huawei, а вот продукцию этого вендора в части трапов не поддерживается в этом скрипте.
      в zabbix_server.conf есть две строки для указания хранения трапов (оба они содержат или не все фактически случившиеся события или вообще не обновляются с 20-го года)
      SNMPTrapperFile=/var/log/snmptrap/snmptrap.log

      StartSNMPTrapper=1
      SNMPTrapperFile=/var/zabbix_traps.tmp

      Сотрудник, который устанавливал заббикс, здесь уже не работает, да и ничего уже не помнит.
      Поэтому мне надо понять этот механизм, чтобы попробовать переписать скрипт для дополнения функционала или добавить на него основе другой.
      В инструкции написано
      Для чтения трапов, Zabbix сервер или прокси должны быть настроены на запуск процесса SNMP траппера и должны знать абсолютный путь к файлу с трапами, который заполняется при помощи SNMPTT или получателя трапов Perl. Чтобы это сделать, измените файл конфигурации (zabbix_server.conf или zabbix_proxy.conf):
      1. StartSNMPTrapper=1
      2. SNMPTrapperFile=[ФАЙЛ С ТРАПАМИ]
      3. ...
      4. https://www.zabbix.com/documentation...types/snmptrap
      Чтобы запарсить массив сообщения от huawei, мне нужно определить, в каком виде он приходит на вход скрипта.

      Чтобы кто-то приручал тарпы huawei, я не нашел в интернете и у производителя.

      Comment

      • Chai
        Junior Member
        • Aug 2020
        • 5

        #4
        Еще вопрос
        config.ini в /external-scripts имеет настройки:

        trapkeyname = ErrDisabled
        trapkeyname_disable = ErrDisable
        trapkeyname_restrict = ErrRestrict

        [logging]
        logfile = /var/log/cisco-errdisable-traphandler.log
        loglevel = INFO
        Что в нем писать, если добавлять huawei?

        Comment

        Working...