我有以下代码,我一直用pysnmp进行轮询。到目前为止,它已被用于行走,但我希望能够得到一个特定的索引。例如,我想轮询HOST-RESOURCES-MIB::hrSWRunPerfMem.999
我可以使用它来成功使用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轮询特定索引有所了解?
答案 0 :(得分: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初始化。