访问接收到的陷阱的varBinds

2024-09-28 21:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道如何从代码示例中访问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

Tags: andselfconfigfordefsetupenginesnmp
1条回答
网友
1楼 · 发布于 2024-09-28 21:31:38

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

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

例如,您可以让一个线程中的通知接收者将接收到的数据推入cbCtx数据结构(例如,它可以是Queue),然后另一个线程从该Queue弹出项目并处理它们

或者可以在回调函数内部处理接收到的数据。确保它是非阻塞的

相关问题 更多 >