Esempio n. 1
0
    def run(self):
        """ Main Transport Dispatcher Loop """
        # Create SNMP engine with auto generated engineID and pre-bound
        # to socket transport dispatcher
        self.snmp_engine = engine.SnmpEngine()

        # Transport setup
        ip_address, net_mask = get_net_addresses()
        # UDP over IPv4, first listening interface/port
        config.addSocketTransport(
            self.snmp_engine, udp.domainName + (1, ),
            udp.UdpTransport().openServerMode((ip_address, SNMP_TRAP_PORT)))

        # SNMPv1/2c setup
        # SecurityName <-> CommunityName mapping
        config.addV1System(self.snmp_engine, 'my-area', SNMP_TRAP_COMMUNITY)

        # Register SNMP Application at the SNMP engine
        ntfrcv.NotificationReceiver(self.snmp_engine, self.callback_function)

        # this job would never finish
        self.snmp_engine.transportDispatcher.jobStarted(1)

        # Run I/O dispatcher which would receive queries and send confirmations
        try:
            self.snmp_engine.transportDispatcher.runDispatcher()
        except:
            self.snmp_engine.transportDispatcher.closeDispatcher()
            raise
Esempio n. 2
0
def initialize_snmp_listener(community, port):

    # Bind SNMP to socket transport dispatcher
    snmpEngine = engine.SnmpEngine()

    # Transport setup
    # UDP over IPv4, first listening interface/port
    config.addTransport(snmpEngine, udp.domainName + (1, ),
                        udp.UdpTransport().openServerMode(('0.0.0.0', port)))
    logger.debug(f'listening on port: {port} - the standard port is 162')

    # SNMPv1/2c setup
    # SecurityName <-> CommunityName mapping
    config.addV1System(snmpEngine, 'my-area', community)

    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmpEngine, handle_mac_notification)

    snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish

    # Run I/O dispatcher which would receive queries and send confirmations
    try:
        logger.debug(f"SNMP Engine running")
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        logger.debug(f"SNMP Engine failure ")
        raise
Esempio n. 3
0
    def __one_time_init(self):
        self.listen_address = '0.0.0.0'  # Set by TrapEngine
        self.listen_port = 162  # Set by TrapEngine
        self.owner = None  # Set by TrapEngine
        self.trap_view = None  # Set by TrapEngine
        self.trap_log = None  # Set by TrapEngine
        self.socket_map = socketmap.SocketMap()
        self.snmpEngine = engine.SnmpEngine()
        transportDispatcher = dispatch.AsynsockDispatcher()
        transportDispatcher.setSocketMap(self.socket_map)
        self.snmpEngine.registerTransportDispatcher(transportDispatcher)
        # @note As of PySNMP 4.1.9a, receipt of a V3 notification with out
        #       any registerred V3 users results in a traceback.
        self.addV3User('\0', config.usmNoAuthProtocol, '\0' * 8,
                       config.usmNoPrivProtocol, '\0' * 8)

        def cbFun(snmpEngine, contextEngineId, contextName, varBinds,
                  trap_thread):
            trap_thread._TrapThread__callback(contextEngineId, contextName,
                                              varBinds)
            return

        self.receiver = ntfrcv.NotificationReceiver(self.snmpEngine, cbFun,
                                                    self)
        # Setup transport endpoint
        config.addSocketTransport(
            self.snmpEngine, udp.domainName,
            udp.UdpSocketTransport().openServerMode(
                (self.listen_address, self.listen_port)))
        return
Esempio n. 4
0
    def run(self):

        snmpEngine = engine.SnmpEngine()

        if self.ipv6:
            domainName = udp6.domainName
            config.addSocketTransport(
                snmpEngine, domainName,
                udp6.Udp6Transport().openServerMode((self.host, self.port)))
        else:
            domainName = udp.domainName
            config.addSocketTransport(
                snmpEngine, domainName,
                udp.UdpTransport().openServerMode((self.host, self.port)))

        config.addV3User(snmpEngine, self.user, self.auth_proto, self.auth_key,
                         self.priv_proto, self.priv_key)

        # Register SNMP Application at the SNMP engine
        ntfrcv.NotificationReceiver(snmpEngine, v3trapCallback)

        snmpEngine.transportDispatcher.jobStarted(
            1)  # this job would never finish

        # Run I/O dispatcher which would receive queries and send confirmations
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except:  # catch *all* exceptions
            e = sys.exc_info()[1]
            snmpEngine.transportDispatcher.closeDispatcher()
            logging.error("Looks like an error: %s" % str(e))
            sys.exit(1)
    def __init__(self, controller, cfg):
        threading.Thread.__init__(self)
        self.controller = controller
        self.cfg = cfg
        self.snmp_engine = engine.SnmpEngine()
        self.count = 0
        # Transport setup
        ipv4 = True
        if IPAddress(self.cfg.snmp.snmp_ip).version == 6:
            ipv4 = False
        # Transport setup
        if ipv4:
            # UDP over IPv4, first listening interface/port
            config.addSocketTransport(
                self.snmp_engine, udp.domainName + (1, ),
                udp.UdpTransport().openServerMode(
                    (self.cfg.snmp.snmp_ip, self.cfg.snmp.snmp_port)))
        else:
            # UDP over IPv6, first listening interface/port
            config.addSocketTransport(
                self.snmp_engine, udp6.domainName + (1, ),
                udp6.Udp6Transport().openServerMode(
                    (self.cfg.snmp.snmp_ip, self.cfg.snmp.snmp_port)))
        # SecurityName <-> CommunityName mapping
        config.addV1System(self.snmp_engine, self.cfg.snmp.snmp_sec_area,
                           self.cfg.snmp.snmp_comm_str)

        ntfrcv.NotificationReceiver(self.snmp_engine, self.cb_fun)
