0

我有以下代码,我一直在使用 pysnmp 进行轮询。到目前为止,它一直用于走路,但我希望能够获得特定的索引。例如我想投票HOST-RESOURCES-MIB::hrSWRunPerfMem.999

我可以使用它来成功取回 hrSWRunPerfMem 中的所有内容getCounter('1.1.1.1', 'public', 'HOST-RESOURCES-MIB', 'hrSWRunPerfMem')

但是,一旦我尝试包含索引号getCounter('1.1.1.1', 'public', 'HOST-RESOURCES-MIB', 'hrSWRunPerfMem', indexNum=999),我总是会得到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)

有没有人对如何使用 pysnmp 轮询特定索引有所了解?

4

1 回答 1

2

您应该使用 cmdGen.getCmd() 调用而不是 nextCmd() 调用。在叶子之后没有“下一个”OID,因此响应为空。

这是您的代码的一些优化版本。它应该在您的 Python 提示符下按原样运行:

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))

性能方面,建议重用 CommandGenerator 实例以节省在后台发生的 [heavy] snmpEngine 初始化。

于 2014-01-28T22:29:56.890 回答