如何在PySNMP中进行单个GETNEXT查询
我正在尝试进行一个简单的 SNMP GETNEXT 查询,以便只获取给定 OID 在树形结构中的下一个项目。
举个例子,我想要的是:
当我用 OID 1.3.6.1.2.1.1(iso.org.dod.internet.mgmt.mib-2.system)发出一个 GETNEXT 请求时,
我希望能得到一个 单一 的响应,其中包含 OID 1.3.6.1.2.1.1.1.0(iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0)及其对应的值。
但实际上:
我并没有得到单个下一个值,而是 PySNMP 在 1.3.6.1.2.1.1 下执行了一个 SNMP walk,获取了所有的子项。
我该如何改变这种行为,让它只返回单个下一个值,而不是执行一个 snmpwalk 呢?
我使用的代码如下,取自 PySNMP 的文档。
# GETNEXT Command Generator
from pysnmp.entity.rfc3413.oneliner import cmdgen
errorIndication, errorStatus, errorIndex, \
varBindTable = cmdgen.CommandGenerator().nextCmd(
cmdgen.CommunityData('test-agent', 'public'),
cmdgen.UdpTransportTarget(('localhost', 161)),
(1,3,6,1,2,1,1)
)
if errorIndication:
print errorIndication
else:
if errorStatus:
print '%s at %s\n' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
2 个回答
-2
errorIndication, errorStatus, errorIndex, \
varBindTable = cmdgen.CommandGenerator().nextCmd(
cmdgen.CommunityData('test-agent', 'public'),
cmdgen.UdpTransportTarget(('localhost', 161)),
(1,3,6,1,2,1,1),maxRows=1
)
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
3
@Cankut,pysnmp的“单行”GETNEXT接口可以通过获取在某个前缀下的所有OID,或者获取直到MIB结束的所有OID来工作。
实现你想要的功能的一种方法是用你自己的函数替换掉pysnmp默认的响应处理函数(这也需要使用一些更底层的异步API):
from pysnmp.entity.rfc3413.oneliner import cmdgen
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
if errorIndication:
print(errorIndication)
return 1
if errorStatus:
print(errorStatus.prettyPrint())
return 1
for varBindRow in varBindTable:
for oid, val in varBindRow:
print('%s = %s' % (oid.prettyPrint(),
val and val.prettyPrint() or '?'))
cmdGen = cmdgen.AsynCommandGenerator()
cmdGen.nextCmd(
cmdgen.CommunityData('test-agent', 'public'),
cmdgen.UdpTransportTarget(('localhost', 161)),
((1,3,6,1,2,1,1),),
(cbFun, None)
)
cmdGen.snmpEngine.transportDispatcher.runDispatcher()