Exemple #1
0
 def dispatch(self, event):
     # Log Event
     events_log.info(event.to_json())
     # Enqueue TrapEvent
     self._events.append(event)
     log.debug("TrapEventDispatcherThread: Enqueued Event: %r" % event)
     return True
Exemple #2
0
    def __init__(self, config, mibs, callback):
        self._config = config
        self._mibs = mibs
        self._callback = callback

        # Create SNMP engine with autogenernated engineID and pre-bound to
        # socket transport dispatcher
        self._snmp_engine = pysnmp.entity.engine.SnmpEngine()
        log.debug("TrapReceiver: Initialized SNMP Engine")

        # Configure transport UDP over IPv4
        if config['snmp']['transport']['udp']['enabled']:
            self._configure_udp_transport(
                    config['snmp']['transport']['listen_address'],
                    int(config['snmp']['transport']['listen_port']))

        # Configure transport TCP over IPv4
        if config['snmp']['transport']['tcp']['enabled']:
            # TODO: Implement TCP transport ?
            pass

        # Configure SNMPv2 if enabled
        if bool(self._config['snmp']['auth']['version2']['enabled']):
            self._configure_snmp_v2(self._config['snmp']['auth']['version2']['community'])

        # Configure SNMPv3 if enabled
        if bool(self._config['snmp']['auth']['version3']['enabled']):
            # TODO: configure SNMPv3 users from config file
            self._configure_snmp_v3(self._config['snmp']['auth']['version3']['users'])

        # configure pysnmp debugging 
        # from pysnmp import debug
        # debug.setLogger(debug.Debug('io'))

        log.debug("TrapReceiver: Initialized")
Exemple #3
0
    def _notification_callback(self, snmp_engine, stateReference, contextEngineId, contextName, varBinds, cbCtx):
        """
        Callback function for receiving notifications
        """
        trap_oid = None
        trap_name = None
        trap_args = dict()

        try:
            # get the source address for this notification
            transportDomain, trap_source = snmp_engine.msgAndPduDsp.getTransportInfo(stateReference)
            log.debug("TrapReceiver: Notification received from %s, %s" % (trap_source[0], trap_source[1]))

            # read all the varBinds
            for oid, val in varBinds:
                # translate OID to mib symbol/modname
                (module, symbol) = self._mibs.lookup_oid(oid)

                if module == "SNMPv2-MIB" and symbol == "snmpTrapOID":
                    # the SNMPv2-MIB::snmpTrapOID value is the trap oid
                    trap_oid = val
                    # load the mib symbol/modname for the trap oid
                    (trap_symbol_name, trap_mod_name) = self._mibs.lookup_oid(trap_oid)
                else:
                    # all other values should be converted to mib symbol/modname
                    # and put in the trap_data dict

                    # trap_arg_oid = oid
                    # For the case the faultIndex was added into the OID, we have to lookup
                    # the original OID from MIB instead of using the OID in the received packet directly.
                    trap_arg_oid = self._mibs.lookup(module, symbol)
                    # convert value
                    trap_arg_value = self._mibs.lookup_value(module, symbol, val)
                    trap_args[trap_arg_oid] = trap_arg_value

                log.debug("TrapReceiver: Trap argument: %s, %s = %s" % (module, symbol, val))

            # get trap source info
            trap_source_address, trap_source_port = trap_source
            trap_source_hostname, trap_source_domain = get_hostname_from_address(trap_source_address)

            # set trap propreties
            trap_properties = dict()
            trap_properties['hostname'] = trap_source_hostname
            trap_properties['ipaddress'] = trap_source_address
            trap_properties['domain'] = trap_source_domain

            # create trap
            trap = self._create_trap(trap_oid, trap_args, trap_properties)

            # now that everything has been parsed, trigger the callback
            self._callback(trap)

        except Exception as ex:
            log.exception("Error handling SNMP notification")