Esempio n. 6
0
    def traprcv(self):
        """Create SNMP engine with autogenernated engineID and pre-bound to socket transport dispatcher"""
        snmpEngine = engine.SnmpEngine()

        """Transport setup  # UDP over IPv4, first listening interface/port"""
        config.addTransport(
            snmpEngine,
            udp.domainName + (1,),
            udp.UdpTransport().openServerMode((self.hosta, self.porta))
        )

        """UDP over IPv4, second listening interface/port"""
        config.addTransport(
            snmpEngine,
            udp.domainName + (2,),
            udp.UdpTransport().openServerMode((self.hostb, self.portb))
        )

        """SNMPv1/2c setup # SecurityName <-> CommunityName mapping"""
        config.addV1System(snmpEngine, 'my-area', 'public')

        """Register SNMP Application at the SNMP engine"""
        ntfrcv.NotificationReceiver(snmpEngine, self.cbFun)
        """this job would never finish"""
        snmpEngine.transportDispatcher.jobStarted(1)

        """Run I/O dispatcher which would receive queries and send confirmations"""
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except IOError:
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
        finally:
            pass
Esempio n. 7
0
def run_trap_listener():
    if not traffy_config.ENABLE_SNMP:
        print("SNMP not enabled! Exiting...")
        exit()

    if not traffy_config.ENABLE_TRAP:
        print("Trap not enabled! Exiting...")
        exit()

    snmp_engine = engine.SnmpEngine()
    config.addTransport(
        snmp_engine, udp.domainName,
        udp.UdpTransport().openServerMode(
            ("0.0.0.0", traffy_config.TRAP_PORT)))

    for id in traffy_config.SWITCHES:
        config.addV3User(snmp_engine,
                         traffy_config.SWITCHES[id]["username"],
                         config.usmHMACSHAAuthProtocol,
                         traffy_config.SWITCHES[id]["password"],
                         config.usmDESPrivProtocol,
                         traffy_config.SWITCHES[id]["password"],
                         securityEngineId=v2c.OctetString(
                             hexValue=traffy_config.SWITCHES[id]["engine_id"]))

    ntfrcv.NotificationReceiver(snmp_engine, trap_callback)
    snmp_engine.transportDispatcher.jobStarted(1)

    try:
        snmp_engine.transportDispatcher.runDispatcher()
    except:
        snmp_engine.transportDispatcher.closeDispatcher()
Esempio n. 8
0
def listen(
    address=DEFAULT_ADDRESSS,
    port=DEFAULT_PORT,
    community=DEFAULT_COMMUNITY,
    mibs=DEFAULT_MIBS,
):
    """Listen to and SNMP trap and print events."""
    # Based on pySNMP example code.
    mib_builder = builder.MibBuilder()
    compiler.addMibCompiler(mib_builder)
    mib_builder.loadModules(*mibs)
    global _view_controller
    _view_controller = view.MibViewController(mib_builder)
    loop = asyncio.get_event_loop()
    snmp_engine = engine.SnmpEngine()
    print(f"Agent is listening SNMP Trap on {address}, Port: {port}")
    if port < 1024:
        print(
            "WARNING: Port < 1024. Root priviledges or authbind required on *nix systems."
        )
    print("-" * 79)
    config.addTransport(
        snmp_engine,
        udp.domainName + (1, ),
        udp.UdpTransport().openServerMode((address, port)),
    )
    config.addV1System(snmp_engine, community, community)
    ntfrcv.NotificationReceiver(snmp_engine, _listen_callback)
    print("Press CTRL-C to quit.")
    loop.run_forever()
Esempio n. 9
0
def receiveTraps():  #checks for incoming traps
    try:
        snmpEngine = SnmpEngine()
        TrapAgentAddress = 'localhost'
        Port = 162

        print("Now listening for Trap on " + TrapAgentAddress + ":" +
              str(Port) + "...\n")
        config.addTransport(
            snmpEngine, udp.domainName + (1, ),
            udp.UdpTransport().openServerMode((TrapAgentAddress, Port)))

        config.addV1System(snmpEngine, 'community', 'public')

        def trapOutput(snmpEngine, stateReference, contextEngineId,
                       contextName, varBinds, cbCtx):
            print("Received new Trap message")
            for name, val in varBinds:  #iterates through each received oid pair
                print('%s = %s' %
                      (name.prettyPrint(),
                       val.prettyPrint()))  #pretty Print to make it readable
            return

        ntfrcv.NotificationReceiver(snmpEngine, trapOutput)

        snmpEngine.transportDispatcher.jobStarted(1)
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except:
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
    except KeyboardInterrupt:
        return
Esempio n. 10
0
    def _setup(self):
        """ Setup Server """
        assert isinstance(self._callbacks, list), \
            "callbacks should be list of functions type not %s" % type(
                self._callbacks)

        snmp_engine = engine.SnmpEngine()
        build = snmp_engine.getMibBuilder()

        if self._add_mib_dir:
            if not os.path.exists(self._add_mib_dir):
                raise PiatError("mib dir does not exist, dir=%r" %
                                self._add_mib_dir)
            if not os.path.isdir(self._add_mib_dir):
                raise PiatError(
                    "add_mib_dir should be a directory not a file, add_mib_dir=%r"
                    % self._add_mib_dir)
            build.addMibSources(builder.DirMibSource(self._add_mib_dir))

        build.loadModules()
        viewer = view.MibViewController(build)
        # UDP over IPv4, first listening interface/port
        transport = udp.UdpTransport()
        config.addTransport(snmp_engine, udp.domainName + (1, ),
                            transport.openServerMode(('0.0.0.0', self._port)))
        # SecurityName <-> CommunityName mapping
        config.addV1System(snmp_engine, '????', self._community)
        # Register SNMP Application at the SNMP engine
        handler = TrapsHandler(self._callbacks, viewer)
        ntfrcv.NotificationReceiver(snmp_engine, handler.handle)
        self._snmpEngine = snmp_engine
