我使用pysnmp 4.3.1,使用Packet Level SNMP语法
我试图在GetNext请求之后寻找一种更改为Get请求的有效方法
例如,我需要走遍整个分支(1.3.6.1.2.1.11),然后我需要得到这两个oid(1.3.6.1.2.1.1.1.0,1.3.6.1.2.1.1.3.0)。
我还需要在SNMPv1上执行这些请求,而不需要任何varbinds。
这是我的代码:
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.carrier.asyncore.dgram import udp
from pyasn1.codec.ber import encoder, decoder
from pysnmp.proto import api
from time import time
# Protocol version to use
pMod = api.protoModules[api.protoVersion1]
#pMod = api.protoModules[api.protoVersion2c]
# SNMP table header
headVars = [ pMod.ObjectIdentifier((1,3,6,1,2,1,11)) ]
next1 = '1.3.6.1.2.1.11'
get2 = '1.3.6.1.2.1.1.1.0'
# Build PDU
reqPDU = pMod.GetNextRequestPDU()
pMod.apiPDU.setDefaults(reqPDU)
pMod.apiPDU.setVarBinds(reqPDU, [ (x, pMod.null) for x in headVars ])
# Build message
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
pMod.apiMessage.setCommunity(reqMsg, 'public')
pMod.apiMessage.setPDU(reqMsg, reqPDU)
startedAt = time()
def cbTimerFun(timeNow):
if timeNow - startedAt > 3:
raise Exception("Request timed out")
def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
wholeMsg, reqPDU=reqPDU, headVars=headVars):
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
rspPDU = pMod.apiMessage.getPDU(rspMsg)
# Match response to request
if pMod.apiPDU.getRequestID(reqPDU)==pMod.apiPDU.getRequestID(rspPDU):
# Check for SNMP errors reported
errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
if errorStatus and errorStatus != 2:
raise Exception(errorStatus)
# Format var-binds table
varBindTable = pMod.apiPDU.getVarBindTable(reqPDU, rspPDU)
# Report SNMP table
for tableRow in varBindTable:
for name, val in tableRow:
print('from: %s, %s = %s' % (
transportAddress, name.prettyPrint(), val.prettyPrint()
)
)
# Generate request for next row
if(next1 in name.prettyPrint()):
pMod.apiPDU.setVarBinds(
reqPDU, [ (x, pMod.null) for x,y in varBindTable[-1] ]
)
pMod.apiPDU.setRequestID(reqPDU, pMod.getNextRequestID())
transportDispatcher.sendMessage(
encoder.encode(reqMsg), transportDomain, transportAddress
)
else:
reqPDU = pMod.GetRequestPDU()
pMod.apiPDU.setVarBinds(
reqPDU, [ (get2, pMod.null) ]
)
pMod.apiPDU.setRequestID(reqPDU, pMod.getNextRequestID())
transportDispatcher.sendMessage(
encoder.encode(reqMsg), transportDomain, transportAddress
)
global startedAt
if time() - startedAt > 3:
raise Exception('Request timed out')
startedAt = time()
return wholeMsg
transportDispatcher = AsyncoreDispatcher()
transportDispatcher.registerRecvCbFun(cbRecvFun)
transportDispatcher.registerTimerCbFun(cbTimerFun)
transportDispatcher.registerTransport(
udp.domainName, udp.UdpSocketTransport().openClientMode()
)
transportDispatcher.sendMessage(
encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161)
)
transportDispatcher.jobStarted(1)
transportDispatcher.runDispatcher()
transportDispatcher.closeDispatcher()
此代码主要来自此GetNext示例 如何使用SNMPv1而不使用varbinds从一系列GetNext请求更改为多个Get请求序列?