kit kit -4 years ago 256
Python Question

How to get SNMP data using pysnmp?

I want to get snmp data by using python pysnmp module. I was using command line to get SNMP data but now I want to read it using pysnmp module.

SNMP command -

snmpwalk -v 1 -c public <ip address>:<port> xyz::pqr

I was using command like above. Now I tried something like below -

import netsnmp

def getmac():
oid = netsnmp.VarList(netsnmp.Varbind('.'))
res = netsnmp.snmpgetbulk(oid, Version = 1, DestHost='ip',
return res

print getmac()

I'm facing error - import netsnmp. No module netsnmp

Anyone can give me suggestion how I can get snmp data from the snmp server with python?

Answer Source

You seem to be using the netsnmp module as opposed to the pysnmp.

If you want to use pysnmp, then this example may help:

from pysnmp.hlapi import *

for (errorIndication,
     varBinds) in nextCmd(SnmpEngine(),
                          CommunityData('public', mpModel=0),
                          UdpTransportTarget(('', 161)),
    if errorIndication or errorStatus:
        print(errorIndication or errorStatus)
        for varBind in varBinds:
            print(' = '.join([x.prettyPrint() for x in varBind]))


The above loop will fetch one OID-value per iteration. If you want to fetch data more efficiently, one option is to stuff more OIDs into the query (in form of many ObjectType(...) parameters) or you can switch onto the GETBULK PDU type which can be done by changing your nextCmd call into bulkCmd like this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download