Frage

I have the following code which I've been using to poll with pysnmp. Up until now it has been used to walk but I'd like to be able to get a specific index. For example I'd like to poll HOST-RESOURCES-MIB::hrSWRunPerfMem.999

I can use this to sucessfully get back everything in hrSWRunPerfMem using getCounter('1.1.1.1', 'public', 'HOST-RESOURCES-MIB', 'hrSWRunPerfMem')

However once I try to include the index number getCounter('1.1.1.1', 'public', 'HOST-RESOURCES-MIB', 'hrSWRunPerfMem', indexNum=999) I always get varBindTable == []

from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.smi import builder, view

def getCounter(ip, community, mibName, counterName, indexNum=None):
    cmdGen = cmdgen.CommandGenerator()
    mibBuilder = cmdGen.mibViewController.mibBuilder
    mibPath = mibBuilder.getMibSources() + (builder.DirMibSource("/path/to/mibs"),)
    mibBuilder.setMibSources(*mibPath)
    mibBuilder.loadModules(mibName)
    mibView = view.MibViewController(mibBuilder)

    retList = []
    if indexNum is not None:
        mibVariable = cmdgen.MibVariable(mibName, counterName, int(indexNum))
    else:
        mibVariable = cmdgen.MibVariable(mibName, counterName)

    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(cmdgen.CommunityData('test-agent', community),
                                                                            cmdgen.UdpTransportTarget((ip, snmpPort)),
                                                                            mibVariable)

Does anyone have some insight into how to poll specific indexes using pysnmp?

War es hilfreich?

Lösung

You should be using cmdGen.getCmd() call instead of nextCmd() call. There's no 'next' OID past the leaf one hence empty response.

Here's a bit optimized version of your code. It should run as-is right from your Python prompt:

from pysnmp.entity.rfc3413.oneliner import cmdgen

def getCounter(ip, community, mibName, counterName, indexNum=None):
    if indexNum is not None:
        mibVariable = cmdgen.MibVariable(mibName, counterName, int(indexNum))
    else:
        mibVariable = cmdgen.MibVariable(mibName, counterName)

    cmdGen = cmdgen.CommandGenerator()

    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.getCmd(
        cmdgen.CommunityData(community),
        cmdgen.UdpTransportTarget((ip, 161)),
        mibVariable.addMibSource("/path/to/mibs")
    )

    if not errorIndication and not errorStatus:
        return varBindTable

#from pysnmp import debug
#debug.setLogger(debug.Debug('msgproc'))

print(getCounter('demo.snmplabs.com',
                 'recorded/linux-full-walk',
                 'HOST-RESOURCES-MIB',
                 'hrSWRunPerfMem',
                  970))

Performance wise, it's recommended to reuse CommandGenerator instance to save on [heavy] snmpEngine initialisation happening under the hood.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top