Exemple #4
0
    def dispatch(self, event):
        hostname = self._device_requester.get_nagios_hostname(event.ipaddr)
        traps = self._device_requester.get_trap_settings(event.ipaddr)

        trap_valid = False
        for trap in traps:
            if event.name == trap['name']:
                if 'oid' in trap:
                    oid = ObjectName(trap['oid'])
                    if str(event.arguments[oid]) == str(trap['value']):
                        trap_valid = True
                        break
                else:
                    trap_valid = True
                    break

        if not trap_valid:
            log.error('TrapEventDispatcher: Trap is not valid %s' % event.to_json())
            return

        command = self._config['dispatcher']['command']
        command_exists = os.path.isfile(command)
        if not command_exists:
            log.error('TrapEventDispatcher: Dispatcher command does not exist.')
            return False

        success = len(event.handlers) > 0

        for handler in event.handlers:
            output_dict = {
                'nagios_status': event.status,
                'output': event.output,
                'type': event.type
            }

            output = '!' + json.dumps(output_dict)

            log.debug('TrapEventDispatcher: command called %s %s %s %s %s' % (command,
                                                                              hostname,
                                                                              handler,
                                                                              str(event.status),
                                                                              output))

            ret = call([command, hostname, handler, str(event.status), output])

            print(event.to_json())
            log.debug('TrapEventDispatcher: Message has been sent to nagios (%s).' % hostname)
            success = ret == 0

        return success
Exemple #5
0
    def _configure_snmp_v3(self, users):
        # configure snmp v3 users
        for user in users:
            auth = users[user]['authentication']
            priv = users[user]['privacy']

            auth_protocol = self.SNMPV3_AUTH_PROTOCOLS[auth['protocol']]
            priv_protocol = self.SNMPV3_PRIV_PROTOCOLS[priv['protocol']]

            if priv_protocol:
                pysnmp.entity.config.addV3User(self._snmp_engine, user,
                                               auth_protocol, auth['password'],
                                               priv_protocol, priv['password'])

                log.debug(
                    "TrapReceiver: Added SNMPv3 user: %s auth: %s, priv: %s" %
                    (user, auth['protocol'], priv['protocol']))
            else:
                pysnmp.entity.config.addV3User(self._snmp_engine, user,
                                               auth_protocol, auth['password'])

                log.debug(
                    "TrapReceiver: Added SNMPv3 user: %s auth: %s, priv: none"
                    % (user, auth['protocol']))

        log.debug("TrapReceiver: Initialized SNMPv3 Auth")
Exemple #6
0
    def _configure_snmp_v3(self, users):
        # configure snmp v3 users
        for user in users:
            auth = users[user]['authentication']
            priv = users[user]['privacy']

            auth_protocol = self.SNMPV3_AUTH_PROTOCOLS[auth['protocol']]
            priv_protocol = self.SNMPV3_PRIV_PROTOCOLS[priv['protocol']]

            if priv_protocol:
                pysnmp.entity.config.addV3User(self._snmp_engine,
                                               user,
                                               auth_protocol,
                                               auth['password'],
                                               priv_protocol,
                                               priv['password'])

                log.debug("TrapReceiver: Added SNMPv3 user: %s auth: %s, priv: %s" % (
                    user, auth['protocol'], priv['protocol']))
            else:
                pysnmp.entity.config.addV3User(self._snmp_engine,
                                               user,
                                               auth_protocol,
                                               auth['password'])

                log.debug("TrapReceiver: Added SNMPv3 user: %s auth: %s, priv: none" % (user, auth['protocol']))

        log.debug("TrapReceiver: Initialized SNMPv3 Auth")
