From 90bbf397ad3dd49db7f83d541afff51f17e63054 Mon Sep 17 00:00:00 2001 From: Ilya Etingof Date: Sat, 2 Apr 2016 23:43:14 +0200 Subject: pep8 reformatted --- pysnmp/entity/config.py | 126 +++++++++++++++++++++++-------- pysnmp/entity/engine.py | 39 ++++++---- pysnmp/entity/observer.py | 4 +- pysnmp/entity/rfc3413/cmdgen.py | 80 +++++++++++++------- pysnmp/entity/rfc3413/cmdrsp.py | 48 +++++++----- pysnmp/entity/rfc3413/config.py | 32 ++++---- pysnmp/entity/rfc3413/context.py | 21 ++++-- pysnmp/entity/rfc3413/mibvar.py | 33 ++++---- pysnmp/entity/rfc3413/ntforg.py | 87 +++++++++++++++------ pysnmp/entity/rfc3413/ntfrcv.py | 19 +++-- pysnmp/entity/rfc3413/oneliner/cmdgen.py | 22 +++--- pysnmp/entity/rfc3413/oneliner/ntforg.py | 25 +++--- 12 files changed, 358 insertions(+), 178 deletions(-) (limited to 'pysnmp/entity') diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py index f66b0b54..10acd25b 100644 --- a/pysnmp/entity/config.py +++ b/pysnmp/entity/config.py @@ -46,13 +46,16 @@ privServices = {des.Des.serviceID: des.Des(), aes256.Aes256.serviceID: aes256.Aes256(), nopriv.NoPriv.serviceID: nopriv.NoPriv()} + def __cookV1SystemInfo(snmpEngine, communityIndex): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpCommunityEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') + snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpCommunityEntry, = mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') tblIdx = snmpCommunityEntry.getInstIdFromIndices(communityIndex) return snmpCommunityEntry, tblIdx, snmpEngineID + def addV1System(snmpEngine, communityIndex, communityName, contextEngineId=None, contextName=None, transportTag=None, securityName=None): @@ -81,6 +84,7 @@ def addV1System(snmpEngine, communityIndex, communityName, (snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo')) ) + def delV1System(snmpEngine, communityIndex): (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) @@ -88,21 +92,26 @@ def delV1System(snmpEngine, communityIndex): ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) + def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + if securityEngineId is None: snmpEngineID = snmpEngineID.syntax else: snmpEngineID = snmpEngineID.syntax.clone(securityEngineId) - usmUserEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') + usmUserEntry, = mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') tblIdx1 = usmUserEntry.getInstIdFromIndices(snmpEngineID, securityName) - pysnmpUsmSecretEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') + pysnmpUsmSecretEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) return snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 + def addV3User(snmpEngine, userName, authProtocol=usmNoAuthProtocol, authKey=None, privProtocol=usmNoPrivProtocol, privKey=None, @@ -110,18 +119,20 @@ def addV3User(snmpEngine, userName, securityName=None, # deprecated parameters follow contextEngineId=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + if securityName is None: securityName = userName if securityEngineId is None: # backward compatibility securityEngineId = contextEngineId - (snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, - tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) + (snmpEngineID, usmUserEntry, tblIdx1, + pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) # Load augmenting table before creating new row in base one - pysnmpUsmKeyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') + pysnmpUsmKeyEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') # Load clone-from (may not be needed) - zeroDotZero, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') + zeroDotZero, = mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) @@ -176,6 +187,7 @@ def addV3User(snmpEngine, userName, (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo')) ) + def delV3User(snmpEngine, userName, securityEngineId=None, @@ -196,7 +208,7 @@ def delV3User(snmpEngine, varBinds = initialVarBinds = ( (usmUserEntry.name + (1,), None), # usmUserEngineID (usmUserEntry.name + (2,), None), # usmUserName - (usmUserEntry.name + (4,), None) # usmUserCloneFrom + (usmUserEntry.name + (4,), None) # usmUserCloneFrom ) while varBinds: varBinds = snmpEngine.msgAndPduDsp.mibInstrumController.readNextVars( @@ -210,11 +222,15 @@ def delV3User(snmpEngine, delV3User(snmpEngine, varBinds[1][1], varBinds[0][1]) varBinds = initialVarBinds + def __cookTargetParamsInfo(snmpEngine, name): - snmpTargetParamsEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpTargetParamsEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) return snmpTargetParamsEntry, tblIdx + # mpModel: 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): if mpModel == 0: @@ -240,32 +256,39 @@ def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): (snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo')) ) + def delTargetParams(snmpEngine, name): snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) ) + def __cookTargetAddrInfo(snmpEngine, addrName): - snmpTargetAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') - snmpSourceAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpTargetAddrEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') + snmpSourceAddrEntry, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrEntry') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) return snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx + def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, params, timeout=None, retryCount=None, tagList=null, sourceAddress=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + SnmpUDPAddress, = mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') transportAddress = SnmpUDPAddress(transportAddress) if sourceAddress is None: sourceAddress = ('0.0.0.0', 0) sourceAddress = SnmpUDPAddress(sourceAddress) elif transportDomain[:len(snmpUDP6Domain)] == snmpUDP6Domain: - TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + TransportAddressIPv6, = mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') transportAddress = TransportAddressIPv6(transportAddress) if sourceAddress is None: sourceAddress = ('::', 0) @@ -286,6 +309,7 @@ def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, (snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo')) ) + def delTargetAddr(snmpEngine, addrName): (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) @@ -293,10 +317,12 @@ def delTargetAddr(snmpEngine, addrName): ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) ) + def addTransport(snmpEngine, transportDomain, transport): if snmpEngine.transportDispatcher: if not transport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): - raise error.PySnmpError('Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher)) + raise error.PySnmpError( + 'Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher)) else: snmpEngine.registerTransportDispatcher( transport.protoTransportDispatcher() @@ -304,16 +330,16 @@ def addTransport(snmpEngine, transportDomain, transport): # here we note that we have created transportDispatcher automatically snmpEngine.setUserContext(automaticTransportDispatcher=0) - snmpEngine.transportDispatcher.registerTransport(transportDomain, - transport) + snmpEngine.transportDispatcher.registerTransport(transportDomain, transport) automaticTransportDispatcher = snmpEngine.getUserContext( 'automaticTransportDispatcher' ) if automaticTransportDispatcher is not None: snmpEngine.setUserContext( - automaticTransportDispatcher=automaticTransportDispatcher+1 + automaticTransportDispatcher=automaticTransportDispatcher + 1 ) + def getTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return @@ -322,6 +348,7 @@ def getTransport(snmpEngine, transportDomain): except error.PySnmpError: return + def delTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return @@ -342,28 +369,33 @@ def delTransport(snmpEngine, transportDomain): snmpEngine.delUserContext(automaticTransportDispatcher) return transport + addSocketTransport = addTransport delSocketTransport = delTransport + # VACM shortcuts def addContext(snmpEngine, contextName): - vacmContextEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry' - ) + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmContextEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmContextEntry.name + (1,) + tblIdx, contextName),) ) + def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): - vacmSecurityToGroupEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' - ) + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmSecurityToGroupEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', + 'vacmSecurityToGroupEntry') tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices(securityModel, securityName) return vacmSecurityToGroupEntry, tblIdx + def addVacmGroup(snmpEngine, groupName, securityModel, securityName): (vacmSecurityToGroupEntry, tblIdx) = __cookVacmGroupInfo(snmpEngine, securityModel, securityName) @@ -377,6 +409,7 @@ def addVacmGroup(snmpEngine, groupName, securityModel, securityName): (vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo')) ) + def delVacmGroup(snmpEngine, securityModel, securityName): vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( snmpEngine, securityModel, securityName @@ -385,20 +418,24 @@ def delVacmGroup(snmpEngine, securityModel, securityName): ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) ) + def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel): - vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmAccessEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') tblIdx = vacmAccessEntry.getInstIdFromIndices(groupName, contextName, securityModel, securityLevel) return vacmAccessEntry, tblIdx + def addVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel, prefix, readView, writeView, notifyView): vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel) - addContext(snmpEngine, contextName) # this is leaky + addContext(snmpEngine, contextName) # this is leaky snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) @@ -414,6 +451,7 @@ def addVacmAccess(snmpEngine, groupName, contextName, securityModel, (vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo')) ) + def delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel): vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, @@ -423,13 +461,17 @@ def delVacmAccess(snmpEngine, groupName, contextName, securityModel, ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) ) + def __cookVacmViewInfo(snmpEngine, viewName, subTree): - vacmViewTreeFamilyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmViewTreeFamilyEntry, = mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' ) tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree) return vacmViewTreeFamilyEntry, tblIdx + def addVacmView(snmpEngine, viewName, viewType, subTree, mask): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, subTree) @@ -444,6 +486,7 @@ def addVacmView(snmpEngine, viewName, viewType, subTree, mask): (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo')) ) + def delVacmView(snmpEngine, viewName, subTree): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, subTree) @@ -451,15 +494,19 @@ def delVacmView(snmpEngine, viewName, subTree): ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) ) + # VACM simplicity wrappers def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + groupName = 'v-%s-%d' % (hash(securityName), securityModel) - SnmpSecurityLevel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') + SnmpSecurityLevel, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') securityLevel = SnmpSecurityLevel(securityLevel) return (groupName, securityLevel, 'r' + groupName, 'w' + groupName, 'n' + groupName) + def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): @@ -476,6 +523,7 @@ def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, if notifySubTree: addVacmView(snmpEngine, notifyView, "included", notifySubTree, null) + def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=()): (groupName, securityLevel, readView, writeView, @@ -496,48 +544,59 @@ def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, snmpEngine, notifyView, notifySubTree ) + # Obsolete shortcuts for add/delVacmUser() wrappers def addRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree) + def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree) + def addRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, subTree) + def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, subTree) + def addTrapUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, (), (), subTree) + def delTrapUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, (), (), subTree) + # Notification target setup def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, filterSubtree=None): - snmpNotifyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') tblIdx1 = snmpNotifyEntry.getInstIdFromIndices(notificationName) - snmpNotifyFilterProfileEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') + snmpNotifyFilterProfileEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', + 'snmpNotifyFilterProfileEntry') tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices(paramsName) profileName = '%s-filter' % hash(notificationName) if filterSubtree: - snmpNotifyFilterEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') + snmpNotifyFilterEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', + 'snmpNotifyFilterEntry') tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices(profileName, filterSubtree) else: @@ -547,6 +606,7 @@ def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, tblIdx3) + def addNotificationTarget(snmpEngine, notificationName, paramsName, transportTag, notifyType=None, filterSubtree=None, filterMask=None, filterType=None): @@ -585,6 +645,7 @@ def addNotificationTarget(snmpEngine, notificationName, paramsName, (snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo')) ) + def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtree=None): (snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, @@ -607,6 +668,7 @@ def delNotificationTarget(snmpEngine, notificationName, paramsName, ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) ) + # rfc3415: A.1 def setInitialVacmParameters(snmpEngine): # rfc3415: A.1.1 --> initial-semi-security-configuration diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py index 76323d7b..868dbf37 100644 --- a/pysnmp/entity/engine.py +++ b/pysnmp/entity/engine.py @@ -9,10 +9,10 @@ import sys import tempfile from pysnmp.proto.rfc3412 import MsgAndPduDispatcher from pysnmp.proto.mpmod.rfc2576 import SnmpV1MessageProcessingModel, \ - SnmpV2cMessageProcessingModel + SnmpV2cMessageProcessingModel from pysnmp.proto.mpmod.rfc3412 import SnmpV3MessageProcessingModel from pysnmp.proto.secmod.rfc2576 import SnmpV1SecurityModel, \ - SnmpV2cSecurityModel + SnmpV2cSecurityModel from pysnmp.proto.secmod.rfc3414 import SnmpUSMSecurityModel from pysnmp.proto.acmod import rfc3415, void from pysnmp.entity import observer @@ -21,6 +21,7 @@ from pysnmp import error __all__ = ['SnmpEngine'] + class SnmpEngine: """Creates SNMP engine object. @@ -51,6 +52,7 @@ class SnmpEngine: >>> """ + def __init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None): self.cache = {} @@ -63,11 +65,11 @@ class SnmpEngine: self.msgAndPduDsp = msgAndPduDsp self.messageProcessingSubsystems = { SnmpV1MessageProcessingModel.messageProcessingModelID: - SnmpV1MessageProcessingModel(), + SnmpV1MessageProcessingModel(), SnmpV2cMessageProcessingModel.messageProcessingModelID: - SnmpV2cMessageProcessingModel(), + SnmpV2cMessageProcessingModel(), SnmpV3MessageProcessingModel.messageProcessingModelID: - SnmpV3MessageProcessingModel() + SnmpV3MessageProcessingModel() } self.securityModels = { SnmpV1SecurityModel.securityModelID: SnmpV1SecurityModel(), @@ -85,11 +87,14 @@ class SnmpEngine: raise error.PySnmpError( 'MIB instrumentation does not yet exist' ) - snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize) - snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') + snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineBoots') snmpEngineBoots.syntax += 1 - origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') if snmpEngineID is None: self.snmpEngineID = origSnmpEngineID.syntax @@ -97,7 +102,8 @@ class SnmpEngine: origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) self.snmpEngineID = origSnmpEngineID.syntax - debug.logger & debug.flagApp and debug.logger('SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint()) + debug.logger & debug.flagApp and debug.logger( + 'SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint()) # Attempt to make some of snmp Engine settings persistent. # This should probably be generalized as a non-volatile MIB store. @@ -115,12 +121,12 @@ class SnmpEngine: f = os.path.join(persistentPath, 'boots') try: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(open(f).read()) - except: + except Exception: pass try: snmpEngineBoots.syntax += 1 - except: + except Exception: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(1) try: @@ -128,14 +134,16 @@ class SnmpEngine: os.write(fd, snmpEngineBoots.syntax.prettyPrint()) os.close(fd) os.rename(fn, f) - except: - debug.logger & debug.flagApp and debug.logger('SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) + except Exception: + debug.logger & debug.flagApp and debug.logger( + 'SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) else: - debug.logger & debug.flagApp and debug.logger('SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) + debug.logger & debug.flagApp and debug.logger( + 'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) def __repr__(self): return '%s(snmpEngineID=%r)' % \ - (self.__class__.__name__, self.snmpEngineID) + (self.__class__.__name__, self.snmpEngineID) # Transport dispatcher bindings @@ -193,4 +201,3 @@ class SnmpEngine: del self.cache['__%s' % arg] except KeyError: pass - diff --git a/pysnmp/entity/observer.py b/pysnmp/entity/observer.py index c18546da..2e137129 100644 --- a/pysnmp/entity/observer.py +++ b/pysnmp/entity/observer.py @@ -6,6 +6,7 @@ # from pysnmp import error + class MetaObserver: """This is a simple facility for exposing internal SNMP Engine working details to pysnmp applications. These details are @@ -21,6 +22,7 @@ class MetaObserver: to exist to functions that are at the same or deeper level of invocation relative to execution point specified. """ + def __init__(self): self.__observers = {} self.__contexts = {} @@ -32,7 +34,7 @@ class MetaObserver: else: self.__contexts[cbFun] = kwargs.get('cbCtx') for execpoint in execpoints: - if not execpoint in self.__observers: + if execpoint not in self.__observers: self.__observers[execpoint] = [] self.__observers[execpoint].append(cbFun) diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py index 200326f3..e174c379 100644 --- a/pysnmp/entity/rfc3413/cmdgen.py +++ b/pysnmp/entity/rfc3413/cmdgen.py @@ -17,16 +17,17 @@ getNextHandle = nextid.Integer(0x7fffffff) __null = univ.Null('') + def getNextVarBinds(varBinds, origVarBinds=None): errorIndication = None idx = nonNulls = len(varBinds) rspVarBinds = [] while idx: - idx = idx - 1 + idx -= 1 if varBinds[idx][1].tagSet in (rfc1905.NoSuchObject.tagSet, rfc1905.NoSuchInstance.tagSet, rfc1905.EndOfMibView.tagSet): - nonNulls = nonNulls - 1 + nonNulls -= 1 elif origVarBinds is not None: if v2c.ObjectIdentifier(origVarBinds[idx][0]).asTuple() >= varBinds[idx][0].asTuple(): errorIndication = errind.oidNotIncreasing @@ -38,8 +39,10 @@ def getNextVarBinds(varBinds, origVarBinds=None): return errorIndication, rspVarBinds + class CommandGenerator: _null = univ.Null('') + def __init__(self): self.__pendingReqs = {} @@ -64,16 +67,17 @@ class CommandGenerator: # 3.1.3 if statusInformation: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) errorIndication = statusInformation['errorIndication'] # SNMP engine discovery will take extra retries, allow that if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID) and \ - origRetries == origRetryCount + 2 or \ - errorIndication not in (errind.notInTimeWindow, - errind.unknownEngineID) and \ - origRetries == origRetryCount: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) + origRetries == origRetryCount + 2 or \ + errorIndication not in (errind.notInTimeWindow, errind.unknownEngineID) and \ + origRetries == origRetryCount: + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) cbFun(snmpEngine, origSendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return @@ -99,19 +103,22 @@ class CommandGenerator: except StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % (sendPduHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % ( + sendPduHandle, statusInformation)) cbFun(snmpEngine, origSendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return if origMessageProcessingModel != messageProcessingModel or \ - origSecurityModel != securityModel or \ - origSecurityName != origSecurityName or \ - origContextEngineId and origContextEngineId != contextEngineId or \ - origContextName and origContextName != contextName or \ - origPduVersion != pduVersion: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) + origSecurityModel != securityModel or \ + origSecurityName != origSecurityName or \ + origContextEngineId and origContextEngineId != contextEngineId or \ + origContextName and origContextName != contextName or \ + origPduVersion != pduVersion: + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) @@ -123,7 +130,8 @@ class CommandGenerator: # 3.1.2 if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu): - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) return @@ -138,9 +146,10 @@ class CommandGenerator: securityLevel) = config.getTargetInfo(snmpEngine, targetName) # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() - SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') + SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') # Cast possible strings into bytes if contextEngineId: @@ -176,13 +185,17 @@ class CommandGenerator: retryCount, 0 ) - debug.logger & debug.flagApp and debug.logger('sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % (sendPduHandle, timeout, timeoutInTicks, retryCount)) + debug.logger & debug.flagApp and debug.logger( + 'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % ( + sendPduHandle, timeout, timeoutInTicks, retryCount)) return sendRequestHandle + # backward compatibility stub CommandGeneratorBase = CommandGenerator + class GetCommandGenerator(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -204,6 +217,7 @@ class GetCommandGenerator(CommandGenerator): contextName, reqPDU, self.processResponseVarBinds, (cbFun, cbCtx)) + class SetCommandGenerator(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -225,6 +239,7 @@ class SetCommandGenerator(CommandGenerator): contextName, reqPDU, self.processResponseVarBinds, (cbFun, cbCtx)) + class NextCommandGeneratorSingleRun(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -247,6 +262,7 @@ class NextCommandGeneratorSingleRun(CommandGenerator): (targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) + class NextCommandGenerator(NextCommandGeneratorSingleRun): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -272,11 +288,12 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): v2c.apiPDU.getErrorStatus(PDU), v2c.apiPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) return # app says enough if not varBinds: - return # no more objects available + return # no more objects available v2c.apiPDU.setRequestID(reqPDU, v2c.getNextRequestID()) v2c.apiPDU.setVarBinds(reqPDU, varBinds) @@ -290,11 +307,13 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): except StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) + class BulkCommandGeneratorSingleRun(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -324,6 +343,7 @@ class BulkCommandGeneratorSingleRun(CommandGenerator): contextEngineId, contextName, reqPDU, cbFun, cbCtx)) + class BulkCommandGenerator(BulkCommandGeneratorSingleRun): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -353,16 +373,16 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): v2c.apiBulkPDU.getErrorStatus(PDU), v2c.apiBulkPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) - return # app says enough + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) + return # app says enough if not varBinds: - return # no more objects available + return # no more objects available v2c.apiBulkPDU.setRequestID(reqPDU, v2c.getNextRequestID()) v2c.apiBulkPDU.setVarBinds(reqPDU, varBinds) - try: self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, @@ -372,10 +392,13 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): except StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % ( + sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) + # # Obsolete, compatibility interfaces. # @@ -386,12 +409,14 @@ def __sendReqCbFun(snmpEngine, sendRequestHandle, errorIndication, return cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx) + def _sendReq(self, snmpEngine, targetName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName=''): return self.sendVarBinds(snmpEngine, targetName, contextEngineId, contextName, varBinds, __sendReqCbFun, (cbFun, cbCtx)) + def _sendBulkReq(self, snmpEngine, targetName, nonRepeaters, maxRepetitions, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName=''): @@ -399,6 +424,7 @@ def _sendBulkReq(self, snmpEngine, targetName, nonRepeaters, maxRepetitions, contextName, nonRepeaters, maxRepetitions, varBinds, __sendReqCbFun, (cbFun, cbCtx)) + # install compatibility wrappers GetCommandGenerator.sendReq = _sendReq SetCommandGenerator.sendReq = _sendReq diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py index aa512170..60c64ad3 100644 --- a/pysnmp/entity/rfc3413/cmdrsp.py +++ b/pysnmp/entity/rfc3413/cmdrsp.py @@ -11,6 +11,7 @@ from pysnmp.proto.proxy import rfc2576 import pysnmp.smi.error from pysnmp import debug + # 3.2 class CommandResponderBase: acmID = 3 # default MIB access control method to use @@ -19,7 +20,7 @@ class CommandResponderBase: def __init__(self, snmpEngine, snmpContext): snmpEngine.msgAndPduDsp.registerContextEngineId( snmpContext.contextEngineId, self.pduTypes, self.processPdu - ) + ) self.snmpContext = snmpContext self.__pendingReqs = {} @@ -44,7 +45,10 @@ class CommandResponderBase: v2c.apiPDU.setErrorIndex(PDU, errorIndex) v2c.apiPDU.setVarBinds(PDU, varBinds) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % (stateReference, errorStatus, errorIndex, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % ( + stateReference, errorStatus, errorIndex, varBinds) + ) self.sendPdu(snmpEngine, stateReference, PDU) @@ -79,8 +83,10 @@ class CommandResponderBase: ) except error.StatusInformation: - debug.logger & debug.flagApp and debug.logger('sendPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') + debug.logger & debug.flagApp and debug.logger( + 'sendPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpSilentDrops') snmpSilentDrops.syntax += 1 _getRequestType = rfc1905.GetRequestPDU.tagSet @@ -105,7 +111,7 @@ class CommandResponderBase: # 3.2.1 if PDU.tagSet not in rfc3411.readClassPDUs and \ - PDU.tagSet not in rfc3411.writeClassPDUs: + PDU.tagSet not in rfc3411.writeClassPDUs: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) # 3.2.2 --> no-op @@ -125,16 +131,18 @@ class CommandResponderBase: varBinds = v2c.apiPDU.getVarBinds(PDU) errorStatus, errorIndex = 'noError', 0 - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) try: self.handleMgmtOperation(snmpEngine, stateReference, - contextName, PDU, + contextName, PDU, (self.__verifyAccess, snmpEngine)) # SNMPv2 SMI exceptions except pysnmp.smi.error.GenError: errorIndication = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) if 'oid' in errorIndication: # Request REPORT generation statusInformation['oid'] = errorIndication['oid'] @@ -195,17 +203,19 @@ class CommandResponderBase: # Map ACM errors onto SMI ones except error.StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + '__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) errorIndication = statusInformation['errorIndication'] # 3.2.5... if errorIndication == errind.noSuchView or \ - errorIndication == errind.noAccessEntry or \ - errorIndication == errind.noGroupName: + errorIndication == errind.noAccessEntry or \ + errorIndication == errind.noGroupName: raise pysnmp.smi.error.AuthorizationError(name=name, idx=idx) elif errorIndication == errind.otherError: raise pysnmp.smi.error.GenError(name=name, idx=idx) elif errorIndication == errind.noSuchContext: - snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-TARGET-MIB', 'snmpUnknownContexts') + snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-TARGET-MIB', 'snmpUnknownContexts') snmpUnknownContexts.syntax += 1 # Request REPORT generation raise pysnmp.smi.error.GenError(name=name, idx=idx, @@ -218,11 +228,12 @@ class CommandResponderBase: else: # rfc2576: 4.1.2.1 if securityModel == 1 and syntax is not None and \ - self._counter64Type == syntax.getTagSet() and \ - self._getNextRequestType == pduType: + self._counter64Type == syntax.getTagSet() and \ + self._getNextRequestType == pduType: # This will cause MibTree to skip this OID-value raise pysnmp.smi.error.NoAccessError(name=name, idx=idx) + class GetCommandResponder(CommandResponderBase): pduTypes = (rfc1905.GetRequestPDU.tagSet,) @@ -236,6 +247,7 @@ class GetCommandResponder(CommandResponderBase): mgmtFun(v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx))) self.releaseStateInformation(stateReference) + class NextCommandResponder(CommandResponderBase): pduTypes = (rfc1905.GetNextRequestPDU.tagSet,) @@ -257,6 +269,7 @@ class NextCommandResponder(CommandResponderBase): break self.releaseStateInformation(stateReference) + class BulkCommandResponder(CommandResponderBase): pduTypes = (rfc1905.GetBulkRequestPDU.tagSet,) maxVarBinds = 64 @@ -276,10 +289,10 @@ class BulkCommandResponder(CommandResponderBase): N = min(int(nonRepeaters), len(reqVarBinds)) M = int(maxRepetitions) - R = max(len(reqVarBinds)-N, 0) + R = max(len(reqVarBinds) - N, 0) if R: - M = min(M, self.maxVarBinds/R) + M = min(M, self.maxVarBinds / R) debug.logger & debug.flagApp and debug.logger('handleMgmtOperation: N %d, M %d, R %d' % (N, M, R)) @@ -294,7 +307,7 @@ class BulkCommandResponder(CommandResponderBase): while M and R: rspVarBinds.extend(mgmtFun(varBinds, (acFun, acCtx))) varBinds = rspVarBinds[-R:] - M = M - 1 + M -= 1 if len(rspVarBinds): self.sendVarBinds(snmpEngine, stateReference, 0, 0, rspVarBinds) @@ -302,6 +315,7 @@ class BulkCommandResponder(CommandResponderBase): else: raise pysnmp.smi.error.SmiError() + class SetCommandResponder(CommandResponderBase): pduTypes = (rfc1905.SetRequestPDU.tagSet,) diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py index adbf6dae..a73f9168 100644 --- a/pysnmp/entity/rfc3413/config.py +++ b/pysnmp/entity/rfc3413/config.py @@ -7,6 +7,7 @@ from pysnmp.smi.error import SmiError, NoSuchInstanceError from pysnmp.entity import config + def getTargetAddr(snmpEngine, snmpTargetAddrName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -30,10 +31,10 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetAddrParams) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', - 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', - 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' - ) + 'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', + 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', + 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' + ) snmpSourceAddrTAddress, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(snmpTargetAddrName) @@ -63,12 +64,14 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain) if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', + 'SnmpUDPAddress') snmpTargetAddrTAddress = transport.addressType( SnmpUDPAddress(snmpTargetAddrTAddress) ).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress)) elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain: - TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') snmpTargetAddrTAddress = transport.addressType( TransportAddressIPv6(snmpTargetAddrTAddress) ).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress)) @@ -111,10 +114,10 @@ def getTargetParams(snmpEngine, paramsName): (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel', - 'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName', - 'snmpTargetParamsSecurityLevel' - ) + 'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel', + 'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName', + 'snmpTargetParamsSecurityLevel' + ) tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(paramsName) @@ -143,6 +146,7 @@ def getTargetParams(snmpEngine, paramsName): return nameToParamsMap[paramsName] + def getTargetInfo(snmpEngine, snmpTargetAddrName): # Transport endpoint (snmpTargetAddrTDomain, @@ -162,6 +166,7 @@ def getTargetInfo(snmpEngine, snmpTargetAddrName): snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) + def getNotificationInfo(snmpEngine, notificationTarget): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -206,6 +211,7 @@ def getNotificationInfo(snmpEngine, notificationTarget): return targetToNotifyMap[notificationTarget] + def getTargetNames(snmpEngine, tag): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -226,9 +232,9 @@ def getTargetNames(snmpEngine, tag): (SnmpTagValue, snmpTargetAddrName, snmpTargetAddrTagList) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', - 'snmpTargetAddrTagList' - ) + 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', + 'snmpTargetAddrTagList' + ) mibNode = snmpTargetAddrTagList while True: try: diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py index 512c93fb..e0b73ef4 100644 --- a/pysnmp/entity/rfc3413/context.py +++ b/pysnmp/entity/rfc3413/context.py @@ -9,9 +9,11 @@ from pyasn1.compat.octets import null from pysnmp import error from pysnmp import debug + class SnmpContext: def __init__(self, snmpEngine, contextEngineId=None): - snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') if contextEngineId is None: # Default to local snmpEngineId self.contextEngineId = snmpEngineId.syntax @@ -19,16 +21,17 @@ class SnmpContext: self.contextEngineId = snmpEngineId.syntax.clone(contextEngineId) debug.logger & debug.flagIns and debug.logger('SnmpContext: contextEngineId \"%r\"' % (self.contextEngineId,)) self.contextNames = { - null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name - } + null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name + } def registerContextName(self, contextName, mibInstrum=None): contextName = univ.OctetString(contextName).asOctets() if contextName in self.contextNames: raise error.PySnmpError( 'Duplicate contextName %s' % contextName - ) - debug.logger & debug.flagIns and debug.logger('registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum)) + ) + debug.logger & debug.flagIns and debug.logger( + 'registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum)) if mibInstrum is None: self.contextNames[contextName] = self.contextNames[null] else: @@ -37,7 +40,8 @@ class SnmpContext: def unregisterContextName(self, contextName): contextName = univ.OctetString(contextName).asOctets() if contextName in self.contextNames: - debug.logger & debug.flagIns and debug.logger('unregisterContextName: unregistered contextName %r' % contextName) + debug.logger & debug.flagIns and debug.logger( + 'unregisterContextName: unregistered contextName %r' % contextName) del self.contextNames[contextName] def getMibInstrum(self, contextName=null): @@ -46,7 +50,8 @@ class SnmpContext: debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName %r not registered' % contextName) raise error.PySnmpError( 'Missing contextName %s' % contextName - ) + ) else: - debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName])) + debug.logger & debug.flagIns and debug.logger( + 'getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName])) return self.contextNames[contextName] diff --git a/pysnmp/entity/rfc3413/mibvar.py b/pysnmp/entity/rfc3413/mibvar.py index 7cc46123..fdcef9f5 100644 --- a/pysnmp/entity/rfc3413/mibvar.py +++ b/pysnmp/entity/rfc3413/mibvar.py @@ -10,16 +10,17 @@ from pyasn1.type import univ from pysnmp.smi.error import NoSuchObjectError + # Name def mibNameToOid(mibView, name): if isinstance(name[0], tuple): f = lambda x='', y='': (x, y) modName, symName = f(*name[0]) - if modName: # load module if needed + if modName: # load module if needed mibView.mibBuilder.loadModules(modName) else: - mibView.mibBuilder.loadModules() # load all (slow) + mibView.mibBuilder.loadModules() # load all (slow) if symName: oid, label, suffix = mibView.getNodeNameByDesc(symName, modName) else: @@ -28,12 +29,12 @@ def mibNameToOid(mibView, name): modName, symName, _s = mibView.getNodeLocation(oid) mibNode, = mibView.mibBuilder.importSymbols( modName, symName - ) - if hasattr(mibNode, 'createTest'): # table column XXX + ) + if hasattr(mibNode, 'createTest'): # table column XXX modName, symName, _s = mibView.getNodeLocation(oid[:-1]) rowNode, = mibView.mibBuilder.importSymbols(modName, symName) return oid, rowNode.getInstIdFromIndices(*suffix) - else: # scalar or incomplete spec + else: # scalar or incomplete spec return oid, suffix elif not isinstance(name, tuple): name = tuple(univ.ObjectIdentifier(name)) @@ -42,8 +43,10 @@ def mibNameToOid(mibView, name): return oid, suffix + __scalarSuffix = (univ.Integer(0),) + def oidToMibName(mibView, oid): if not isinstance(oid, tuple): oid = tuple(univ.ObjectIdentifier(oid)) @@ -51,27 +54,29 @@ def oidToMibName(mibView, oid): modName, symName, __suffix = mibView.getNodeLocation(_oid) mibNode, = mibView.mibBuilder.importSymbols( modName, symName - ) - if hasattr(mibNode, 'createTest'): # table column + ) + if hasattr(mibNode, 'createTest'): # table column __modName, __symName, __s = mibView.getNodeLocation(_oid[:-1]) rowNode, = mibView.mibBuilder.importSymbols(__modName, __symName) return (symName, modName), rowNode.getIndicesFromInstId(suffix) - elif not suffix: # scalar + elif not suffix: # scalar return (symName, modName), suffix - elif suffix == (0,): # scalar + elif suffix == (0,): # scalar return (symName, modName), __scalarSuffix else: raise NoSuchObjectError( - str='No MIB registered that defines %s object, closest known parent is %s (%s::%s)' % (univ.ObjectIdentifier(oid), univ.ObjectIdentifier(mibNode.name), modName, symName) - ) + str='No MIB registered that defines %s object, closest known parent is %s (%s::%s)' % ( + univ.ObjectIdentifier(oid), univ.ObjectIdentifier(mibNode.name), modName, symName) + ) + # Value def cloneFromMibValue(mibView, modName, symName, value): mibNode, = mibView.mibBuilder.importSymbols( modName, symName - ) - if hasattr(mibNode, 'syntax'): # scalar + ) + if hasattr(mibNode, 'syntax'): # scalar return mibNode.syntax.clone(value) else: - return # identifier + return # identifier diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py index 66d7f33d..c9bd69c4 100644 --- a/pysnmp/entity/rfc3413/ntforg.py +++ b/pysnmp/entity/rfc3413/ntforg.py @@ -17,8 +17,10 @@ from pysnmp import debug getNextHandle = nextid.Integer(0x7fffffff) + class NotificationOriginator: acmID = 3 # default MIB access control method to use + def __init__(self, snmpContext=None): self.__pendingReqs = {} self.__pendingNotifications = {} @@ -43,15 +45,19 @@ class NotificationOriginator: snmpEngine.transportDispatcher.jobFinished(id(self)) if statusInformation: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % (sendRequestHandle, sendPduHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % ( + sendRequestHandle, sendPduHandle, statusInformation)) if origRetries == origRetryCount: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % (sendRequestHandle, sendPduHandle, origRetries)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % ( + sendRequestHandle, sendPduHandle, origRetries)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(origTimeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = float(origTimeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() # User-side API assumes SMIv2 if messageProcessingModel == 0: @@ -73,14 +79,18 @@ class NotificationOriginator: ) except error.StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % ( + sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return snmpEngine.transportDispatcher.jobStarted(id(self)) - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % (sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % ( + sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( @@ -118,7 +128,7 @@ class NotificationOriginator: # 3.3.5 if reqPDU.tagSet in rfc3411.confirmedClassPDUs: # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() sendRequestHandle = getNextHandle() @@ -131,7 +141,8 @@ class NotificationOriginator: self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) - debug.logger & debug.flagApp and debug.logger('sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) + debug.logger & debug.flagApp and debug.logger( + 'sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( @@ -160,10 +171,14 @@ class NotificationOriginator: self.__pendingNotifications[notificationHandle].remove(sendRequestHandle) - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, errorIndication %s, pending requests %s' % (notificationHandle, sendRequestHandle, errorIndication, self.__pendingNotifications[notificationHandle])) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, errorIndication %s, pending requests %s' % ( + notificationHandle, sendRequestHandle, errorIndication, self.__pendingNotifications[notificationHandle])) if not self.__pendingNotifications[notificationHandle]: - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % (notificationHandle, sendRequestHandle)) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % ( + notificationHandle, sendRequestHandle)) del self.__pendingNotifications[notificationHandle] cbFun(snmpEngine, sendRequestHandle, errorIndication, pdu and v2c.apiPDU.getErrorStatus(pdu) or 0, @@ -177,10 +192,13 @@ class NotificationOriginator: # def sendVarBinds(self, snmpEngine, notificationTarget, contextEngineId, contextName, varBinds=(), cbFun=None, cbCtx=None): - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % (notificationTarget, contextEngineId or '', contextName, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % ( + notificationTarget, contextEngineId or '', contextName, varBinds)) if contextName: - __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') + __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-FRAMEWORK-MIB', 'SnmpAdminString') contextName = __SnmpAdminString(contextName) # 3.3 @@ -188,12 +206,16 @@ class NotificationOriginator: notificationHandle = getNextHandle() - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % (notificationHandle, notifyTag, notifyType)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % ( + notificationHandle, notifyTag, notifyType)) varBinds = [(v2c.ObjectIdentifier(x), y) for x, y in varBinds] # 3.3.2 & 3.3.3 - snmpTrapOID, sysUpTime = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpTrapOID', 'sysUpTime') + snmpTrapOID, sysUpTime = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpTrapOID', + 'sysUpTime') for idx in range(len(varBinds)): if idx and varBinds[idx][0] == sysUpTime.getName(): @@ -211,6 +233,8 @@ class NotificationOriginator: varBinds.insert(1, (v2c.ObjectIdentifier(snmpTrapOID.getName()), snmpTrapOID.getSyntax())) + sendRequestHandle = -1 + debug.logger & debug.flagApp and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,)) for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): @@ -221,13 +245,16 @@ class NotificationOriginator: securityLevel) = config.getTargetParams(snmpEngine, params) # 3.3.1 XXX -# XXX filtering's yet to be implemented -# filterProfileName = config.getNotifyFilterProfile(params) + # XXX filtering's yet to be implemented + # filterProfileName = config.getNotifyFilterProfile(params) -# (filterSubtree, filterMask, -# filterType) = config.getNotifyFilter(filterProfileName) + # (filterSubtree, filterMask, + # filterType) = config.getNotifyFilter(filterProfileName) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % (notificationHandle, notifyTag, transportDomain, transportAddress, securityModel, securityName, securityLevel)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % ( + notificationHandle, notifyTag, transportDomain, transportAddress, securityModel, + securityName, securityLevel)) for varName, varVal in varBinds: if varName in (sysUpTime.name, snmpTrapOID.name): @@ -238,10 +265,13 @@ class NotificationOriginator: securityLevel, 'notify', contextName, varName ) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) except error.StatusInformation: - debug.logger & debug.flagApp and debug.logger('sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % (varName, securityName)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % ( + varName, securityName)) return # 3.3.4 @@ -265,9 +295,11 @@ class NotificationOriginator: except error.StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % ( + sendRequestHandle, statusInformation)) if notificationHandle not in self.__pendingNotifications or \ - not self.__pendingNotifications[notificationHandle]: + not self.__pendingNotifications[notificationHandle]: if notificationHandle in self.__pendingNotifications: del self.__pendingNotifications[notificationHandle] if cbFun: @@ -276,17 +308,22 @@ class NotificationOriginator: cbCtx) return notificationHandle - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % (notificationHandle, sendRequestHandle, timeout)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % ( + notificationHandle, sendRequestHandle, timeout)) if notifyType == 2: if notificationHandle not in self.__pendingNotifications: self.__pendingNotifications[notificationHandle] = set() self.__pendingNotifications[notificationHandle].add(sendRequestHandle) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % (notificationHandle, sendRequestHandle)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % ( + notificationHandle, sendRequestHandle)) return notificationHandle + # # Obsolete, compatibility interfaces. # @@ -303,6 +340,7 @@ def _sendNotificationCbFun(snmpEngine, sendRequestHandle, errorIndication, # a backward compatible way of calling user function cbFun(sendRequestHandle, errorIndication, cbCtx) + def _sendNotification(self, snmpEngine, notificationTarget, notificationName, additionalVarBinds=(), cbFun=None, cbCtx=None, contextName=null, instanceIndex=None): @@ -342,6 +380,7 @@ def _sendNotification(self, snmpEngine, notificationTarget, notificationName, contextName, varBinds + list(additionalVarBinds), _sendNotificationCbFun, (cbFun, cbCtx)) + # install compatibility wrapper NotificationOriginator.sendNotification = _sendNotification diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py index 2b79f9f1..55b2841c 100644 --- a/pysnmp/entity/rfc3413/ntfrcv.py +++ b/pysnmp/entity/rfc3413/ntfrcv.py @@ -11,6 +11,7 @@ from pysnmp.proto.api import v1, v2c # backend is always SMIv2 compliant from pysnmp.proto.proxy import rfc2576 from pysnmp import debug + # 3.4 class NotificationReceiver: pduTypes = (v1.TrapPDU.tagSet, v2c.SNMPv2TrapPDU.tagSet, @@ -18,7 +19,7 @@ class NotificationReceiver: def __init__(self, snmpEngine, cbFun, cbCtx=None): snmpEngine.msgAndPduDsp.registerContextEngineId( - null, self.pduTypes, self.processPdu # '' is a wildcard + null, self.pduTypes, self.processPdu # '' is a wildcard ) self.__cbFunVer = 0 self.__cbFun = cbFun @@ -46,7 +47,8 @@ class NotificationReceiver: errorIndex = 0 varBinds = v2c.apiPDU.getVarBinds(PDU) - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) # 3.4 if PDU.tagSet in rfc3411.confirmedClassPDUs: @@ -59,7 +61,8 @@ class NotificationReceiver: v2c.apiPDU.setErrorIndex(rspPDU, errorIndex) v2c.apiPDU.setVarBinds(rspPDU, varBinds) - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint())) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint())) # Agent-side API complies with SMIv2 if messageProcessingModel == 0: @@ -76,8 +79,10 @@ class NotificationReceiver: stateReference, statusInformation) except error.StatusInformation: - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpSilentDrops') snmpSilentDrops.syntax += 1 elif PDU.tagSet in rfc3411.unconfirmedClassPDUs: @@ -85,7 +90,9 @@ class NotificationReceiver: else: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (stateReference, self.__cbFun, self.__cbCtx, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % ( + stateReference, self.__cbFun, self.__cbCtx, varBinds)) if self.__cbFunVer: self.__cbFun(snmpEngine, stateReference, contextEngineId, diff --git a/pysnmp/entity/rfc3413/oneliner/cmdgen.py b/pysnmp/entity/rfc3413/oneliner/cmdgen.py index 61bfbbbc..411fc40c 100644 --- a/pysnmp/entity/rfc3413/oneliner/cmdgen.py +++ b/pysnmp/entity/rfc3413/oneliner/cmdgen.py @@ -18,6 +18,7 @@ __all__ = ['AsynCommandGenerator', 'CommandGenerator', 'MibVariable'] MibVariable = ObjectIdentity + class AsynCommandGenerator: _null = univ.Null('') @@ -26,7 +27,7 @@ class AsynCommandGenerator: def __init__(self, snmpEngine=None): if snmpEngine is None: - self.snmpEngine = snmpEngine = SnmpEngine() + self.snmpEngine = SnmpEngine() else: self.snmpEngine = snmpEngine @@ -95,7 +96,6 @@ class AsynCommandGenerator: if contextName is null and authData.contextName: contextName = authData.contextName - return setCmd( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId, contextName), *varBinds, @@ -159,8 +159,10 @@ class AsynCommandGenerator: asyncBulkCmd = bulkCmd + class CommandGenerator: _null = univ.Null('') + def __init__(self, snmpEngine=None, asynCmdGen=None): # compatibility attributes self.snmpEngine = snmpEngine or SnmpEngine() @@ -172,8 +174,8 @@ class CommandGenerator: kwargs['lookupValues'] = False errorIndication, errorStatus, errorIndex, varBinds = None, 0, 0, [] for errorIndication, \ - errorStatus, errorIndex, \ - varBinds \ + errorStatus, errorIndex, \ + varBinds \ in sync.getCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), @@ -189,8 +191,8 @@ class CommandGenerator: kwargs['lookupValues'] = False errorIndication, errorStatus, errorIndex, rspVarBinds = None, 0, 0, [] for errorIndication, \ - errorStatus, errorIndex, \ - rspVarBinds \ + errorStatus, errorIndex, \ + rspVarBinds \ in sync.setCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), @@ -210,8 +212,8 @@ class CommandGenerator: errorIndication, errorStatus, errorIndex = None, 0, 0 varBindTable = [] for errorIndication, \ - errorStatus, errorIndex, \ - varBinds \ + errorStatus, errorIndex, \ + varBinds \ in sync.nextCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), @@ -235,8 +237,8 @@ class CommandGenerator: errorIndication, errorStatus, errorIndex = None, 0, 0 varBindTable = [] for errorIndication, \ - errorStatus, errorIndex, \ - varBinds \ + errorStatus, errorIndex, \ + varBinds \ in sync.bulkCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), diff --git a/pysnmp/entity/rfc3413/oneliner/ntforg.py b/pysnmp/entity/rfc3413/oneliner/ntforg.py index ddb7438f..2436b5ba 100644 --- a/pysnmp/entity/rfc3413/oneliner/ntforg.py +++ b/pysnmp/entity/rfc3413/oneliner/ntforg.py @@ -21,6 +21,7 @@ __all__ = ['AsynNotificationOriginator', MibVariable = ObjectIdentity + class ErrorIndicationReturn: def __init__(self, *vars): self.__vars = vars @@ -29,7 +30,7 @@ class ErrorIndicationReturn: return self.__vars[i] def __nonzero__(self): - return self.__vars[0] and 1 or 0 + return bool(self) def __bool__(self): return bool(self.__vars[0]) @@ -37,9 +38,11 @@ class ErrorIndicationReturn: def __str__(self): return str(self.__vars[0]) + class AsynNotificationOriginator: vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() + def __init__(self, snmpEngine=None, snmpContext=None): if snmpEngine is None: self.snmpEngine = snmpEngine = SnmpEngine() @@ -133,8 +136,10 @@ class AsynNotificationOriginator: asyncSendNotification = sendNotification + class NotificationOriginator: vbProcessor = NotificationOriginatorVarBinds() + def __init__(self, snmpEngine=None, snmpContext=None, asynNtfOrg=None): # compatibility attributes self.snmpEngine = snmpEngine or SnmpEngine() @@ -162,15 +167,15 @@ class NotificationOriginator: for errorIndication, \ errorStatus, errorIndex, \ rspVarBinds \ - in sync.sendNotification(self.snmpEngine, authData, - transportTarget, - ContextData( - kwargs.get('contextEngineId'), - kwargs.get('contextName', null) - ), - notifyType, - notificationType.addVarBinds(*varBinds), - **kwargs): + in sync.sendNotification(self.snmpEngine, authData, + transportTarget, + ContextData( + kwargs.get('contextEngineId'), + kwargs.get('contextName', null) + ), + notifyType, + notificationType.addVarBinds(*varBinds), + **kwargs): if notifyType == 'inform': return errorIndication, errorStatus, errorIndex, rspVarBinds else: -- cgit v1.2.1