pysnmp walk v2c if no response try v3

454 views Asked by At

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]))
1

There are 1 answers

1
Ilya Etingof On

Off the top of my head, you can just leverage the fact that SNMP v1 and v3 authentication objects can be used interchangeably:

from pysnmp.hlapi import *

snmpEngine = SnmpEngine()

for snmpAuth in CommunityData('public'), UsmUserData('usr-md5-none', 'authkey1'):

    snmpQueryIterator = getCmd(
        snmpEngine,
        snmpAuth,
        UdpTransportTarget(('demo.snmplabs.com', 161)),
        ContextData(),
        ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))
    )

    errorIndication, errorStatus, errorIndex, varBinds = next(snmpQueryIterator)

    if errorIndication:
        continue

    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]))

    break

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.