[英]pysnmp - ValueError: too many values to unpack (expected 4)
如果我尝试这样的事情,我会
ValueError:太多值无法解包(预期4)
有人可以解释为什么吗?
from pysnmp.hlapi import *
errorIndication, errorStatus, errorIndex, varBinds = 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)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for v in varBinds:
for name, val in v:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
nextCmd()
函数(以及其他pysnmp函数)返回一个Python生成器对象,您应该对其进行迭代:
>>> from pysnmp.hlapi import *
>>> g = nextCmd(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 161)),
... ContextData(),
... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')))
>>> next(g)
(None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')),
DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))])
您可以像任何Python迭代器一样使用此生成器,例如在循环中使用。 或者,如果您只需要运行单个请求/响应,则只需在其上调用next
。
pysnmp在每次迭代中都会发出一个请求(一个或多个,具体取决于情况),以请求一个大于上一个的OID。 这样,您可以“遍历” SNMP代理,直到您摆脱环路或耗尽代理方的OID。
您在这里的错误是,您期望pysnmp的nextCmd
立即运行SNMP查询并返回一个值。 而是pysnmp为您提供了一个生成器协程,您可以重复使用它来执行多个查询(您也可以.send()
它的OID .send()
发送给它)。
感谢您的回答。 我重写了代码。 现在它正在做我想要的。 它仅搜索“ 1.3.6.1.2.1.31.1.1.1.x”树。
from pysnmp.hlapi import *
for errorIndication, errorStatus, errorIndex, varBinds in 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)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for v in varBinds:
print(v.prettyPrint())
SNMPv2-SMI::mib-2.31.1.1.1.1.1 = sc0
SNMPv2-SMI::mib-2.31.1.1.1.1.2 = sl0
SNMPv2-SMI::mib-2.31.1.1.1.1.3 = sc1
SNMPv2-SMI::mib-2.31.1.1.1.1.5 = VLAN-1
SNMPv2-SMI::mib-2.31.1.1.1.1.6 = VLAN-1002
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.