I'm trying to write a snmp script with python and pysnmp but I can't seem to find a simple way to try a snmp v2c walk and if no response try v3 without having to write basically the same code over again. Is there an easy way to do so? I couldn't seem to find a way.
This is the way I currently have it but I feel its very inefficient.
from pysnmp.hlapi import *
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('sysDescr')))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
elif
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
UsmUserData('usr-md5-none', 'authkey1'),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1)))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
Off the top of my head, you can just leverage the fact that SNMP v1 and v3 authentication objects can be used interchangeably:
The above code performs SNMP GET query, if you need to "walk" your agent, you might need to adapt it a little to GETNEXT operation. Heer's an example.