访问已接收的TRAP的varBinds

时间:2019-05-13 21:56:11

标签: python pysnmp

我没有从代码示例中获取如何访问varBinds的信息。我可以打印它,但是如果我要存储它或将其传递给方法或类怎么办?

即使将其存储在类中,也无法进一步访问它。


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

1 个答案:

答案 0 :(得分:1)

您不能从回调函数“返回”任何东西。因为其调用者(主循环)对其返回值不感兴趣。

因此,您应该使用cbCtx或其他一些全局对象(例如dict)将在回调函数中接收到的信息传递给应用程序的其他部分。首先可以将cbCtx对象传递给NotificationReceiver,然后将其显示在回调函数中。

例如,您可以在一个线程中具有通知接收器,该线程将接收到的数据推入cbCtx数据结构(例如可以为Queue),然后另一个线程从该{{1} }并对其进行处理。

或者您可以直接在回调函数中处理接收到的数据。只要确保它没有阻塞即可。

相关问题