pysnmp:重用迭代器来遍历几个 OID?

问题描述

我正在使用 pysnmp 查询多个 oid 范围。我需要使用 nxtCmd 因为这些我需要遍历,例如,所有的 IF 地址。但是,当我在走路时使用 lexicographicMode=False 来防止跨越 OID 障碍时,我无法重用相同的迭代器来使用“发送”查询新范围,因为我收到了 stopiteration 错误(迭代器已耗尽)。每次都实例化一个新的迭代器的解决方案是什么?我是否错误地处理了这个问题?

代码

iterator = nextCmd(SnmpEngine(),CommunityData('public'),UdpTransportTarget(('localhost',161)),ContextData(),ObjectType(ObjectIdentity('1.3.6.1.2.1.4.20.1.1')),lexicographicMode=False)

for (errorIndication,errorStatus,errorIndex,varBinds) in iterator:

    if errorIndication:
        print(errorIndication)
        break
    
    elif errorStatus:
        print('%s at %s' % (errorStatus.prettyPrint(),errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
        break
    
    else:
        for varBind in varBinds:
            print(type(varBind))
            print(' = '.join([x.prettyPrint() for x in varBind]))

errorIndication,varBinds = iterator.send(ObjectType(ObjectIdentity('1.3.6.1.2.1.4.20.1.1')))
print(varBinds[1].prettyPrint)

一个循环有效,send 命令产生一个 stopiteration 异常

解决方法

是的,如果迭代器用完了,你就不能重用它。

然而,即使有迭代器和 generators are similar,也只有生成器支持 send 方法。

我会首先检查 nextCmd 是否明确返回了一个生成器,如果确实如此,请查看这篇文章:How to Use .send(),它会给你一个例子。