2008-02-17 11:37:58

Python snmp example using pysnmp

Here's a simple python program that makes an snmp query against network interface descriptions, and then grabs the physical address of that interface using another snmp call.

#!/usr/bin/env python
import re, os, sys, getopt, string, commands
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.entity.rfc3413 import mibvar
from pysnmp.proto import rfc1902

SNMP_HOST='127.0.0.1'
SNMP_RO_STRING='whatever'
SNMP_PORT=161

IOD_sysdescr=[1,3,6,1,2,1,1,1,0]
IOD_descr=[1,3,6,1,2,1,2,2,1,2]
IOD_phyaddr=[1,3,6,1,2,1,2,2,1,6]
IOD_type=[1,3,6,1,2,1,2,2,1,3]
IOD_speed=[1,3,6,1,2,1,2,2,1,5]
IOD_alias=[1,3,6,1,2,1,31,1,1,1,18]
    
def main():
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
        cmdgen.CommunityData('duofold', SNMP_RO_STRING), cmdgen.UdpTransportTarget((SNMP_HOST, SNMP_PORT)),
        (('IF-MIB', 'ifDescr'),),)

    if errorIndication:
        print errorIndication
    else:
        if errorStatus:
            print '%s at %s\n' % (errorStatus.prettyPrint(),varBindTable[-1][int(errorIndex)-1])
        else:
            for varBindTableRow in varBindTable:
                for oid, val in varBindTableRow:
                    (symName, modName), indices = mibvar.oidToMibName(cmdGen.mibViewController, oid)
                    val = mibvar.cloneFromMibValue(cmdGen.mibViewController, modName, symName, val)
                    #print '%s::%s.%s = %s' % (modName, symName,string.join(map(lambda v: v.prettyPrint(), indices), '.'),val.prettyPrint())
                    INTERFACE=oid.prettyPrint().split('.')[-1:].pop(0)
                    get_attr(INTERFACE,IOD_phyaddr)


def get_attr(interface,attr):
    cmdGen = cmdgen.CommandGenerator()
    IOD_list=attr+[int(interface)]
    IOD=tuple(IOD_list)
    errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
        cmdgen.CommunityData('edson', SNMP_RO_STRING),cmdgen.UdpTransportTarget((SNMP_HOST, SNMP_PORT)),(IOD))
    if errorIndication:
        print errorIndication
    else:
        if errorStatus:
            print '%s at %s\n' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1])
        else:
            for name, val in varBinds:
                if attr==IOD_phyaddr:
                    print '%s = %s' % (name.prettyPrint(), hexify(val))
                else:
                    print '%s = %s' % (name.prettyPrint(), val.prettyPrint())

def hexify(input):
    return ":".join([ '%x'%(ord(s)) for s in input])

main()

Tags:   python     |    Perm Link:   Python snmp example using pysnmp



James Conner