您似乎正在使用netsnmp
模块而不是pysnmp
.
如果你想使用pysnmp
, then 这个例子 http://pysnmp.sourceforge.net/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.html#snmpv2c可能有帮助:
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]))
UPDATE:
上述循环每次迭代都会获取一个 OID 值。如果您想更有效地获取数据,一种选择是将更多 OID 填充到查询中(以许多形式)ObjectType(...)
参数)。
或者您可以切换到 GETBULK PDU 类型,这可以通过更改您的nextCmd
呼入bulkCmd
像这样 http://pysnmp.sourceforge.net/docs/hlapi/asyncore/sync/manager/cmdgen/bulkcmd.html#pysnmp.hlapi.bulkCmd.
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 使用它。