Search code examples
python-3.xpysnmp

How to get each returned value as variable for later use?


from this code im trying to get the returned values of the walk as variables.

def walk(host, oid):

    for (errorIndication,
         errorStatus,
         errorIndex,
         varBinds) in nextCmd(SnmpEngine(),
                              CommunityData('public'),
                              UdpTransportTarget((host, 161)),
                              ContextData(),
                              ObjectType(ObjectIdentity(oid)),
                              lookupMib=False,
                              lexicographicMode=False):

        if errorIndication:
            print(errorIndication, file=sys.stderr)
            break

        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(),
                                errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), file=sys.stderr)
            break

        else:
            for oid, raw_value in varBinds:
                print(f'item: {raw_value.prettyPrint()}')

ill get this:

item: 6000
item: 520
item: 200
item: 200

How i can get these (could be limited to two or tree) as variables for later use. thanks.


Solution

  • Instead of printing the items, use yield to return them from the function.

    for oid, raw_value in varBinds:
        yield raw_value
    

    Then you can use them later like this:

    for item in walk(host, oid):
        # do something with the item