您似乎使用的是 netsnmp 模块,而不是 pysnmp。
如果您想使用pysnmp,那么this example 可能会有所帮助:
from pysnmp.hlapi import *
for (errorIndication,
errorStatus,
errorIndex,
varBinds) in nextCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('1.3.6.1.2.1.17.7.1.2.2.1.2'))):
if errorIndication or errorStatus:
print(errorIndication or errorStatus)
break
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
更新:
上述循环每次迭代都会获取一个 OID 值。如果您想更有效地获取数据,一种选择是将更多 OID 填充到查询中(以许多 ObjectType(...) 参数的形式)。
或者您可以切换到 GETBULK PDU 类型,这可以通过将您的 nextCmd 调用更改为 bulkCmd like this 来完成。
from pysnmp.hlapi import *
for (errorIndication,
errorStatus,
errorIndex,
varBinds) in bulkCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
0, 25, # fetch up to 25 OIDs one-shot
ObjectType(ObjectIdentity('1.3.6.1.2.1.17.7.1.2.2.1.2'))):
if errorIndication or errorStatus:
print(errorIndication or errorStatus)
break
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
请记住,GETBULK 命令支持最初是在 SNMP v2c 中引入的,也就是说您不能在 SNMP v1 上使用它。