Esempio n. 11
0
    def start(self):
        """Starts the snmp trap receiver with necessary prerequisites."""
        snmp_engine = engine.SnmpEngine()
        self.snmp_engine = snmp_engine

        try:
            # Load all the mibs and do snmp config
            self._mib_builder()

            self._load_snmp_config()

            # Register callback for notification receiver
            ntfrcv.NotificationReceiver(snmp_engine, self._cb_fun)

            # Add transport info(ip, port) and start the listener
            self._add_transport()

            snmp_engine.transportDispatcher.jobStarted(
                constants.SNMP_DISPATCHER_JOB_ID)
        except Exception as e:
            LOG.error(e)
            raise ValueError("Failed to setup for trap listener.")

        try:
            LOG.info("Starting trap receiver.")
            snmp_engine.transportDispatcher.runDispatcher()
        except Exception:
            snmp_engine.transportDispatcher.closeDispatcher()
            raise ValueError("Failed to start trap listener.")
def main():
    app_config = _parse_args()

    port = app_config["port"]
    address4 = ('0.0.0.0', port)
    address6 = ('::1', port)

    zmq_context = zmq.Context()
    snmptrapd_out = wiring.Wire('collector_out',
                                zmq_context=zmq_context,
                                conf_path=app_config.get('wiring_conf_path')
                                or None)

    snmpEngine = getSNMPEngine(address4, address6,
                               app_config["snmpv12_agents"],
                               app_config["SNMPv3_users"])
    cbCtx = {
        "out_wire": snmptrapd_out,
        "MIBView": getMIBViewer(),
        "app_config": app_config,
        "last_col_ts": 0,
        "log_counter": 0
    }
    ntfrcv.NotificationReceiver(snmpEngine, cbFun, cbCtx)
    snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish
    snmpEngine.transportDispatcher.runDispatcher()
Esempio n. 13
0
def main():
    # Instantiate snmp engine
    snmpEngine = engine.SnmpEngine()

    # Load MIBs (for translation of the numeric OIDs)
    mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB')
    mibViewController = view.MibViewController(mibBuilder)

    # Transport setup
    # UDP over IPv6, listening interface/port
    config.addTransport(
        snmpEngine,
        udp6.domainName + (1,),
        udp6.Udp6Transport().openServerMode(('::', TRAP_PORT))
    )

    # SNMPv2c setup
    # SecurityName <-> CommunityName mapping
    config.addV1System(snmpEngine, 'my-area', 'public')


    # Callback function for receiving notifications
    # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
    def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
            varBinds, cbCtx):
        # Translate numerical OIDs into human readable form
        varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]

        # Turn on write permission for everyone
        os.umask(0)
        # Open file, append new data at the end
        with open(os.open(TRAP_LOG_PATH, os.O_CREAT | os.O_WRONLY, 0o777), 'a+') as f:
            t = time.gmtime()
            f.write('TRAP received on %s from ContextEngineId "%s", ContextName "%s" \n' % (time.strftime('%c', t), contextEngineId.prettyPrint(),
                                                                            contextName.prettyPrint()))
            # Write data in file
            for varbind in varBinds:
                f.write(varbind.prettyPrint()+'\n')
            f.write('\n')
            
    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmpEngine, cbFun)

    snmpEngine.transportDispatcher.jobStarted(1)  # Start a job that will never finish

    # Run I/O dispatcher which would receive queries and send confirmations
    try:
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
Esempio n. 14
0
 def register(self):
     """
     registers the engine & callback
     """
     for servermode in self.transports:
         task = self.transports[servermode]._lport
         if task.done():
             log.error("Error setting up {}: {}".format(
                 servermode, task.exception()))
         else:
             log.info("Started {}".format(servermode))
     ntfrcv.NotificationReceiver(self._engine, self._notification_callback)
     log.info('Registered callback')
     return True
Esempio n. 15
0
    def run(self):
        # Register SNMP Application at the SNMP engine
        ntfrcv.NotificationReceiver(self._snmp_engine,
                                    self._notification_callback)

        self._snmp_engine.transportDispatcher.jobStarted(
            1)  # this job would never finish

        # Run I/O dispatcher which would receive queries and send confirmations
        try:
            self._snmp_engine.transportDispatcher.runDispatcher()
        except:
            self._snmp_engine.transportDispatcher.closeDispatcher()
            raise
Esempio n. 16
0
    def trap_receiver(self):

        self.ntfrcv = ntfrcv.NotificationReceiver(self.snmpEngine, self.cbFun)

        self.snmpEngine.transportDispatcher.jobStarted(
            1)  # this job would never finish

        try:
            self.snmpEngine.transportDispatcher.runDispatcher()
        except:
            self.snmpEngine.transportDispatcher.closeDispatcher()
            raise
        if self.stopped:
            return
Esempio n. 17
0
 def run(self):
     """Run collector and start processing incoming traps"""
     config.addSocketTransport(
         self.snmp_engine,
         udp.domainName + (1, ),
         udp.UdpTransport().openServerMode(("0.0.0.0", 162)),
     )
     config.addV1System(self.snmp_engine, "new", "public")
     config.addContext(self.snmp_engine, "")
     ntfrcv.NotificationReceiver(self.snmp_engine, self.process_trap)
     self.snmp_engine.transportDispatcher.jobStarted(1)
     try:
         self.snmp_engine.transportDispatcher.runDispatcher()
     except Exception:
         self.snmp_engine.transportDispatcher.closeDispatcher()
         raise
