How to make a single GETNEXT query in PySNMP
Frage
I'm trying to make a simple snmp GETNEXT query to retrieve only the next item of given OID in tree hierarchy.
For example, what I want is:
When i make a GETNEXT request with OID 1.3.6.1.2.1.1 (iso.org.dod.internet.mgmt.mib-2.system)
I expect to get a single response including OID 1.3.6.1.2.1.1.1.0 (iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0) with its corresponding value.
The fact is:
Insted of retrieving single next value, PySNMP performs an SNMP walk under 1.3.6.1.2.1.1 and retrieves all subItems.
How can i change this behaviour and make it to just return single next value instead of performing an snmpwalk?
I use the below code which is taken from PySNMP's documentation.
# 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())
Lösung
@Cankut, pysnmp's "oneliner" GETNEXT API works by retrieving either all OIDs under a given prefix or all OIDs till end-of-mib.
One way of doing what you want would be to replace pysnmp's stock response processing function with your own (that would also require using a bit lower-level async 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()
Andere Tipps
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
)