Search code examples
pythonpysnmp

Access to varBinds of received TRAP


I don't get how to access varBinds from code example. I can print it, but what if I want to store it or pass to method or class?

Even if I store it in class, I can't access it further.


class TrapReceiver
    def __init__(self):
        # Create SNMP engine with autogenernated engineID and pre-bound
        # to socket transport dispatcher
        self.snmpEngine = engine.SnmpEngine()
        # Transport setup
        # UDP over IPv4, first listening interface/port
        config.addTransport(
            self.snmpEngine,
            udp.domainName + (1,),
            udp.UdpTransport().openServerMode(('127.0.0.1', 162))
        )
        # SNMPv1/2c setup
        # SecurityName <-> CommunityName mapping
        config.addV1System(self.snmpEngine, 'my-area', 'public')
    # Callback function for receiving notifications
    # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal
    def cbFun(self,snmpEngine, stateReference, contextEngineId, contextName,
                  varBinds, cbCtx):
            for varBind in varBinds:
                oid, value = varBind
                trap_source = str(oid)
                trap_val = int(value)
                #TODO: return trap_source, trap_val

    def run(self):
        # Register SNMP Application at the SNMP engine
        ntfrcv.NotificationReceiver(self.snmpEngine, self.cbFun)

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

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

Solution

  • You can't "return" anything from a callback function. Because its caller (main loop) is not interested in its return value.

    Therefore you should use cbCtx or some other global object (e.g. dict) to pass information received in the callback function to other parts of the application. The cbCtx object can be initially passed to NotificationReceiver, then it appears in the callback function.

    So for example you can have notification receiver in one thread pushing received data into the cbCtx data structure (it can be Queue for instance), then another thread popping items from that Queue and processing them.

    Or you can process received data right inside the callback function. Just make sure it's non-blocking.