Exemple #7
0
    def __init__(self, mib_paths=None, mib_list=None):
        if mib_paths is None:
            mib_paths = []
        if mib_list is None:
            mib_list = []

        # Initialize mib MibBuilder
        self._mib_builder = pysnmp.smi.builder.MibBuilder()

        # Configure MIB sources
        self._mib_sources = self._mib_builder.getMibSources()

        # Load default mib dirs
        for path in self.DEFAULT_MIB_PATHS + mib_paths:
            self.load_mib_dir(path)
        # Load default mibs
        for mib in self.DEFAULT_MIB_LIST + mib_list:
            self.load_mib(mib)

        # Initialize MibViewController
        self._mib_view = pysnmp.smi.view.MibViewController(self._mib_builder)
        log.debug("MibResolver: Initialized")
Exemple #8
0
    def __init__(self, mib_paths=None, mib_list=None):
        if mib_paths is None:
            mib_paths = []
        if mib_list is None:
            mib_list = []

        # Initialize mib MibBuilder
        self._mib_builder = pysnmp.smi.builder.MibBuilder()

        # Configure MIB sources
        self._mib_sources = self._mib_builder.getMibSources()

        # Load default mib dirs
        for path in self.DEFAULT_MIB_PATHS + mib_paths:
            self.load_mib_dir(path)
        # Load default mibs
        for mib in self.DEFAULT_MIB_LIST + mib_list:
            self.load_mib(mib)

        # Initialize MibViewController
        self._mib_view = pysnmp.smi.view.MibViewController(self._mib_builder)
        log.debug("MibResolver: Initialized")
Exemple #9
0
    def __init__(self, config, mibs, callback):
        self._config = config
        self._mibs = mibs
        self._callback = callback

        # Create SNMP engine with autogenernated engineID and pre-bound to
        # socket transport dispatcher
        self._snmp_engine = pysnmp.entity.engine.SnmpEngine()
        log.debug("TrapReceiver: Initialized SNMP Engine")

        # Configure transport UDP over IPv4
        if config['snmp']['transport']['udp']['enabled']:
            self._configure_udp_transport(
                config['snmp']['transport']['listen_address'],
                int(config['snmp']['transport']['listen_port']))

        # Configure transport TCP over IPv4
        if config['snmp']['transport']['tcp']['enabled']:
            # TODO: Implement TCP transport ?
            pass

        # Configure SNMPv2 if enabled
        if bool(self._config['snmp']['auth']['version2']['enabled']):
            self._configure_snmp_v2(
                self._config['snmp']['auth']['version2']['community'])

        # Configure SNMPv3 if enabled
        if bool(self._config['snmp']['auth']['version3']['enabled']):
            # TODO: configure SNMPv3 users from config file
            self._configure_snmp_v3(
                self._config['snmp']['auth']['version3']['users'])

        # configure pysnmp debugging
        # from pysnmp import debug
        # debug.setLogger(debug.Debug('io'))

        log.debug("TrapReceiver: Initialized")
Exemple #10
0
    def run(self):
        log.debug("%s: Started" % self.name)
        self._run = True
        backoff = 0
        while self._run:
            if backoff <= 0:
                try:
                    # pop event off queue
                    event = self._events.popleft()

                    success = False
                    # attempt to dispatch event
                    try:
                        success = self._trap_event_dispatcher.dispatch(event)
                    except Exception as err:
                        print(traceback.format_exc())

                    if not success:
                        # dispatch failed. put the event back on the queue
                        self._events.appendleft(event)

                        # back off
                        backoff = int(self._config['dispatcher']['backoff'])

                        log.debug("TrapDispatcherThread: back off for %d seconds" % backoff)

                except IndexError:
                    # Nothing in queue
                    pass

            else:
                backoff -= 1

            time.sleep(1)

        log.debug("%s: Exiting" % self.name)
Exemple #11
0
 def run(self):
     log.debug("%s: Started" % self.name)
     self._trap_receiver.run()
     log.debug("%s: Exiting" % self.name)
Exemple #12
0
 def load_mib(self, mib):
     self._mib_builder.loadModules(mib, )
     log.debug("MibResolver: Loaded MIB: %s" % mib)
