我是python的新手。我试图了解pysnmp的用法。
我尝试了以下方法:
import asyncio
from pysnmp.hlapi.asyncio import *
from pysnmp import debug
@asyncio.coroutine
def run():
snmpEngine = SnmpEngine()
while True:
errorIndication, errorStatus, errorIndex, varBinds = yield from nextCmd(
snmpEngine,
CommunityData('public', mpModel=1),
UdpTransportTarget(('giga-int-2', 161)),
ContextData(),
ObjectType(ObjectIdentity('1.3.6.1.2.1.31.1.1.1.1')),
lexicographicMode=False
)
if errorIndication:
print(errorIndication)
break
elif errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?')
)
else:
for varBind in varBinds:
for v in varBind:
print(' = '.join([x.prettyPrint() for x in v]))
snmpEngine.transportDispatcher.closeDispatcher()
asyncio.get_event_loop().run_until_complete(run())
结果,我总是得到相同的界面。怎么了?为什么不检索下一个元素?
SNMPv2-SMI::mib-2.31.1.1.1.1.1 = sc0
SNMPv2-SMI::mib-2.31.1.1.1.1.1 = sc0
SNMPv2-SMI::mib-2.31.1.1.1.1.1 = sc0
最佳答案
这可行。但我想避免显式的next(),它不适合异步
from pysnmp.hlapi import *
from pysnmp import debug
g = nextCmd(
SnmpEngine(),
CommunityData('public', mpModel=1),
UdpTransportTarget(('giga-int-2', 161)),
ContextData(),
ObjectType(ObjectIdentity('1.3.6.1.2.1.31.1.1.1.1')),
lexicographicMode=False
)
while True:
try:
errorIndication, errorStatus, errorIndex, varBinds = next(g);
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for name, val in varBinds:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
except StopIteration:
break