2014-01-28 35 views
0

我有下面的代码,我一直在使用它来查询pysnmp。到目前为止,它已被用来散步,但我希望能够得到一个特定的索引。例如,我想查询HOST-RESOURCES-MIB::hrSWRunPerfMem.999pysnmp轮询HOST-RESOURCES-MIB中的特定进程索引

我可以用它来使用getCounter('1.1.1.1', 'public', 'HOST-RESOURCES-MIB', 'hrSWRunPerfMem')

然而成功地取回一切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轮询特定索引的见解?

回答

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实例,以节省[重] snmpEngine初始化引擎盖下发生。

+0

这样做!谢谢!在最后的建议中,我重新编了一些代码,而且事情看起来更顺畅。 – EEP