Exemple #13
0
 def load_mib_dir(self, path):
     self._mib_sources += (pysnmp.smi.builder.DirMibSource(path),)
     log.debug("MibResolver: Loaded MIB source: %s" % path)
     self._mib_builder.setMibSources(*self._mib_sources)
Exemple #14
0
 def _configure_snmp_v2(self, community):
     # v1/2 setup
     pysnmp.entity.config.addV1System(self._snmp_engine,
                                      'nagios-trapd-agent', community)
     log.debug("TrapReceiver: Initialized SNMPv1 Auth")
Exemple #15
0
 def run(self):
     log.debug("%s: Started" % self.name)
     self._trap_receiver.run()
     log.debug("%s: Exiting" % self.name)
Exemple #16
0
 def _configure_snmp_v2(self, community):
     # v1/2 setup
     pysnmp.entity.config.addV1System(self._snmp_engine, 'nagios-trapd-agent', community)
     log.debug("TrapReceiver: Initialized SNMPv1 Auth")
Exemple #17
0
 def load_mib(self, mib):
     self._mib_builder.loadModules(mib, )
     log.debug("MibResolver: Loaded MIB: %s" % mib)
Exemple #18
0
 def load_mib_dir(self, path):
     self._mib_sources += (pysnmp.smi.builder.DirMibSource(path), )
     log.debug("MibResolver: Loaded MIB source: %s" % path)
     self._mib_builder.setMibSources(*self._mib_sources)
Exemple #19
0
    def __init__(self, config):
        self._config = config
        self._device_requester = DeviceRequester(config)

        log.debug("TrapEventDispatcher: Initialized")
Exemple #20
0
    def _notification_callback(self, snmp_engine, stateReference,
                               contextEngineId, contextName, varBinds, cbCtx):
        """
        Callback function for receiving notifications
        """
        trap_oid = None
        trap_name = None
        trap_args = dict()

        try:
            # get the source address for this notification
            transportDomain, trap_source = snmp_engine.msgAndPduDsp.getTransportInfo(
                stateReference)
            log.debug("TrapReceiver: Notification received from %s, %s" %
                      (trap_source[0], trap_source[1]))

            # read all the varBinds
            for oid, val in varBinds:
                # translate OID to mib symbol/modname
                (module, symbol) = self._mibs.lookup_oid(oid)

                if module == "SNMPv2-MIB" and symbol == "snmpTrapOID":
                    # the SNMPv2-MIB::snmpTrapOID value is the trap oid
                    trap_oid = val
                    # load the mib symbol/modname for the trap oid
                    (trap_symbol_name,
                     trap_mod_name) = self._mibs.lookup_oid(trap_oid)
                else:
                    # all other values should be converted to mib symbol/modname
                    # and put in the trap_data dict

                    # trap_arg_oid = oid
                    # For the case the faultIndex was added into the OID, we have to lookup
                    # the original OID from MIB instead of using the OID in the received packet directly.
                    trap_arg_oid = self._mibs.lookup(module, symbol)
                    # convert value
                    trap_arg_value = self._mibs.lookup_value(
                        module, symbol, val)
                    trap_args[trap_arg_oid] = trap_arg_value

                log.debug("TrapReceiver: Trap argument: %s, %s = %s" %
                          (module, symbol, val))

            # get trap source info
            trap_source_address, trap_source_port = trap_source
            trap_source_hostname, trap_source_domain = get_hostname_from_address(
                trap_source_address)

            # set trap propreties
            trap_properties = dict()
            trap_properties['hostname'] = trap_source_hostname
            trap_properties['ipaddress'] = trap_source_address
            trap_properties['domain'] = trap_source_domain

            # create trap
            trap = self._create_trap(trap_oid, trap_args, trap_properties)

            # now that everything has been parsed, trigger the callback
            self._callback(trap)

        except Exception as ex:
            log.exception("Error handling SNMP notification")