Esempio n. 18
0
def trap_receiver():

    myAddress = socket.gethostbyname(socket.gethostname())
    snmpEngine = engine.SnmpEngine()
    TrapAgentAddress = myAddress
    Port = 162
    config.addTransport(
        snmpEngine, udp.domainName + (1, ),
        udp.UdpTransport().openServerMode((TrapAgentAddress, Port)))
    config.addV1System(snmpEngine, 'my-area', 'public')
    ntfrcv.NotificationReceiver(snmpEngine, cbFun)
    snmpEngine.transportDispatcher.jobStarted(1)
    try:
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
Esempio n. 19
0
    def __init__(self):
        self.snmpEngine = engine.SnmpEngine()

        config.addSocketTransport(
            self.snmpEngine, udp.domainName,
            udp.UdpSocketTransport().openServerMode(('0.0.0.0', 162)))

        config.addV1System(self.snmpEngine, 'test-agent', 'public')

        config.addV3User(
            self.snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol,
            'authkey1', config.usmDESPrivProtocol, 'privkey1'
            #    '80004fb81c3dafe69'   # ContextEngineID of Notification Originator
        )
        # Apps registration
        ntfrcv.NotificationReceiver(self.snmpEngine, self.recvcallback)
        self.snmpEngine.transportDispatcher.jobStarted(
            1)  # this job would never finish
        self.snmpEngine.transportDispatcher.runDispatcher()
Esempio n. 20
0
    def __init__(self, out_q):
        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher
        snmpEngine = engine.SnmpEngine()

        # Transport setup

        # UDP over IPv4, first listening interface/port
        config.addTransport(snmpEngine, udp.domainName + (1, ),
                            udp.UdpTransport().openServerMode((IP, 162)))

        # SNMPv1/2c setup

        # SecurityName <-> CommunityName mapping
        config.addV1System(snmpEngine, 'my-area', 'public')

        # Callback function for receiving notifications
        # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
        def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
                  varBinds, cbCtx):
            print('Notification from ContextEngineId "%s", ContextName "%s"' %
                  (contextEngineId.prettyPrint(), contextName.prettyPrint()))
            for name, val in varBinds:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))

            out_q.put("teste")

        # Register SNMP Application at the SNMP engine
        if ntfrcv.NotificationReceiver(snmpEngine, cbFun):
            print "HEEEE"

        snmpEngine.transportDispatcher.jobStarted(
            1)  # this job would never finish

        # Run I/O dispatcher which would receive queries and send confirmations
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except:
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
Esempio n. 21
0
def trap_engine():
    snmpEngine = engine.SnmpEngine()
    print('[SNMP API] Trap Server listening on ' + listening_ip + ":" +
          str(listening_port))
    config.addTransport(
        snmpEngine, udp.domainName + (1, ),
        udp.UdpTransport().openServerMode((listening_ip, listening_port)))
    config.addV1System(snmpEngine, 'my-area', 'public')

    def callback(eng, ref, eng_id, name, var_binds, cb_ctx):
        sender_domain, sender_address = eng.msgAndPduDsp.getTransportInfo(ref)
        if not trap_list.__contains__(sender_address[0]):
            trap_list.append(sender_address[0])

    ntfrcv.NotificationReceiver(snmpEngine, callback)
    snmpEngine.transportDispatcher.jobStarted(1)

    try:
        snmpEngine.transportDispatcher.runDispatcher()
    finally:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
Esempio n. 22
0
# Callback function for receiving notifications
# noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
          varBinds, cbCtx):
	logTime=datetime.now().strftime("%m/%d/%Y-%H:%M:%S.%f")[:-3]
	writeLogs('\n\n{}\nNotification from ContextEngineId "{}", ContextName "{}"'.format(logTime,contextEngineId.prettyPrint(), contextName.prettyPrint()))
	print('\nNotification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(),
																		contextName.prettyPrint()))

	varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds]
	for varBind in varBinds:
		writeLogs('\n' + varBind.prettyPrint())
		print(varBind.prettyPrint())
	
	writeLogs('\n')


# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmpEngine, cbFun)

snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish

# Run I/O dispatcher which would receive queries and send confirmations
try:
    snmpEngine.transportDispatcher.runDispatcher()
except:
    snmpEngine.transportDispatcher.closeDispatcher()
    raise

