Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snmpwalk with PySNMP

I’d like to reproduce the comportment of the following SNMP command :

snmpwalk -v2c -cpublic 192.168.0.10 1.3.6.1.2.1.25.2.3.1.3

which gives me this output :

iso.3.6.1.2.1.25.2.3.1.3.1 = STRING: "Physical memory"
iso.3.6.1.2.1.25.2.3.1.3.3 = STRING: "Virtual memory"
iso.3.6.1.2.1.25.2.3.1.3.6 = STRING: "Memory buffers"
iso.3.6.1.2.1.25.2.3.1.3.7 = STRING: "Cached memory"
iso.3.6.1.2.1.25.2.3.1.3.8 = STRING: "Shared memory"
iso.3.6.1.2.1.25.2.3.1.3.10 = STRING: "Swap space"
iso.3.6.1.2.1.25.2.3.1.3.31 = STRING: "/"
iso.3.6.1.2.1.25.2.3.1.3.37 = STRING: "/run"
iso.3.6.1.2.1.25.2.3.1.3.39 = STRING: "/dev/shm"
iso.3.6.1.2.1.25.2.3.1.3.40 = STRING: "/run/lock"
iso.3.6.1.2.1.25.2.3.1.3.41 = STRING: "/sys/fs/cgroup"
iso.3.6.1.2.1.25.2.3.1.3.59 = STRING: "/tmp"
iso.3.6.1.2.1.25.2.3.1.3.60 = STRING: "/run/cgmanager/fs"
iso.3.6.1.2.1.25.2.3.1.3.61 = STRING: "/run/user/112"
iso.3.6.1.2.1.25.2.3.1.3.63 = STRING: "/run/user/0"

So I tried this code :

#!/usr/bin/env python3
from pysnmp.hlapi import *

def walk(host, oid):
    for (errorIndication,errorStatus,errorIndex,varBinds) in nextCmd(SnmpEngine(), 
        CommunityData('public'), UdpTransportTarget((host, 161)), ContextData(), 
        ObjectType(ObjectIdentity(oid))):
        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 varBind in varBinds:
                print(varBind)

walk('192.168.0.10','1.3.6.1.2.1.25.2.3.1.3')

and the problem is that it returns a lot of unwanted OIDs…

I tried different things, like using the getCmd() function but I can’t manage to have it working the way I want.

I could call the external snmpwalk command from my Python code but I’d prefer to find a solution using the Python module.

Any idea to help me?

like image 313
Stéphane Avatar asked Jan 31 '23 01:01

Stéphane


1 Answers

Try passing the lexicographicMode keyword argument to the nextCmd(). For example:

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

That should have the effect of capping the SNMP walk by the initial OID you give it (assuming that unwanted OIDs you mention are those going out of the prefix).

like image 198
Ilya Etingof Avatar answered May 12 '23 00:05

Ilya Etingof