Search code examples
pythonpython-3.xpysnmp

How do I return two values gotten from a loop done with PySNMP?


I am new to PySNMP and Python but been passionate about it.

I have a script taken from PySNMP documentation and I have make it a python function called SnmpGetNext().

At the end what I want to do is to get the two OIDS from the nextCmd, which should give me 1.3.6.1.2.1.2.2.1.14 .1 and .2

When I do this, it gets both values and save it into a dictionary, which is great.

for varBindTableRow in varBindTable:
    for name, val in varBindTableRow:
        result2 = {}

        result2['OID']= str(val)
        print(result2

However I want to be able return them and later use this function to use it with more OID, if I return result2 this will only return me the first value.

I have tried passing it the OID through a dictionary and just as strings.

from pysnmp.entity.rfc3413.oneliner import cmdgen

host = "demo.snmplabs.com"
community = "public"
test1 = ".1.3.6.1.2.1.2.2.1.14"

def SnmpGetNext(host,community,oid):
    errorIndication, errorStatus, errorIndex, \
                     varBindTable = cmdgen.CommandGenerator().nextCmd(
        cmdgen.CommunityData('test-agent', community),
        cmdgen.UdpTransportTarget((host, 161)),
        (oid),
        )

    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:
                    result2 = {}

                    result2['OID']= str(val)
                    print(result2)
                    #return (name.prettyPrint(),val.prettyPrint())
                    #print ('%s = %s' % (name.prettyPrint(), val.prettyPrint()))


result = {}
result['test1']= SnmpGetNext(host,community,test1)
print(result)

Desired results would be by running

SnmpGetNext(host, community,test1) to get:

1.3.6.1.2.1.2.2.1.14.1 1.3.6.1.2.1.2.2.1.14.2


Solution

  • So basically I had to use instead of return, yield and now it works perfect.