class TrapReceiver(object):
    '''
    ' 接受Trap数据,构造trap数据对象并调用相应处理
    ' methods:
    '     start: 启动监听进程
    '''
    def __init__(self, configdata):
        self._configdata = configdata

    def start(self):
        '''
        ' 启动监听进程
        ' raise Exception: 异常停止时抛出
        '''
        logger.info('Start trap listener...')
        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher
        snmpEngine = engine.SnmpEngine()

        # Transport setup
        # UDP over IPv4
        config.addSocketTransport(
            snmpEngine,
            udp.domainName,
            udp.UdpTransport().openServerMode((self._configdata.Localaddress, \
                                             self._configdata.Listenport))
        )

        try:
            for agentip in self._configdata.Hostdata.keys():
                issuccess = self._configdata.Hostdata[agentip][
                    HOST_CFG_KEY_ISSUCCESS]
                if issuccess != True:
                    continue
                version = self._configdata.Hostdata[agentip][
                    HOST_CFG_KEY_TRAPSNMPVERSION]
                if 'V3' == version.upper():
                    # SNMPv3/USM setup
                    authProtocol = str(self._configdata.Hostdata[agentip]
                                       [HOST_CFG_KEY_AUTHPROTOCOL])
                    privProtocol = str(self._configdata.Hostdata[agentip]
                                       [HOST_CFG_KEY_PRIVPROTOCOL])
                    username = str(
                        self._configdata.Hostdata[agentip][HOST_CFG_KEY_USER])
                    password = str(
                        self._configdata.Hostdata[agentip][HOST_CFG_KEY_PASS])
                    enginid = str(self._configdata.Hostdata[agentip]
                                  [HOST_CFG_KEY_ENGINID])

                    if enginid is None or enginid == '':
                        logger.info(
                            "enginid is null,please check device,ipaddr :" +
                            str(agentip))
                        strEnginid = None
                    else:
                        strEnginid = v2c.OctetString(hexValue=enginid)

                    if authProtocol == 'MD5' and privProtocol == "DES":
                        config.addV3User(snmpEngine,
                                         username,
                                         config.usmHMACMD5AuthProtocol,
                                         password,
                                         config.usmDESPrivProtocol,
                                         password,
                                         contextEngineId=strEnginid)
                    elif authProtocol == 'MD5' and privProtocol == "AES":
                        config.addV3User(snmpEngine,
                                         username,
                                         config.usmHMACMD5AuthProtocol,
                                         password,
                                         config.usmAesCfb128Protocol,
                                         password,
                                         contextEngineId=strEnginid)
                    elif authProtocol == 'SHA' and privProtocol == "DES":
                        config.addV3User(snmpEngine,
                                         username,
                                         config.usmHMACSHAAuthProtocol,
                                         password,
                                         config.usmDESPrivProtocol,
                                         password,
                                         contextEngineId=strEnginid)
                    elif authProtocol == 'SHA' and privProtocol == "AES":
                        config.addV3User(snmpEngine,
                                         username,
                                         config.usmHMACSHAAuthProtocol,
                                         password,
                                         config.usmAesCfb128Protocol,
                                         password,
                                         contextEngineId=strEnginid)
                else:
                    # v1/2 setup
                    trapcommunity = str(self._configdata.Hostdata[agentip]
                                        [HOST_CFG_KEY_TRAPCOMMUNITY])
                    config.addV1System(snmpEngine, 'test-agent', trapcommunity)
        except Exception, err:
            logger.error("cache userinfor ,error :" + str(err))
            snmpEngine.transportDispatcher.closeDispatcher()
            raise

        # Register SNMP Application at the SNMP engine
        # Run I/O dispatcher which would receive queries and send confirmations
        try:

            ntfrcv.NotificationReceiver(snmpEngine, self._cbHandler)
            # this job would never finish
            snmpEngine.transportDispatcher.jobStarted(1)
            logger.info('Plugin working now...')
            snmpEngine.transportDispatcher.runDispatcher()
            logger.info("transportDispatcher start successfully.")

        except Exception, err:
            logger.error("transportDispatcher close,error :" + str(err))
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
Esempio n. 24
0
def snmpv3_trap(user='',
                hash_meth=None,
                hash_key=None,
                cry_meth=None,
                cry_key=None,
                engineid='',
                ip='127.0.0.1',
                port=162):
    # Create SNMP engine with autogenernated engineID and pre-bound
    snmp_engine = engine.SnmpEngine()

    config.addSocketTransport(snmp_engine, udp.domainName,
                              udp.UdpTransport().openServerMode((ip, port)))

    # usmHMACMD5AuthProtocol - MD5 hashing
    # usmHMACSHAAuthProtocol - SHA hashing
    # usmNoAuthProtocol - no authentication
    # usmDESPrivProtocol - DES encryption
    # usm3DESEDEPrivProtocol - triple-DES encryption
    # usmAesCfb128Protocol - AES encryption, 128-bit
    # usmAesCfb192Protocol - AES encryption, 192-bit
    # usmAesCfb256Protocol - AES encryption, 256-bit
    # usmNoPrivProtocol - no encryption

    # NoAuthNoPriv
    if hash_meth is None and cry_meth is None:
        hashval = config.usmNoAuthProtocol
        cryval = config.usmNoPrivProtocol
    # AuthNoPriv
    elif hash_meth is not None and cry_meth is None:
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        cryval = config.usmNoPrivProtocol
    # AuthPriv
    elif hash_meth is not None and cry_meth is not None:
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        if cry_meth == '3des':
            cryval = config.usm3DESEDEPrivProtocol
        elif cry_meth == 'des':
            cryval = config.usmDESPrivProtocol
        elif cry_meth == 'aes128':
            cryval = config.usmAesCfb128Protocol
        elif cry_meth == 'aes192':
            cryval = config.usmAesCfb192Protocol
        elif cry_meth == 'aes256':
            cryval = config.usmAesCfb256Protocol
        else:
            print('加密算法必须是3des, des, aes128, aes192 or aes256 !')
            return
    # 提供的参数不符合标准时给出提示
    else:
        print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。')
        return

    config.addV3User(snmp_engine,
                     user,
                     hashval,
                     hash_key,
                     cryval,
                     cry_key,
                     contextEngineId=v2c.OctetString(hexValue=engineid))

    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmp_engine, cb_fun)

    snmp_engine.transportDispatcher.jobStarted(
        1)  # this job would never finish

    # Run I/O dispatcher which would receive queries and send confirmations
    try:
        snmp_engine.transportDispatcher.runDispatcher()
    except Exception:
        snmp_engine.transportDispatcher.closeDispatcher()
        raise
Esempio n. 25
0
    for name, val in varBinds:
        # Append to output String
        szOut = szOut + ", Oid: {}, Value: {}".format(name.prettyPrint(),
                                                      val.prettyPrint())

        if isinstance(val, OctetString):
            if (name.prettyPrint() != "SNMP-COMMUNITY-MIB::snmpTrapAddress.0"):
                szOctets = val.asOctets()  #.rstrip('\r').rstrip('\n')
                szOut = szOut + ", Octets: {}".format(szOctets)
        if (bDebug):
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
    outputFile.write(szOut)
    if "\n" not in szOut:
        outputFile.write("\n")
    outputFile.flush()


# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmpEngine, cbReceiverSnmp)

# this job would never finish
snmpEngine.transportDispatcher.jobStarted(1)

# Run I/O dispatcher which would receive queries and send confirmations
try:
    snmpEngine.transportDispatcher.runDispatcher()
except:
    snmpEngine.transportDispatcher.closeDispatcher()
    raise
Esempio n. 26
0
    def do_run(self):
        '''
        Run sensor.
        '''
        # Too many branches.
        # pylint: disable=R0912

        from pysnmp.error import PySnmpError
        from pysnmp.entity import engine, config
        from pysnmp.carrier.asynsock.dgram import udp, udp6
        from pysnmp.entity.rfc3413 import ntfrcv
        from pysnmp.proto.api import v2c

        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher.
        snmp_engine = engine.SnmpEngine()

        # Transport setup.
        try:
            socket.inet_pton(socket.AF_INET, self.config['interface_ip'])
            # UDP over IPv4.
            config.addSocketTransport(
                snmp_engine,
                udp.domainName,
                udp.UdpTransport().openServerMode(
                    (self.config['interface_ip'], self.config['port'])
                )
            )
        except socket.error:
            try:
                socket.inet_pton(socket.AF_INET6, self.config['interface_ip'])
                # UDP over IPv6.
                config.addSocketTransport(
                    snmp_engine,
                    udp6.domainName,
                    udp6.Udp6Transport().openServerMode(
                        (self.config['interface_ip'], self.config['port'])
                    )
                )
            except socket.error:
                self.log('given interface_ip is neither IPv4 nor IPv6 address')
                return
        snmpv3_protocols = {
            'MD5': config.usmHMACMD5AuthProtocol,
            'SHA': config.usmHMACSHAAuthProtocol,
            'DES': config.usmDESPrivProtocol,
            '3DES': config.usm3DESEDEPrivProtocol,
            'AES128': config.usmAesCfb128Protocol,
            'AES192': config.usmAesCfb192Protocol,
            'AES256': config.usmAesCfb256Protocol
        }

        def snmpv3_setup_args(version, authentication=None, encryption=None,
                              auth_key=None, encrypt_key=None, device_id=None):
            '''
            Helper function, parses args.
            '''
            # R0913: Too many arguments
            # pylint: disable=R0913
            del version
            del device_id
            args = [snmp_engine, 'usr-{}-{}'.format(
                authentication.lower() if authentication else 'none',
                encryption.lower() if encryption else 'none'
            )]
            if authentication:
                # Expression not assigned
                # pylint: disable=W0106
                args.append(snmpv3_protocols[authentication]),
                args.append(auth_key)
            if encryption:
                # Expression not assigned
                # pylint: disable=W0106
                args.append(snmpv3_protocols[encryption]),
                args.append(encrypt_key)
            return args
        # Setup devices.
        for device in self.config['devices']:
            if device['version'] == 'v3':
                # SNMPv3 setup.
                if 'device_id' in device:
                    config.addV3User(
                        *snmpv3_setup_args(**device),
                        contextEngineId=v2c.OctetString(hexValue=device['device_id'])
                    )
                else:
                    config.addV3User(*snmpv3_setup_args(**device))
            else:
                # SNMPv1/2c setup.
                # SecurityName <-> CommunityName mapping.
                config.addV1System(
                    snmp_engine,
                    device['index'],
                    device['name']
                )

        def cb_fun(snmp_engine, state_reference, context_engine_id,
                   context_name, var_binds, cb_ctx):
            # Too many arguments
            # pylint: disable=R0913
            '''
            Callback function for receiving notifications.
            '''
            _, transport_address = snmp_engine.msgAndPduDsp.getTransportInfo(
                state_reference
            )
            for name, val in var_binds:
                self.send_results(datetime.utcnow(), (
                    ('sender', transport_address),
                    ('context_engine_id', context_engine_id.prettyPrint()),
                    ('context_name', context_name.prettyPrint()),
                    ('variable_name', name.prettyPrint()),
                    ('variable_value', val.prettyPrint())
                ))

        # Register SNMP Application at the SNMP engine.
        ntfrcv.NotificationReceiver(snmp_engine, cb_fun)

        # This job would never finish.
        snmp_engine.transportDispatcher.jobStarted(1)

        # Run I/O dispatcher which would receive queries and send confirmations.
        try:
            snmp_engine.transportDispatcher.runDispatcher()
        except PySnmpError as err:
            snmp_engine.transportDispatcher.closeDispatcher()
            self.send_results(datetime.utcnow(), (('error', err.message),))
            return
Esempio n. 27
0
def snmpv3_trap(user='',
                hash_meth=None,
                hash_key=None,
                cry_meth=None,
                cry_key=None,
                engineid=''):
    #usmHMACMD5AuthProtocol - MD5 hashing
    #usmHMACSHAAuthProtocol - SHA hashing
    #usmNoAuthProtocol - no authentication
    #usmDESPrivProtocol - DES encryption
    #usm3DESEDEPrivProtocol - triple-DES encryption
    #usmAesCfb128Protocol - AES encryption, 128-bit
    #usmAesCfb192Protocol - AES encryption, 192-bit
    #usmAesCfb256Protocol - AES encryption, 256-bit
    #usmNoPrivProtocol - no encryption
    hashval = None
    cryval = None

    #NoAuthNoPriv
    if hash_meth == None and cry_meth == None:
        hashval = config.usmNoAuthProtocol
        cryval = config.usmNoPrivProtocol
    #AuthNoPriv
    elif hash_meth != None and cry_meth == None:
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        cryval = config.usmNoPrivProtocol
    #AuthPriv
    elif hash_meth != None and cry_meth != None:
        if hash_meth == 'md5':
            hashval = config.usmHMACMD5AuthProtocol
        elif hash_meth == 'sha':
            hashval = config.usmHMACSHAAuthProtocol
        else:
            print('哈希算法必须是md5 or sha!')
            return
        if cry_meth == '3des':
            cryval = config.usm3DESEDEPrivProtocol
        elif cry_meth == 'des':
            cryval = config.usmDESPrivProtocol
        elif cry_meth == 'aes128':
            cryval = config.usmAesCfb128Protocol
        elif cry_meth == 'aes192':
            cryval = config.usmAesCfb192Protocol
        elif cry_meth == 'aes256':
            cryval = config.usmAesCfb256Protocol
        else:
            print('加密算法必须是3des, des, aes128, aes192 or aes256 !')
            return
    #提供的参数不符合标准时给出提示
    else:
        print('三种USM: NoAuthNoPriv, AuthNoPriv, AuthPriv.。请选择其中一种。')
        return

    # SNMPv3/USM setup
    # user: usr-md5-des, auth: MD5, priv DES, contextEngineId: 8000000001020304
    # this USM entry is used for TRAP receiving purposes
    config.addV3User(snmpEngine,
                     user,
                     hashval,
                     hash_key,
                     cryval,
                     cry_key,
                     contextEngineId=v2c.OctetString(hexValue=engineid))

    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmpEngine, cbFun)

    snmpEngine.transportDispatcher.jobStarted(1)  # this job would never finish

    # Run I/O dispatcher which would receive queries and send confirmations
    try:
        snmpEngine.transportDispatcher.runDispatcher()
    except:
        snmpEngine.transportDispatcher.closeDispatcher()
        raise
    def run(self):
        snmpEngine = engine.SnmpEngine()
        addTransport(snmpEngine, udp.domainName,
                     udp.UdpTransport().openServerMode((self.ip, self.port)))
        if self.securityEngineId:
            if self.snmpVer == "version3":
                addV3User(snmpEngine,
                          self.userName,
                          self.authProtocol,
                          self.authPass,
                          self.privProtocol,
                          self.privPass,
                          securityEngineId=v2c.OctetString(
                              hexValue=self.securityEngineId))
            else:
                addV1System(snmpEngine, self.comminutyIndex,
                            self.comminutyString)
            snmpVersion = self.snmpVer
            snmpUserName = self.userName

            def cbFun(snmpEngine, stateReference, contextEngineId, contextName,
                      varBinds, cbCtx):
                execContext = snmpEngine.observer.getExecutionContext(
                    'rfc3412.receiveMessage:request')
                USM = models.SnmpUsm.objects.get(SnmpUserName=snmpUserName,
                                                 SnmpVersion=snmpVersion)
                TrapConfiguration = models.RecievedTrapConfiguration.objects.filter(
                    SenderIP=execContext["transportAddress"][0], SnmpUser=USM)
                print(TrapConfiguration)

                if TrapConfiguration:
                    OidValue = {}

                    for name, val in varBinds:
                        models.TrapRecord.objects.create(
                            SnmpUsm=USM,
                            Name=name.prettyPrint(),
                            Value=val.prettyPrint(),
                            ContextName=contextName,
                            SenderIP=execContext["transportAddress"][0])
                        OidValue.update(
                            {name.prettyPrint(): val.prettyPrint()})

                    x = hierarchy.Checker({
                        "SenderIP":
                        execContext["transportAddress"][0],
                        "Authentication":
                        USM,
                        "EngineID":
                        self.securityEngineId,
                        "ContextEngineID":
                        contextEngineId.prettyPrint(),
                        "ContextName":
                        contextName.prettyPrint(),
                        "OidValue":
                        OidValue
                    })
                    x.start()
                else:
                    pass

        ntfrcv.NotificationReceiver(snmpEngine, cbFun)
        try:
            snmpEngine.transportDispatcher.jobStarted(1)
        except:
            print("nashod1")
        try:
            snmpEngine.transportDispatcher.runDispatcher()
        except:
            snmpEngine.transportDispatcher.closeDispatcher()
            raise
Esempio n. 29
0
    def start_listener(self,
                       callback,
                       address=None,
                       port=1162,
                       community='public',
                       timeout=TIMEOUT):
        '''
        Start a TRAP v1/v2c/v3 notification receiver with predefined users.

        @param callback: Takes these args snmpEngine, stateReference,
                         contextEngineId, contextName, varBinds, cbCtx
        @param address: The address to listen to
        @param port: The port to listen to
        @param community: The community name for v2c

        Predefined users:
        usr-md5-des
        usr-md5-none
        usr-sha-aes128

        Auth: authkey1
        Priv: privkey1
        '''
        if not address:
            address = get_local_ip(self.host)
        if timeout < 0:
            timeout = 10**10
        # Create SNMP engine with auto-generated engineID and pre-bound
        # to socket transport dispatcher
        snmpEngine = engine.SnmpEngine()

        # Transport setup
        if IPAddress(address).version == 4:
            # UDP over IPv4
            domain_oid = udp.domainName
            transport = udp.UdpTransport()
        else:
            # UDP over IPv6
            domain_oid = udp6.domainName
            transport = udp6.Udp6Transport()

        # Waiting up to TIMEOUT seconds for the port to be released
        LOG.debug('Waiting for port %s:%d to become available...', address,
                  port)
        transport = wait(lambda: transport.openServerMode((address, port)),
                         timeout=TIMEOUT,
                         interval=1)
        LOG.info('Listening for traps on %s:%d...', address, port)

        config.addSocketTransport(snmpEngine, domain_oid, transport)

        # Terrible monkey patching!!
        # But there's no other way to cause the dispatcher loop to end if we
        # don't get what we expect in a given amount of time. For now that time
        # is limited to TIMEOUT seconds.
        end = time.time() + timeout

        def jobsArePending(self):
            if self._AbstractTransportDispatcher__jobs and time.time() < end:
                return 1
            else:
                return 0

        snmpEngine.transportDispatcher.__class__.jobsArePending = jobsArePending

        # SNMPv1/2 setup
        config.addV1System(snmpEngine, 'test-agent', community)

        # SNMPv3/USM setup
        # user: usr-md5-des, auth: MD5, priv DES
        config.addV3User(snmpEngine, 'usr-md5-des',
                         config.usmHMACMD5AuthProtocol, 'authkey1',
                         config.usmDESPrivProtocol, 'privkey1')

        # user: usr-md5-des, auth: MD5, priv DES, contextEngineId: 8000000001020304
        # this USM entry is used for TRAP receiving purposes
        config.addV3User(
            snmpEngine,
            'usr-md5-des',
            config.usmHMACMD5AuthProtocol,
            'authkey1',
            config.usmDESPrivProtocol,
            'privkey1',
            contextEngineId=v2c.OctetString(hexValue='8000000001020304'))

        # user: usr-md5-none, auth: MD5, priv NONE
        config.addV3User(snmpEngine, 'usr-md5-none',
                         config.usmHMACMD5AuthProtocol, 'authkey1')

        # user: usr-md5-none, auth: MD5, priv NONE, contextEngineId: 8000000001020304
        # this USM entry is used for TRAP receiving purposes
        config.addV3User(
            snmpEngine,
            'usr-md5-none',
            config.usmHMACMD5AuthProtocol,
            'authkey1',
            contextEngineId=v2c.OctetString(hexValue='8000000001020304'))

        # user: usr-sha-aes128, auth: SHA, priv AES
        config.addV3User(snmpEngine, 'usr-sha-aes128',
                         config.usmHMACSHAAuthProtocol, 'authkey1',
                         config.usmAesCfb128Protocol, 'privkey1')
        # user: usr-sha-aes128, auth: SHA, priv AES, contextEngineId: 8000000001020304
        # this USM entry is used for TRAP receiving purposes
        config.addV3User(
            snmpEngine,
            'usr-sha-aes128',
            config.usmHMACSHAAuthProtocol,
            'authkey1',
            config.usmAesCfb128Protocol,
            'privkey1',
            contextEngineId=v2c.OctetString(hexValue='8000000001020304'))

        #         def sample_callback(snmpEngine, stateReference, contextEngineId, contextName,
        #                             varBinds, cbCtx):
        #             print('Notification received, ContextEngineId "%s", ContextName "%s"' % (
        #                   contextEngineId.prettyPrint(), contextName.prettyPrint())
        #             )
        #             for name, val in varBinds:
        #                 print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
        #             print

        # If callback() returns True we'll stop the loop
        def callback_wrapper(*args, **kwargs):
            if callback(*args, **kwargs):
                snmpEngine.transportDispatcher.jobFinished(DEFAULT_JOB)

        # Register SNMP Application at the SNMP engine
        ntfrcv.NotificationReceiver(snmpEngine, callback_wrapper)

        #return address, port
        t = TrapListener(snmpEngine)
        t.start()
        return address, port, t
Esempio n. 30
0
def main():
    # Get the event loop for this thread
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    # Create SNMP engine with autogenernated engineID and pre-bound
    # to socket transport dispatcher
    snmpEngine = engine.SnmpEngine()
    # UDP over IPv4, first listening interface/port
    config.addTransport(
        snmpEngine,
        udp.domainName,
        udp.UdpTransport().openServerMode(("0.0.0.0", 2162)),
    )
    with open(CONFIG_PATH, encoding="utf-8") as file:
        config_base = yaml.safe_load(file)
    idx = 0
    if "communities" in config_base:
        if "2c" in config_base["communities"]:
            for community in config_base["communities"]["2c"]:
                idx += 1
                config.addV1System(snmpEngine, idx, community)

    if "usernameSecrets" in config_base:
        for secret in config_base["usernameSecrets"]:
            location = os.path.join("secrets/snmpv3", secret)
            userName = get_secret_value(location,
                                        "userName",
                                        required=True,
                                        default=None)

            authKey = get_secret_value(location, "authKey", required=False)
            privKey = get_secret_value(location, "privKey", required=False)

            authProtocol = get_secret_value(location,
                                            "authProtocol",
                                            required=False)
            logging.debug(f"authProtocol: {authProtocol}")
            authProtocol = AuthProtocolMap.get(authProtocol.upper(), "NONE")

            privProtocol = get_secret_value(location,
                                            "privProtocol",
                                            required=False,
                                            default="NONE")
            logging.debug(f"privProtocol: {privProtocol}")
            privProtocol = PrivProtocolMap.get(privProtocol.upper(), "NONE")

            config.addV3User(
                snmpEngine,
                userName=userName,
                authProtocol=authProtocol,
                authKey=authKey,
                privProtocol=privProtocol,
                privKey=privKey,
                securityEngineId=v2c.OctetString(hexValue=SECURITY_ENGINE_ID),
            )
            logging.debug(
                f"V3 users: {userName} auth {authProtocol} authkey {authKey} privprotocol {privProtocol} "
                f"privkey {privKey} securityEngineId {SECURITY_ENGINE_ID}")

    # Register SNMP Application at the SNMP engine
    ntfrcv.NotificationReceiver(snmpEngine, cbFun)

    # Run asyncio main loop
    loop.run_forever()