diff options
35 files changed, 1095 insertions, 1969 deletions
diff --git a/pysnmp/carrier/asyncio/dgram/udp6.py b/pysnmp/carrier/asyncio/dgram/udp6.py index 7c92716f..b80187d2 100644 --- a/pysnmp/carrier/asyncio/dgram/udp6.py +++ b/pysnmp/carrier/asyncio/dgram/udp6.py @@ -19,15 +19,12 @@ class Udp6AsyncioTransport(DgramAsyncioProtocol): def normalizeAddress(self, transportAddress): if '%' in transportAddress[0]: # strip zone ID - return self.addressType( - (transportAddress[0].split('%')[0], - transportAddress[1], - 0, # flowinfo - 0) # scopeid - ) + return self.addressType((transportAddress[0].split('%')[0], + transportAddress[1], + 0, # flowinfo + 0)) # scopeid else: - return self.addressType( - (transportAddress[0], transportAddress[1], 0, 0) - ) + return self.addressType((transportAddress[0], + transportAddress[1], 0, 0)) Udp6Transport = Udp6AsyncioTransport diff --git a/pysnmp/carrier/asyncio/dispatch.py b/pysnmp/carrier/asyncio/dispatch.py index ca96683e..4bc54b62 100644 --- a/pysnmp/carrier/asyncio/dispatch.py +++ b/pysnmp/carrier/asyncio/dispatch.py @@ -81,14 +81,12 @@ class AsyncioDispatcher(AbstractTransportDispatcher): # Trollius or Tulip? if not hasattr(asyncio, "From"): - exec( -"""\ + exec("""\ @asyncio.coroutine def handle_timeout(self): while True: yield from asyncio.sleep(self.getTimerResolution()) self.handleTimerTick(loop.time()) AsyncioDispatcher.handle_timeout = handle_timeout\ -""" - ) +""") diff --git a/pysnmp/carrier/asyncore/dgram/udp6.py b/pysnmp/carrier/asyncore/dgram/udp6.py index 28ba1540..c6a69c0a 100644 --- a/pysnmp/carrier/asyncore/dgram/udp6.py +++ b/pysnmp/carrier/asyncore/dgram/udp6.py @@ -20,9 +20,8 @@ class Udp6SocketTransport(DgramSocketTransport): 0, # flowinfo 0)) # scopeid else: - ta = self.addressType( - (transportAddress[0], transportAddress[1], 0, 0) - ) + ta = self.addressType((transportAddress[0], + transportAddress[1], 0, 0)) if isinstance(transportAddress, self.addressType) and \ transportAddress.getLocalAddress(): diff --git a/pysnmp/debug.py b/pysnmp/debug.py index fe6967b9..bec85400 100644 --- a/pysnmp/debug.py +++ b/pysnmp/debug.py @@ -109,7 +109,5 @@ def setLogger(l): logger = l def hexdump(octets): - return ' '.join( - ['%s%.2X' % (n%16 == 0 and ('\n%.5d: ' % n) or '', x) - for n, x in zip(range(len(octets)), octs2ints(octets))] - ) + return ' '.join(['%s%.2X' % (n%16 == 0 and ('\n%.5d: ' % n) or '', x) + for n, x in zip(range(len(octets)), octs2ints(octets))]) diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py index 7b4d1ccf..3e323403 100644 --- a/pysnmp/entity/config.py +++ b/pysnmp/entity/config.py @@ -52,9 +52,8 @@ def __cookV1SystemInfo(snmpEngine, communityIndex): def addV1System(snmpEngine, communityIndex, communityName, contextEngineId=None, contextName=None, transportTag=None, securityName=None): - snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( - snmpEngine, communityIndex - ) + (snmpCommunityEntry, tblIdx, + snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) if contextEngineId is None: contextEngineId = snmpEngineID.syntax @@ -79,9 +78,8 @@ def addV1System(snmpEngine, communityIndex, communityName, ) def delV1System(snmpEngine, communityIndex): - snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( - snmpEngine, communityIndex - ) + (snmpCommunityEntry, tblIdx, + snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) @@ -94,9 +92,7 @@ def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): snmpEngineID = snmpEngineID.syntax.clone(securityEngineId) usmUserEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') - tblIdx1 = usmUserEntry.getInstIdFromIndices( - snmpEngineID, securityName - ) + tblIdx1 = usmUserEntry.getInstIdFromIndices(snmpEngineID, securityName) pysnmpUsmSecretEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) @@ -114,10 +110,8 @@ def addV3User(snmpEngine, userName, 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') @@ -156,9 +150,7 @@ def addV3User(snmpEngine, userName, authProtocol, hashedPrivPassphrase, snmpEngineID ) else: - raise error.PySnmpError( - 'Unknown priv protocol %s' % (privProtocol,) - ) + raise error.PySnmpError('Unknown priv protocol %s' % (privProtocol,)) # Commit localized keys snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( @@ -166,18 +158,18 @@ def addV3User(snmpEngine, userName, (pysnmpUsmKeyEntry.name + (2,) + tblIdx1, localPrivKey), (pysnmpUsmKeyEntry.name + (3,) + tblIdx1, hashedAuthPassphrase), (pysnmpUsmKeyEntry.name + (4,) + tblIdx1, hashedPrivPassphrase)) - ) + ) # Commit passphrases snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo'), (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey), (pysnmpUsmSecretEntry.name + (3,) + tblIdx2, privKey),) - ) + ) def delV3User(snmpEngine, userName, @@ -186,10 +178,8 @@ def delV3User(snmpEngine, contextEngineId=None): 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) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) ) @@ -220,16 +210,11 @@ def __cookTargetParamsInfo(snmpEngine, name): tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) return snmpTargetParamsEntry, tblIdx -def addTargetParams( - snmpEngine, - name, - securityName, - securityLevel, - mpModel=3 # 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 - ): +# mpModel: 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 +def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): if mpModel == 0: securityModel = 1 - elif mpModel == 1 or mpModel == 2: + elif mpModel in (1, 2): securityModel = 2 elif mpModel == 3: securityModel = 3 @@ -240,7 +225,7 @@ def addTargetParams( snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo'), (snmpTargetParamsEntry.name + (1,) + tblIdx, name), @@ -248,15 +233,13 @@ def addTargetParams( (snmpTargetParamsEntry.name + (3,) + tblIdx, securityModel), (snmpTargetParamsEntry.name + (4,) + tblIdx, securityName), (snmpTargetParamsEntry.name + (5,) + tblIdx, securityLevel)) - ) + ) def delTargetParams(snmpEngine, name): - snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo( - 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') @@ -264,20 +247,11 @@ def __cookTargetAddrInfo(snmpEngine, addrName): tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) return snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx -def addTargetAddr( - snmpEngine, - addrName, - transportDomain, - transportAddress, - params, - timeout=None, - retryCount=None, - tagList=null, - sourceAddress=None - ): - snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx = __cookTargetAddrInfo( - snmpEngine, addrName - ) +def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, + params, timeout=None, retryCount=None, tagList=null, + sourceAddress=None): + (snmpTargetAddrEntry, snmpSourceAddrEntry, + tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain: SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') @@ -294,7 +268,7 @@ def addTargetAddr( snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo'), (snmpTargetAddrEntry.name + (1,) + tblIdx, addrName), @@ -305,15 +279,14 @@ def addTargetAddr( (snmpTargetAddrEntry.name + (6,) + tblIdx, tagList), (snmpTargetAddrEntry.name + (7,) + tblIdx, params), (snmpSourceAddrEntry.name + (1,) + tblIdx, sourceAddress),) - ) + ) def delTargetAddr(snmpEngine, addrName): - snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx = __cookTargetAddrInfo( - snmpEngine, addrName - ) + (snmpTargetAddrEntry, snmpSourceAddrEntry, + tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) - ) + ) def addTransport(snmpEngine, transportDomain, transport): if snmpEngine.transportDispatcher: @@ -326,9 +299,8 @@ 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' ) @@ -373,64 +345,59 @@ delSocketTransport = delTransport def addContext(snmpEngine, contextName): vacmContextEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.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' ) - tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( - securityModel, securityName - ) + tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices(securityModel, + securityName) return vacmSecurityToGroupEntry, tblIdx def addVacmGroup(snmpEngine, groupName, securityModel, securityName): - vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( - snmpEngine, securityModel, securityName - ) + (vacmSecurityToGroupEntry, + tblIdx) = __cookVacmGroupInfo(snmpEngine, securityModel, securityName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo'), (vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), (vacmSecurityToGroupEntry.name + (3,) + tblIdx, groupName),) - ) + ) def delVacmGroup(snmpEngine, securityModel, securityName): vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( snmpEngine, securityModel, securityName - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) - ) + ) def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel): - vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' - ) - tblIdx = vacmAccessEntry.getInstIdFromIndices( - groupName, contextName, securityModel, securityLevel - ) + vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.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 - ) + vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, + contextName, securityModel, + securityLevel) addContext(snmpEngine, contextName) # this is leaky snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo'), (vacmAccessEntry.name + (1,) + tblIdx, contextName), @@ -440,48 +407,44 @@ def addVacmAccess(snmpEngine, groupName, contextName, securityModel, (vacmAccessEntry.name + (5,) + tblIdx, readView), (vacmAccessEntry.name + (6,) + tblIdx, writeView), (vacmAccessEntry.name + (7,) + tblIdx, notifyView),) - ) + ) def delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel): - vacmAccessEntry, tblIdx = __cookVacmAccessInfo( - snmpEngine, groupName, contextName, securityModel, securityLevel - ) + vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, + contextName, securityModel, + securityLevel) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) - ) + ) def __cookVacmViewInfo(snmpEngine, viewName, subTree): vacmViewTreeFamilyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' - ) - tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices( - viewName, subTree - ) + ) + tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree) return vacmViewTreeFamilyEntry, tblIdx def addVacmView(snmpEngine, viewName, viewType, subTree, mask): - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( - snmpEngine, viewName, subTree - ) + vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, + subTree) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo'), (vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, mask), (vacmViewTreeFamilyEntry.name + (4,) + tblIdx, viewType),) - ) + ) def delVacmView(snmpEngine, viewName, subTree): - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( - snmpEngine, viewName, subTree - ) + vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, + subTree) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) - ) + ) # VACM simplicity wrappers @@ -489,186 +452,153 @@ def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): groupName = 'v-%s-%d' % (hash(securityName), securityModel) SnmpSecurityLevel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') securityLevel = SnmpSecurityLevel(securityLevel) - return ( groupName, securityLevel, - 'r' + groupName, 'w' + groupName, 'n' + groupName ) + return (groupName, securityLevel, + 'r' + groupName, 'w' + groupName, 'n' + groupName) def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): - ( groupName, securityLevel, - readView, writeView, notifyView ) = __cookVacmUserInfo( - snmpEngine, securityModel, securityName, securityLevel, - ) - addVacmGroup( - snmpEngine, groupName, securityModel, securityName - ) - addVacmAccess( - snmpEngine, groupName, contextName, securityModel, securityLevel, 1, - readView, writeView, notifyView - ) + (groupName, securityLevel, readView, writeView, + notifyView) = __cookVacmUserInfo(snmpEngine, securityModel, securityName, + securityLevel) + addVacmGroup(snmpEngine, groupName, securityModel, securityName) + addVacmAccess(snmpEngine, groupName, contextName, securityModel, + securityLevel, 1, readView, writeView, notifyView) if readSubTree: - addVacmView( - snmpEngine, readView, "included", readSubTree, null, - ) + addVacmView(snmpEngine, readView, "included", readSubTree, null) if writeSubTree: - addVacmView( - snmpEngine, writeView, "included", writeSubTree, null, - ) + addVacmView(snmpEngine, writeView, "included", writeSubTree, null) if notifySubTree: - addVacmView( - snmpEngine, notifyView, "included", notifySubTree, null, - ) + addVacmView(snmpEngine, notifyView, "included", notifySubTree, null) def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=()): - ( groupName, securityLevel, - readView, writeView, notifyView ) = __cookVacmUserInfo( - snmpEngine, securityModel, securityName, securityLevel, - ) - delVacmGroup( - snmpEngine, securityModel, securityName - ) - delVacmAccess( - snmpEngine, groupName, null, securityModel, securityLevel - ) + (groupName, securityLevel, readView, writeView, + notifyView) = __cookVacmUserInfo(snmpEngine, securityModel, + securityName, securityLevel) + delVacmGroup(snmpEngine, securityModel, securityName) + delVacmAccess(snmpEngine, groupName, null, securityModel, securityLevel) if readSubTree: delVacmView( snmpEngine, readView, readSubTree - ) + ) if writeSubTree: delVacmView( snmpEngine, writeView, writeSubTree - ) + ) if notifySubTree: delVacmView( snmpEngine, notifyView, notifySubTree - ) + ) # Obsolete shortcuts for add/delVacmUser() wrappers def addRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - addVacmUser( - snmpEngine, securityModel, securityName, securityLevel, subTree - ) + addVacmUser(snmpEngine, securityModel, securityName, + securityLevel, subTree) def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - delVacmUser( - 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 - ) + addVacmUser(snmpEngine, securityModel, securityName, securityLevel, + subTree, subTree) def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - delVacmUser( - snmpEngine, securityModel, securityName, securityLevel, - subTree, subTree - ) + delVacmUser(snmpEngine, securityModel, securityName, securityLevel, + subTree, subTree) def addTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): - addVacmUser( - snmpEngine, securityModel, securityName, securityLevel, - (), (), subTree, - ) + addVacmUser(snmpEngine, securityModel, securityName, securityLevel, + (), (), subTree) def delTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): - delVacmUser( - 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') - tblIdx1 = snmpNotifyEntry.getInstIdFromIndices( - notificationName - ) + tblIdx1 = snmpNotifyEntry.getInstIdFromIndices(notificationName) snmpNotifyFilterProfileEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') - tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices( - paramsName - ) + tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices(paramsName) profileName = '%s-filter' % hash(notificationName) if filterSubtree: snmpNotifyFilterEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') - tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices( - profileName, filterSubtree - ) + tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices(profileName, + filterSubtree) else: snmpNotifyFilterEntry = tblIdx3 = None - return ( snmpNotifyEntry, tblIdx1, - snmpNotifyFilterProfileEntry, tblIdx2, profileName, - snmpNotifyFilterEntry, tblIdx3 ) + return (snmpNotifyEntry, tblIdx1, + snmpNotifyFilterProfileEntry, tblIdx2, profileName, + snmpNotifyFilterEntry, tblIdx3) def addNotificationTarget(snmpEngine, notificationName, paramsName, transportTag, notifyType=None, filterSubtree=None, filterMask=None, filterType=None): - ( snmpNotifyEntry, tblIdx1, - snmpNotifyFilterProfileEntry, tblIdx2, profileName, - snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( - snmpEngine, notificationName, paramsName, filterSubtree - ) + (snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, tblIdx2, + profileName, snmpNotifyFilterEntry, + tblIdx3) = __cookNotificationTargetInfo(snmpEngine, notificationName, + paramsName, filterSubtree) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyEntry.name + (5,) + tblIdx1, 'createAndGo'), (snmpNotifyEntry.name + (2,) + tblIdx1, transportTag), (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'createAndGo'), (snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName),) - ) + ) if not snmpNotifyFilterEntry: return snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo'), (snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), (snmpNotifyFilterEntry.name + (3,) + tblIdx3, filterType),) - ) + ) def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtree=None): - ( snmpNotifyEntry, tblIdx1, - snmpNotifyFilterProfileEntry, tblIdx2, profileName, - snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( - snmpEngine, notificationName, paramsName, filterSubtree - ) + (snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, + tblIdx2, profileName, snmpNotifyFilterEntry, + tblIdx3) = __cookNotificationTargetInfo(snmpEngine, notificationName, + paramsName, filterSubtree) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) - ) + ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) - ) + ) if not snmpNotifyFilterEntry: return snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) - ) + ) # rfc3415: A.1 def setInitialVacmParameters(snmpEngine): diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py index e966b360..90d1df71 100644 --- a/pysnmp/entity/engine.py +++ b/pysnmp/entity/engine.py @@ -134,13 +134,8 @@ class SnmpEngine: # Transport dispatcher bindings - def __receiveMessageCbFun( - self, - transportDispatcher, - transportDomain, - transportAddress, - wholeMsg - ): + def __receiveMessageCbFun(self, transportDispatcher, transportDomain, + transportAddress, wholeMsg): self.msgAndPduDsp.receiveMessage( self, transportDomain, transportAddress, wholeMsg ) diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py index 2e811b7f..dfe9ec13 100644 --- a/pysnmp/entity/rfc3413/cmdrsp.py +++ b/pysnmp/entity/rfc3413/cmdrsp.py @@ -17,9 +17,9 @@ class CommandResponderBase: self.snmpContext = snmpContext self.__pendingReqs = {} - def handleMgmtOperation( - self, snmpEngine, stateReference, contextName, PDU, acInfo - ): pass + def handleMgmtOperation(self, snmpEngine, stateReference, contextName, + PDU, acInfo): + pass def close(self, snmpEngine): snmpEngine.msgAndPduDsp.unregisterContextEngineId( @@ -28,18 +28,11 @@ class CommandResponderBase: self.snmpContext = self.__pendingReqs = None def sendVarBinds(self, snmpEngine, stateReference, - errorStatus, errorIndex, varBinds): - ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - origPdu, - maxSizeResponseScopedPDU, - statusInformation ) = self.__pendingReqs[stateReference] + errorStatus, errorIndex, varBinds): + (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, PDU, origPdu, maxSizeResponseScopedPDU, + statusInformation) = self.__pendingReqs[stateReference] v2c.apiPDU.setErrorStatus(PDU, errorStatus) v2c.apiPDU.setErrorIndex(PDU, errorIndex) @@ -53,17 +46,10 @@ class CommandResponderBase: sendRsp = sendVarBinds def sendPdu(self, snmpEngine, stateReference, PDU): - ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - _, - origPdu, - maxSizeResponseScopedPDU, - statusInformation ) = self.__pendingReqs[stateReference] + (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, _, origPdu, maxSizeResponseScopedPDU, + statusInformation) = self.__pendingReqs[stateReference] # Agent-side API complies with SMIv2 if messageProcessingModel == 0: @@ -84,11 +70,12 @@ class CommandResponderBase: maxSizeResponseScopedPDU, stateReference, statusInformation - ) + ) + 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') - snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 + snmpSilentDrops.syntax += 1 _getRequestType = rfc1905.GetRequestPDU.tagSet _getNextRequestType = rfc1905.GetNextRequestPDU.tagSet @@ -99,20 +86,9 @@ class CommandResponderBase: if stateReference in self.__pendingReqs: del self.__pendingReqs[stateReference] - def processPdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference - ): + def processPdu(self, snmpEngine, messageProcessingModel, securityModel, + securityName, securityLevel, contextEngineId, contextName, + pduVersion, PDU, maxSizeResponseScopedPDU, stateReference): # Agent-side API complies with SMIv2 if messageProcessingModel == 0: @@ -134,18 +110,10 @@ class CommandResponderBase: statusInformation = {} self.__pendingReqs[stateReference] = ( - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - rspPDU, - origPdu, - maxSizeResponseScopedPDU, - statusInformation - ) + messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, pduVersion, + rspPDU, origPdu, maxSizeResponseScopedPDU, statusInformation + ) # 3.2.5 varBinds = v2c.apiPDU.getVarBinds(PDU) @@ -154,10 +122,9 @@ class CommandResponderBase: debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) try: - self.handleMgmtOperation( - snmpEngine, stateReference, - contextName, PDU, (self.__verifyAccess, snmpEngine) - ) + self.handleMgmtOperation(snmpEngine, stateReference, + contextName, PDU, + (self.__verifyAccess, snmpEngine)) # SNMPv2 SMI exceptions except pysnmp.smi.error.GenError: errorIndication = sys.exc_info()[1] @@ -202,31 +169,23 @@ class CommandResponderBase: else: # successful request processor must release state info return - self.sendVarBinds( - snmpEngine, stateReference, errorStatus, errorIndex, varBinds - ) + self.sendVarBinds(snmpEngine, stateReference, errorStatus, + errorIndex, varBinds) self.releaseStateInformation(stateReference) def __verifyAccess(self, name, syntax, idx, viewType, acCtx): snmpEngine = acCtx - execCtx = snmpEngine.observer.getExecutionContext( - 'rfc3412.receiveMessage:request' - ) - ( securityModel, - securityName, - securityLevel, - contextName, - pduType ) = ( execCtx['securityModel'], - execCtx['securityName'], - execCtx['securityLevel'], - execCtx['contextName'], - execCtx['pdu'].getTagSet() ) + execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request') + (securityModel, securityName, securityLevel, contextName, + pduType) = (execCtx['securityModel'], execCtx['securityName'], + execCtx['securityLevel'], execCtx['contextName'], + execCtx['pdu'].getTagSet()) try: snmpEngine.accessControlModel[self.acmID].isAccessAllowed( snmpEngine, securityModel, securityName, securityLevel, viewType, contextName, name - ) + ) # Map ACM errors onto SMI ones except error.StatusInformation: statusInformation = sys.exc_info()[1] @@ -236,69 +195,55 @@ class CommandResponderBase: if errorIndication == errind.noSuchView or \ errorIndication == errind.noAccessEntry or \ errorIndication == errind.noGroupName: - raise pysnmp.smi.error.AuthorizationError( - name=name, idx=idx - ) + 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.syntax = snmpUnknownContexts.syntax + 1 + snmpUnknownContexts.syntax += 1 # Request REPORT generation - raise pysnmp.smi.error.GenError( - name=name, idx=idx, - oid=snmpUnknownContexts.name, - val=snmpUnknownContexts.syntax - ) + raise pysnmp.smi.error.GenError(name=name, idx=idx, + oid=snmpUnknownContexts.name, + val=snmpUnknownContexts.syntax) elif errorIndication == errind.notInView: return 1 else: - raise error.ProtocolError( - 'Unknown ACM error %s' % errorIndication - ) + raise error.ProtocolError('Unknown ACM error %s' % errorIndication) else: # rfc2576: 4.1.2.1 - if securityModel == 1 and \ - syntax is not None and \ - self._counter64Type == syntax.getTagSet() and \ - self._getNextRequestType == pduType: + if securityModel == 1 and syntax is not None and \ + 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, ) + pduTypes = (rfc1905.GetRequestPDU.tagSet,) # rfc1905: 4.2.1 - def handleMgmtOperation( - self, snmpEngine, stateReference, contextName, PDU, acInfo - ): + def handleMgmtOperation(self, snmpEngine, stateReference, + contextName, PDU, acInfo): (acFun, acCtx) = acInfo # rfc1905: 4.2.1.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readVars - self.sendVarBinds( - snmpEngine, stateReference, 0, 0, mgmtFun( - v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) - ) - ) + self.sendVarBinds(snmpEngine, stateReference, 0, 0, + mgmtFun(v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx))) self.releaseStateInformation(stateReference) class NextCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.GetNextRequestPDU.tagSet, ) + pduTypes = (rfc1905.GetNextRequestPDU.tagSet,) # rfc1905: 4.2.2 - def handleMgmtOperation( - self, snmpEngine, stateReference, contextName, PDU, acInfo - ): + def handleMgmtOperation(self, snmpEngine, stateReference, + contextName, PDU, acInfo): (acFun, acCtx) = acInfo # rfc1905: 4.2.2.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars varBinds = v2c.apiPDU.getVarBinds(PDU) - while 1: + while True: rspVarBinds = mgmtFun(varBinds, (acFun, acCtx)) try: - self.sendVarBinds( - snmpEngine, stateReference, 0, 0, rspVarBinds - ) + self.sendVarBinds(snmpEngine, stateReference, 0, 0, rspVarBinds) except error.StatusInformation: idx = sys.exc_info()[1]['idx'] varBinds[idx] = (rspVarBinds[idx][0], varBinds[idx][1]) @@ -307,13 +252,12 @@ class NextCommandResponder(CommandResponderBase): self.releaseStateInformation(stateReference) class BulkCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.GetBulkRequestPDU.tagSet, ) + pduTypes = (rfc1905.GetBulkRequestPDU.tagSet,) maxVarBinds = 64 # rfc1905: 4.2.3 - def handleMgmtOperation( - self, snmpEngine, stateReference, contextName, PDU, acInfo - ): + def handleMgmtOperation(self, snmpEngine, stateReference, + contextName, PDU, acInfo): (acFun, acCtx) = acInfo nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU) if nonRepeaters < 0: @@ -342,39 +286,32 @@ class BulkCommandResponder(CommandResponderBase): varBinds = reqVarBinds[-R:] while M and R: - rspVarBinds.extend( - mgmtFun(varBinds, (acFun, acCtx)) - ) + rspVarBinds.extend(mgmtFun(varBinds, (acFun, acCtx))) varBinds = rspVarBinds[-R:] M = M - 1 if len(rspVarBinds): - self.sendVarBinds( - snmpEngine, stateReference, 0, 0, rspVarBinds - ) + self.sendVarBinds(snmpEngine, stateReference, 0, 0, rspVarBinds) self.releaseStateInformation(stateReference) else: raise pysnmp.smi.error.SmiError() class SetCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.SetRequestPDU.tagSet, ) + pduTypes = (rfc1905.SetRequestPDU.tagSet,) # rfc1905: 4.2.5 - def handleMgmtOperation( - self, snmpEngine, stateReference, contextName, PDU, acInfo - ): + def handleMgmtOperation(self, snmpEngine, stateReference, + contextName, PDU, acInfo): (acFun, acCtx) = acInfo mgmtFun = self.snmpContext.getMibInstrum(contextName).writeVars # rfc1905: 4.2.5.1-13 try: - self.sendVarBinds( - snmpEngine, stateReference, 0, 0, mgmtFun( - v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) - ) - ) + self.sendVarBinds(snmpEngine, stateReference, 0, 0, + mgmtFun(v2c.apiPDU.getVarBinds(PDU), + (acFun, acCtx))) self.releaseStateInformation(stateReference) - except ( pysnmp.smi.error.NoSuchObjectError, - pysnmp.smi.error.NoSuchInstanceError ): + except (pysnmp.smi.error.NoSuchObjectError, + pysnmp.smi.error.NoSuchInstanceError): e = pysnmp.smi.error.NotWritableError() e.update(sys.exc_info()[1]) raise e diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py index 61a0580c..8add3901 100644 --- a/pysnmp/entity/rfc3413/config.py +++ b/pysnmp/entity/rfc3413/config.py @@ -20,22 +20,16 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): nameToTargetMap = cache['nameToTargetMap'] if snmpTargetAddrName not in nameToTargetMap: - ( snmpTargetAddrTDomain, - snmpTargetAddrTAddress, - snmpTargetAddrTimeout, - snmpTargetAddrRetryCount, - snmpTargetAddrParams ) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', - 'snmpTargetAddrTDomain', - 'snmpTargetAddrTAddress', - 'snmpTargetAddrTimeout', - 'snmpTargetAddrRetryCount', - 'snmpTargetAddrParams' - ) - ( snmpSourceAddrTAddress, ) = mibBuilder.importSymbols( - 'PYSNMP-SOURCE-MIB', - 'snmpSourceAddrTAddress' - ) + (snmpTargetAddrTDomain, + snmpTargetAddrTAddress, + snmpTargetAddrTimeout, + snmpTargetAddrRetryCount, + snmpTargetAddrParams) = mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', + 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', + 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' + ) + snmpSourceAddrTAddress, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(snmpTargetAddrName) @@ -47,7 +41,7 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): snmpTargetAddrTAddress.name + tblIdx ).syntax snmpTargetAddrTimeout = snmpTargetAddrTimeout.getNode( - snmpTargetAddrTimeout.name + tblIdx + snmpTargetAddrTimeout.name + tblIdx ).syntax snmpTargetAddrRetryCount = snmpTargetAddrRetryCount.getNode( snmpTargetAddrRetryCount.name + tblIdx @@ -109,16 +103,13 @@ def getTargetParams(snmpEngine, paramsName): nameToParamsMap = cache['nameToParamsMap'] if paramsName not in nameToParamsMap: - ( snmpTargetParamsMPModel, - snmpTargetParamsSecurityModel, - snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel ) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', - 'snmpTargetParamsMPModel', - 'snmpTargetParamsSecurityModel', - 'snmpTargetParamsSecurityName', - 'snmpTargetParamsSecurityLevel' - ) + (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, + snmpTargetParamsSecurityName, + snmpTargetParamsSecurityLevel) = mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel', + 'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName', + 'snmpTargetParamsSecurityLevel' + ) tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(paramsName) @@ -138,12 +129,10 @@ def getTargetParams(snmpEngine, paramsName): except NoSuchInstanceError: raise SmiError('Parameters %s not configured at LCD' % paramsName) - nameToParamsMap[paramsName] = ( - snmpTargetParamsMPModel, - snmpTargetParamsSecurityModel, - snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel - ) + nameToParamsMap[paramsName] = (snmpTargetParamsMPModel, + snmpTargetParamsSecurityModel, + snmpTargetParamsSecurityName, + snmpTargetParamsSecurityLevel) cache['id'] = snmpTargetParamsEntry.branchVersionId @@ -151,36 +140,32 @@ def getTargetParams(snmpEngine, paramsName): def getTargetInfo(snmpEngine, snmpTargetAddrName): # Transport endpoint - ( snmpTargetAddrTDomain, - snmpTargetAddrTAddress, - snmpTargetAddrTimeout, - snmpTargetAddrRetryCount, - snmpTargetAddrParams ) = getTargetAddr(snmpEngine, snmpTargetAddrName) - - ( snmpTargetParamsMPModel, - snmpTargetParamsSecurityModel, - snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel ) = getTargetParams(snmpEngine, snmpTargetAddrParams) - - return ( snmpTargetAddrTDomain, - snmpTargetAddrTAddress, - snmpTargetAddrTimeout, - snmpTargetAddrRetryCount, - snmpTargetParamsMPModel, - snmpTargetParamsSecurityModel, - snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel ) + (snmpTargetAddrTDomain, + snmpTargetAddrTAddress, + snmpTargetAddrTimeout, + snmpTargetAddrRetryCount, + snmpTargetAddrParams) = getTargetAddr(snmpEngine, snmpTargetAddrName) + + (snmpTargetParamsMPModel, + snmpTargetParamsSecurityModel, + snmpTargetParamsSecurityName, + snmpTargetParamsSecurityLevel) = getTargetParams(snmpEngine, + snmpTargetAddrParams) + + return (snmpTargetAddrTDomain, snmpTargetAddrTAddress, + snmpTargetAddrTimeout, snmpTargetAddrRetryCount, + snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, + snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) def getNotificationInfo(snmpEngine, notificationTarget): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpNotifyEntry, = mibBuilder.importSymbols( - 'SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry' - ) + snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', + 'snmpNotifyEntry') cache = snmpEngine.getUserContext('getNotificationInfo') if cache is None: - cache = { 'id': -1 } + cache = {'id': -1} snmpEngine.setUserContext(getNotificationInfo=cache) if cache['id'] != snmpNotifyEntry.branchVersionId: @@ -189,12 +174,10 @@ def getNotificationInfo(snmpEngine, notificationTarget): targetToNotifyMap = cache['targetToNotifyMap'] if notificationTarget not in targetToNotifyMap: - ( snmpNotifyTag, - snmpNotifyType ) = mibBuilder.importSymbols( - 'SNMP-NOTIFICATION-MIB', - 'snmpNotifyTag', - 'snmpNotifyType' - ) + (snmpNotifyTag, + snmpNotifyType) = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', + 'snmpNotifyTag', + 'snmpNotifyType') tblIdx = snmpNotifyEntry.getInstIdFromIndices(notificationTarget) @@ -221,13 +204,12 @@ def getNotificationInfo(snmpEngine, notificationTarget): def getTargetNames(snmpEngine, tag): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpTargetAddrEntry, = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry' - ) + snmpTargetAddrEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', + 'snmpTargetAddrEntry') cache = snmpEngine.getUserContext('getTargetNames') if cache is None: - cache = { 'id': -1 } + cache = {'id': -1} snmpEngine.setUserContext(getTargetNames=cache) if cache['id'] == snmpTargetAddrEntry.branchVersionId: @@ -237,17 +219,14 @@ def getTargetNames(snmpEngine, tag): tagToTargetsMap = cache['tagToTargetsMap'] - ( SnmpTagValue, - snmpTargetAddrName, - snmpTargetAddrTagList ) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', - 'SnmpTagValue', - 'snmpTargetAddrName', - 'snmpTargetAddrTagList' - ) + (SnmpTagValue, snmpTargetAddrName, + snmpTargetAddrTagList) = mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', + 'snmpTargetAddrTagList' + ) targetNames = [] mibNode = snmpTargetAddrTagList - while 1: + while True: try: mibNode = snmpTargetAddrTagList.getNextNode(mibNode.name) except NoSuchInstanceError: diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py index 998c62df..42274069 100644 --- a/pysnmp/entity/rfc3413/ntforg.py +++ b/pysnmp/entity/rfc3413/ntforg.py @@ -18,37 +18,21 @@ class NotificationOriginator: self.__pendingNotifications = {} self.snmpContext = snmpContext # this is deprecated - def processResponsePdu(self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - statusInformation, - sendPduHandle, - cbInfo): + def processResponsePdu(self, snmpEngine, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, + PDU, statusInformation, sendPduHandle, cbInfo): sendRequestHandle, cbFun, cbCtx = cbInfo # 3.3.6d if sendPduHandle not in self.__pendingReqs: raise error.ProtocolError('Missing sendPduHandle %s' % sendPduHandle) - ( origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPdu, - origTimeout, - origRetryCount, - origRetries ) = self.__pendingReqs.pop(sendPduHandle) + (origTransportDomain, origTransportAddress, + origMessageProcessingModel, origSecurityModel, + origSecurityName, origSecurityLevel, origContextEngineId, + origContextName, origPdu, origTimeout, + origRetryCount, origRetries) = self.__pendingReqs.pop(sendPduHandle) snmpEngine.transportDispatcher.jobFinished(id(self)) @@ -56,11 +40,8 @@ class NotificationOriginator: 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)) - cbFun(snmpEngine, - sendRequestHandle, - statusInformation['errorIndication'], - None, - cbCtx) + cbFun(snmpEngine, sendRequestHandle, + statusInformation['errorIndication'], None, cbCtx) return # Convert timeout in seconds into timeout in timer ticks @@ -77,30 +58,18 @@ class NotificationOriginator: # 3.3.6a try: sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( - snmpEngine, - origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - pduVersion, - reqPDU, - 1, # expectResponse - timeoutInTicks, - self.processResponsePdu, + snmpEngine, origTransportDomain, origTransportAddress, + origMessageProcessingModel, origSecurityModel, + origSecurityName, origSecurityLevel, + origContextEngineId, origContextName, pduVersion, + reqPDU, True, timeoutInTicks, self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % (sendRequestHandle, statusInformation)) - cbFun(snmpEngine, - sendRequestHandle, - statusInformation['errorIndication'], - None, - cbCtx) + cbFun(snmpEngine, sendRequestHandle, + statusInformation['errorIndication'], None, cbCtx) return snmpEngine.transportDispatcher.jobStarted(id(self)) @@ -109,18 +78,11 @@ class NotificationOriginator: # 3.3.6b self.__pendingReqs[sendPduHandle] = ( - origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPdu, - origTimeout, - origRetryCount, - origRetries + 1 + origTransportDomain, origTransportAddress, + origMessageProcessingModel, origSecurityModel, + origSecurityName, origSecurityLevel, + origContextEngineId, origContextName, origPdu, + origTimeout, origRetryCount, origRetries + 1 ) return @@ -131,24 +93,13 @@ class NotificationOriginator: cbFun(snmpEngine, sendRequestHandle, None, PDU, cbCtx) - def sendPdu(self, - snmpEngine, - targetName, - contextEngineId, - contextName, - pdu, - cbFun=None, - cbCtx=None): - ( transportDomain, - transportAddress, - timeout, - retryCount, - params ) = config.getTargetAddr(snmpEngine, targetName) - - ( messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetParams(snmpEngine, params) + def sendPdu(self, snmpEngine, targetName, contextEngineId, + contextName, pdu, cbFun=None, cbCtx=None): + (transportDomain, transportAddress, timeout, + retryCount, params) = config.getTargetAddr(snmpEngine, targetName) + + (messageProcessingModel, securityModel, securityName, + securityLevel) = config.getTargetParams(snmpEngine, params) # User-side API assumes SMIv2 if messageProcessingModel == 0: @@ -167,55 +118,29 @@ class NotificationOriginator: # 3.3.6a sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - # expectResponse - 1, - timeoutInTicks, - self.processResponsePdu, - (sendRequestHandle, cbFun, cbCtx) + snmpEngine, transportDomain, transportAddress, + messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, reqPDU, True, timeoutInTicks, + self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) debug.logger & debug.flagApp and debug.logger('sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pdu, - timeout, - retryCount, - 1 + transportDomain, transportAddress, messageProcessingModel, + securityModel, securityName, securityLevel, contextEngineId, + contextName, pdu, timeout, retryCount, True ) snmpEngine.transportDispatcher.jobStarted(id(self)) else: - snmpEngine.msgAndPduDsp.sendPdu(snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - None) # do not expectResponse + snmpEngine.msgAndPduDsp.sendPdu( + snmpEngine, transportDomain, transportAddress, + messageProcessingModel, securityModel, + securityName, securityLevel, contextEngineId, + contextName, pduVersion, reqPDU, False + ) sendRequestHandle = None @@ -223,12 +148,8 @@ class NotificationOriginator: return sendRequestHandle - def processResponseVarBinds(self, - snmpEngine, - sendRequestHandle, - errorIndication, - pdu, - cbCtx): + def processResponseVarBinds(self, snmpEngine, sendRequestHandle, + errorIndication, pdu, cbCtx): notificationHandle, cbFun, cbCtx = cbCtx self.__pendingNotifications[notificationHandle].remove(sendRequestHandle) @@ -238,9 +159,7 @@ class NotificationOriginator: if not self.__pendingNotifications[notificationHandle]: debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % (notificationHandle, sendRequestHandle)) del self.__pendingNotifications[notificationHandle] - cbFun(snmpEngine, - sendRequestHandle, - errorIndication, + cbFun(snmpEngine, sendRequestHandle, errorIndication, pdu and v2c.apiPDU.getErrorStatus(pdu) or 0, pdu and v2c.apiPDU.getErrorIndex(pdu, muteErrors=True) or 0, pdu and v2c.apiPDU.getVarBinds(pdu) or (), @@ -250,14 +169,8 @@ class NotificationOriginator: # Higher-level API to Notification Originator. Supports multiple # targets, automatic var-binding formation and is fully LCD-driven. # - def sendVarBinds(self, - snmpEngine, - notificationTarget, - contextEngineId, - contextName, - varBinds=(), - cbFun=None, - cbCtx=None): + 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 '<default>', contextName, varBinds)) if contextName: @@ -265,16 +178,13 @@ class NotificationOriginator: contextName = __SnmpAdminString(contextName) # 3.3 - ( notifyTag, - notifyType ) = config.getNotificationInfo( - snmpEngine, notificationTarget - ) + (notifyTag, notifyType) = config.getNotificationInfo(snmpEngine, notificationTarget) notificationHandle = getNextHandle() 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 ] + 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') @@ -298,23 +208,18 @@ class NotificationOriginator: debug.logger & debug.flagApp and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,)) for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): - ( transportDomain, - transportAddress, - timeout, - retryCount, - params ) = config.getTargetAddr(snmpEngine, targetAddrName) - ( messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetParams(snmpEngine, params) + (transportDomain, transportAddress, timeout, + retryCount, params) = config.getTargetAddr(snmpEngine, + targetAddrName) + (messageProcessingModel, securityModel, securityName, + securityLevel) = config.getTargetParams(snmpEngine, params) # 3.3.1 XXX # 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)) @@ -325,7 +230,7 @@ class NotificationOriginator: snmpEngine.accessControlModel[self.acmID].isAccessAllowed( snmpEngine, securityModel, securityName, securityLevel, 'notify', contextName, varName - ) + ) debug.logger & debug.flagApp and debug.logger('sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) @@ -346,14 +251,11 @@ class NotificationOriginator: # 3.3.5 try: - sendRequestHandle = self.sendPdu(snmpEngine, - targetAddrName, - contextEngineId, - contextName, - pdu, - self.processResponseVarBinds, - (notificationHandle, - cbFun, cbCtx)) + sendRequestHandle = self.sendPdu( + snmpEngine, targetAddrName, contextEngineId, + contextName, pdu, self.processResponseVarBinds, + (notificationHandle, cbFun, cbCtx) + ) except error.StatusInformation: statusInformation = sys.exc_info()[1] @@ -362,10 +264,9 @@ class NotificationOriginator: not self.__pendingNotifications[notificationHandle]: if notificationHandle in self.__pendingNotifications: del self.__pendingNotifications[notificationHandle] - cbFun(snmpEngine, - notificationHandle, - statusInformation['errorIndication'], - 0, 0, (), cbCtx) + cbFun(snmpEngine, notificationHandle, + statusInformation['errorIndication'], 0, 0, (), + cbCtx) return notificationHandle debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % (notificationHandle, sendRequestHandle, timeout)) @@ -383,13 +284,8 @@ class NotificationOriginator: # Obsolete, compatibility interfaces. # -def _sendNotificationCbFun(snmpEngine, - sendRequestHandle, - errorIndication, - errorStatus, - errorIndex, - varBinds, - cbCtx): +def _sendNotificationCbFun(snmpEngine, sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBinds, cbCtx): cbFun, cbCtx = cbCtx try: @@ -400,15 +296,9 @@ def _sendNotificationCbFun(snmpEngine, # 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): +def _sendNotification(self, snmpEngine, notificationTarget, notificationName, + additionalVarBinds=(), cbFun=None, cbCtx=None, + contextName=null, instanceIndex=None): if self.snmpContext is None: raise error.ProtocolError('SNMP context not specified') @@ -432,25 +322,21 @@ def _sendNotification(self, else: notificationName = rfc1902.ObjectIdentity(notificationName) - varBinds = rfc1902.NotificationType( - notificationName, instanceIndex=instanceIndex - ).resolveWithMib(mibViewController) + varBinds = rfc1902.NotificationType(notificationName, + instanceIndex=instanceIndex) + varBinds.resolveWithMib(mibViewController) mibInstrumController = self.snmpContext.getMibInstrum(contextName) varBinds = varBinds[:1] + mibInstrumController.readVars(varBinds[1:]) - return self.sendVarBinds(snmpEngine, - notificationTarget, + return self.sendVarBinds(snmpEngine, notificationTarget, self.snmpContext.contextEngineId, - contextName, - varBinds + list(additionalVarBinds), - _sendNotificationCbFun, - (cbFun, cbCtx)) + contextName, varBinds + list(additionalVarBinds), + _sendNotificationCbFun, (cbFun, cbCtx)) # install compatibility wrapper NotificationOriginator.sendNotification = _sendNotification # XXX # move/group/implement config setting/retrieval at a stand-alone module - diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py index 0d3675aa..e78c512a 100644 --- a/pysnmp/entity/rfc3413/ntfrcv.py +++ b/pysnmp/entity/rfc3413/ntfrcv.py @@ -7,11 +7,8 @@ from pysnmp import debug # 3.4 class NotificationReceiver: - pduTypes = ( - v1.TrapPDU.tagSet, - v2c.SNMPv2TrapPDU.tagSet, - v2c.InformRequestPDU.tagSet - ) + pduTypes = (v1.TrapPDU.tagSet, v2c.SNMPv2TrapPDU.tagSet, + v2c.InformRequestPDU.tagSet) def __init__(self, snmpEngine, cbFun, cbCtx=None): snmpEngine.msgAndPduDsp.registerContextEngineId( @@ -27,20 +24,10 @@ class NotificationReceiver: ) self.__cbFun = self.__cbCtx = None - def processPdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference - ): + def processPdu(self, snmpEngine, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, PDU, + maxSizeResponseScopedPDU, stateReference): # Agent-side API complies with SMIv2 if messageProcessingModel == 0: @@ -77,19 +64,11 @@ class NotificationReceiver: # 3.4.3 try: snmpEngine.msgAndPduDsp.returnResponsePdu( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - rspPDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) + snmpEngine, messageProcessingModel, securityModel, + securityName, securityLevel, contextEngineId, + contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU, + 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') @@ -103,20 +82,14 @@ class NotificationReceiver: 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, contextName, - varBinds, self.__cbCtx - ) + self.__cbFun(snmpEngine, stateReference, contextEngineId, + contextName, varBinds, self.__cbCtx) else: # Compatibility stub (handle legacy cbFun interface) try: - self.__cbFun( - snmpEngine, contextEngineId, contextName, - varBinds, self.__cbCtx - ) + self.__cbFun(snmpEngine, contextEngineId, contextName, + varBinds, self.__cbCtx) except TypeError: self.__cbFunVer = 1 - self.__cbFun( - snmpEngine, stateReference, contextEngineId, contextName, - varBinds, self.__cbCtx - ) + self.__cbFun(snmpEngine, stateReference, contextEngineId, + contextName, varBinds, self.__cbCtx) diff --git a/pysnmp/hlapi/asyncio/cmdgen.py b/pysnmp/hlapi/asyncio/cmdgen.py index 71b0db1c..edee7a93 100644 --- a/pysnmp/hlapi/asyncio/cmdgen.py +++ b/pysnmp/hlapi/asyncio/cmdgen.py @@ -253,7 +253,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, @asyncio.coroutine def nextCmd(snmpEngine, authData, transportTarget, contextData, - *varBinds, **options): + *varBinds, **options): """Creates a generator to perform SNMP GETNEXT query. When itereator gets advanced by :py:mod:`asyncio` main loop, diff --git a/pysnmp/hlapi/asyncore/sync/cmdgen.py b/pysnmp/hlapi/asyncore/sync/cmdgen.py index 6d5497db..df131526 100644 --- a/pysnmp/hlapi/asyncore/sync/cmdgen.py +++ b/pysnmp/hlapi/asyncore/sync/cmdgen.py @@ -382,7 +382,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, errorIndication = errorStatus = errorIndex = None varBinds = [] - initialVarBinds = ( yield errorIndication, errorStatus, + initialVarBinds = ( yield errorIndication, errorStatus,\ errorIndex, varBinds ) if initialVarBinds: @@ -596,7 +596,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, stopFlag = True for varBinds in varBindTable: - initialVarBinds = ( yield errorIndication, errorStatus, + initialVarBinds = ( yield errorIndication, errorStatus,\ errorIndex, varBinds ) if initialVarBinds: diff --git a/pysnmp/hlapi/twisted/cmdgen.py b/pysnmp/hlapi/twisted/cmdgen.py index 4a8d1f11..b7265d93 100644 --- a/pysnmp/hlapi/twisted/cmdgen.py +++ b/pysnmp/hlapi/twisted/cmdgen.py @@ -248,7 +248,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, return deferred def nextCmd(snmpEngine, authData, transportTarget, contextData, - *varBinds, **options): + *varBinds, **options): """Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet diff --git a/pysnmp/proto/mpmod/cache.py b/pysnmp/proto/mpmod/cache.py index 08988379..bad7788e 100644 --- a/pysnmp/proto/mpmod/cache.py +++ b/pysnmp/proto/mpmod/cache.py @@ -19,12 +19,9 @@ class Cache: def pushByStateRef(self, stateReference, **msgInfo): if stateReference in self.__stateReferenceIndex: - raise error.ProtocolError( - 'Cache dup for stateReference=%s at %s' % - (stateReference, self) - ) + raise error.ProtocolError('Cache dup for stateReference=%s at %s' % (stateReference, self)) expireAt = self.__expirationTimer+600 - self.__stateReferenceIndex[stateReference] = ( msgInfo, expireAt ) + self.__stateReferenceIndex[stateReference] = msgInfo, expireAt # Schedule to expire if expireAt not in self.__expirationQueue: @@ -37,10 +34,7 @@ class Cache: if stateReference in self.__stateReferenceIndex: cacheInfo = self.__stateReferenceIndex[stateReference] else: - raise error.ProtocolError( - 'Cache miss for stateReference=%s at %s' % - (stateReference, self) - ) + raise error.ProtocolError('Cache miss for stateReference=%s at %s' % (stateReference, self)) del self.__stateReferenceIndex[stateReference] cacheEntry, expireAt = cacheInfo del self.__expirationQueue[expireAt]['stateReference'][stateReference] @@ -55,9 +49,9 @@ class Cache: if msgId in self.__msgIdIndex: raise error.ProtocolError( 'Cache dup for msgId=%s at %s' % (msgId, self) - ) + ) expireAt = self.__expirationTimer+600 - self.__msgIdIndex[msgId] = ( msgInfo, expireAt ) + self.__msgIdIndex[msgId] = msgInfo, expireAt self.__sendPduHandleIdx[msgInfo['sendPduHandle']] = msgId @@ -74,7 +68,7 @@ class Cache: else: raise error.ProtocolError( 'Cache miss for msgId=%s at %s' % (msgId, self) - ) + ) msgInfo, expireAt = cacheInfo del self.__sendPduHandleIdx[msgInfo['sendPduHandle']] del self.__msgIdIndex[msgId] @@ -97,4 +91,4 @@ class Cache: for msgId in cacheInfo['msgId']: del self.__msgIdIndex[msgId] del self.__expirationQueue[self.__expirationTimer] - self.__expirationTimer = self.__expirationTimer + 1 + self.__expirationTimer += 1 diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py index 94b61faf..8e2b502a 100644 --- a/pysnmp/proto/mpmod/rfc2576.py +++ b/pysnmp/proto/mpmod/rfc2576.py @@ -17,22 +17,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): messageProcessingModelID = univ.Integer(0) # SNMPv1 snmpMsgSpec = v1.Message # rfc3412: 7.1 - def prepareOutgoingMessage( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - expectResponse, - sendPduHandle - ): + def prepareOutgoingMessage(self, snmpEngine, transportDomain, + transportAddress, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, + pdu, expectResponse, sendPduHandle): snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineId = snmpEngineId.syntax @@ -57,25 +46,25 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) # rfc3412: 7.1.6 - scopedPDU = ( contextEngineId, contextName, pdu ) + scopedPDU = (contextEngineId, contextName, pdu) msg = self._snmpMsgSpec msg.setComponentByPosition(0, self.messageProcessingModelID) msg.setComponentByPosition(2) msg.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False - ) + ) # rfc3412: 7.1.7 - globalData = ( msg, ) + globalData = (msg,) k = int(securityModel) if k in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[k] else: raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityModel - ) + errorIndication=errind.unsupportedSecurityModel + ) # rfc3412: 7.1.9.a & rfc2576: 5.2.1 --> no-op @@ -86,17 +75,12 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): pdu.setComponentByPosition(0, msgID) # rfc3412: 7.1.9.b - ( securityParameters, wholeMsg ) = smHandler.generateRequestMsg( - snmpEngine, - self.messageProcessingModelID, - globalData, - snmpEngineMaxMessageSize.syntax, - securityModel, - snmpEngineId, - securityName, - securityLevel, - scopedPDU - ) + (securityParameters, + wholeMsg) = smHandler.generateRequestMsg( + snmpEngine, self.messageProcessingModelID, globalData, + snmpEngineMaxMessageSize.syntax, securityModel, + snmpEngineId, securityName, securityLevel, scopedPDU + ) # return original request-id right after PDU serialization if pdu.tagSet in rfc3411.confirmedClassPDUs: @@ -105,25 +89,20 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc3412: 7.1.9.c if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX rfc bug? why stateReference should be created? - self._cache.pushByMsgId( - int(msgID), - sendPduHandle=sendPduHandle, - reqID=reqID, - snmpEngineId=snmpEngineId, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - contextEngineId=contextEngineId, - contextName=contextName, - transportDomain=transportDomain, - transportAddress=transportAddress - ) + self._cache.pushByMsgId(int(msgID), sendPduHandle=sendPduHandle, + reqID=reqID, snmpEngineId=snmpEngineId, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + transportDomain=transportDomain, + transportAddress=transportAddress) communityName = msg.getComponentByPosition(1) # for observer snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc2576.prepareOutgoingMessage', + snmpEngine, 'rfc2576.prepareOutgoingMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, wholeMsg=wholeMsg, @@ -139,32 +118,21 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): snmpEngine, 'rfc2576.prepareOutgoingMessage' ) - return ( transportDomain, transportAddress, wholeMsg ) + return transportDomain, transportAddress, wholeMsg # rfc3412: 7.1 - def prepareResponseMessage( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ): + def prepareResponseMessage(self, snmpEngine, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, + pdu, maxSizeResponseScopedPDU, stateReference, + statusInformation): snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineId = snmpEngineId.syntax # rfc3412: 7.1.2.b if stateReference is None: - raise error.StatusInformation( - errorIndication = errind.nonReportable - ) + raise error.StatusInformation(errorIndication=errind.nonReportable) + cachedParams = self._cache.popByStateRef(stateReference) msgID = cachedParams['msgID'] reqID = cachedParams['reqID'] @@ -185,9 +153,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc3412: 7.1.3a (N/A) # rfc3412: 7.1.3b (always discard) - raise error.StatusInformation( - errorIndication = errind.nonReportable - ) + raise error.StatusInformation(errorIndication=errind.nonReportable) # rfc3412: 7.1.4 # Since there's no SNMP engine identification in v1/2c, @@ -200,7 +166,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): contextName = null # rfc3412: 7.1.6 - scopedPDU = ( contextEngineId, contextName, pdu ) + scopedPDU = (contextEngineId, contextName, pdu) debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) @@ -209,45 +175,36 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): msg.setComponentByPosition(2) msg.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False - ) + ) # att: msgId not set back to PDU as it's up to responder app # rfc3412: 7.1.7 - globalData = ( msg, ) + globalData = (msg,) k = int(securityModel) if k in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[k] else: raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityModel - ) + errorIndication=errind.unsupportedSecurityModel + ) # set original request-id right prior to PDU serialization pdu.setComponentByPosition(0, reqID) # rfc3412: 7.1.8.a - ( securityParameters, - wholeMsg ) = smHandler.generateResponseMsg( - snmpEngine, - self.messageProcessingModelID, - globalData, - maxMessageSize, - securityModel, - snmpEngineId, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ) + (securityParameters, wholeMsg) = smHandler.generateResponseMsg( + snmpEngine, self.messageProcessingModelID, globalData, + maxMessageSize, securityModel, snmpEngineId, securityName, + securityLevel, scopedPDU, securityStateReference + ) # recover unique request-id right after PDU serialization pdu.setComponentByPosition(0, msgID) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc2576.prepareResponseMessage', + snmpEngine, 'rfc2576.prepareResponseMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -263,36 +220,26 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): snmpEngine, 'rfc2576.prepareResponseMessage' ) - return ( transportDomain, transportAddress, wholeMsg ) + return transportDomain, transportAddress, wholeMsg # rfc3412: 7.2.1 - def prepareDataElements( - self, - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ): + def prepareDataElements(self, snmpEngine, transportDomain, + transportAddress, wholeMsg): # rfc3412: 7.2.2 try: - msg, restOfwholeMsg = decoder.decode( - wholeMsg, asn1Spec=self._snmpMsgSpec - ) + msg, restOfwholeMsg = decoder.decode(wholeMsg, + asn1Spec=self._snmpMsgSpec) except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 - raise error.StatusInformation( - errorIndication = errind.parseError - ) + raise error.StatusInformation(errorIndication=errind.parseError) debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) if eoo.endOfOctets.isSameTypeWith(msg): - raise error.StatusInformation( - errorIndication=errind.parseError - ) + raise error.StatusInformation(errorIndication=errind.parseError) # rfc3412: 7.2.3 msgVersion = messageProcessingModel = msg.getComponentByPosition(0) @@ -300,11 +247,9 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc2576: 5.2.1 snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') communityName = msg.getComponentByPosition(1) - securityParameters = ( - communityName, - # transportDomain identifies local enpoint - (transportDomain, transportAddress) - ) + # transportDomain identifies local enpoint + securityParameters = (communityName, + (transportDomain, transportAddress)) messageProcessingModel = int(msg.getComponentByPosition(0)) securityModel = messageProcessingModel + 1 securityLevel = 1 @@ -316,24 +261,16 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): smHandler = snmpEngine.securityModels[k] else: raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityModel - ) + errorIndication=errind.unsupportedSecurityModel + ) # rfc3412: 7.2.6 - ( securityEngineId, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) = smHandler.processIncomingMsg( - snmpEngine, - messageProcessingModel, - snmpEngineMaxMessageSize.syntax, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg - ) + (securityEngineId, securityName, scopedPDU, maxSizeResponseScopedPDU, + securityStateReference) = smHandler.processIncomingMsg( + snmpEngine, messageProcessingModel, + snmpEngineMaxMessageSize.syntax, securityParameters, + securityModel, securityLevel, wholeMsg, msg + ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM returned securityEngineId %r securityName %r' % (securityEngineId, securityName)) @@ -380,18 +317,17 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc3412: 7.2.12a -> noop # rfc3412: 7.2.12b if securityModel != cachedReqParams['securityModel'] or \ - securityName != cachedReqParams['securityName'] or \ - securityLevel != cachedReqParams['securityLevel'] or \ - contextEngineId != cachedReqParams['contextEngineId'] or \ - contextName != cachedReqParams['contextName']: + securityName != cachedReqParams['securityName'] or \ + securityLevel != cachedReqParams['securityLevel'] or \ + contextEngineId != cachedReqParams['contextEngineId'] or \ + contextName != cachedReqParams['contextName']: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation(errorIndication=errind.dataMismatch) stateReference = None snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc2576.prepareDataElements:response', + snmpEngine, 'rfc2576.prepareDataElements:response', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -411,19 +347,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): smHandler.releaseStateInformation(securityStateReference) # rfc3412: 7.2.12d - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) + return (messageProcessingModel, securityModel, + securityName, securityLevel, contextEngineId, + contextName, pduVersion, pdu, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, + stateReference) # rfc3412: 7.2.13 if pduType in rfc3411.confirmedClassPDUs: @@ -438,31 +366,25 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): if securityEngineId != snmpEngineId.syntax: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( - errorIndication = errind.engineIDMismatch + errorIndication=errind.engineIDMismatch ) # rfc3412: 7.2.13b stateReference = self._cache.newStateReference() self._cache.pushByStateRef( - stateReference, - msgVersion=messageProcessingModel, - msgID=msgID, - reqID=reqID, - contextEngineId=contextEngineId, - contextName=contextName, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, + stateReference, msgVersion=messageProcessingModel, + msgID=msgID, reqID=reqID, contextEngineId=contextEngineId, + contextName=contextName, securityModel=securityModel, + securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, msgMaxSize=snmpEngineMaxMessageSize.syntax, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress - ) + ) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc2576.prepareDataElements:confirmed', + snmpEngine, 'rfc2576.prepareDataElements:confirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -481,19 +403,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): debug.logger & debug.flagMP and debug.logger('prepareDataElements: cached by new stateReference %s' % stateReference) # rfc3412: 7.2.13c - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) + return (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, pdu, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, + stateReference) # rfc3412: 7.2.14 if pduType in rfc3411.unconfirmedClassPDUs: @@ -501,8 +415,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): stateReference = self._cache.newStateReference() snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc2576.prepareDataElements:unconfirmed', + snmpEngine, 'rfc2576.prepareDataElements:unconfirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -521,19 +434,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # This is not specified explicitly in RFC smHandler.releaseStateInformation(securityStateReference) - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) + return (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, pdu, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, + stateReference) smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation(errorIndication=errind.unsupportedPDUtype) diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py index 9671d4a9..a76458d2 100644 --- a/pysnmp/proto/mpmod/rfc3412.py +++ b/pysnmp/proto/mpmod/rfc3412.py @@ -35,11 +35,11 @@ class HeaderData(univ.Sequence): class SNMPv3Message(univ.Sequence): componentType = namedtype.NamedTypes( - namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), - namedtype.NamedType('msgGlobalData', HeaderData()), - namedtype.NamedType('msgSecurityParameters', univ.OctetString()), - namedtype.NamedType('msgData', ScopedPduData()) - ) + namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), + namedtype.NamedType('msgGlobalData', HeaderData()), + namedtype.NamedType('msgSecurityParameters', univ.OctetString()), + namedtype.NamedType('msgData', ScopedPduData()) + ) # XXX move somewhere? _snmpErrors = {(1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0): 'unsupportedSecLevel', @@ -76,22 +76,11 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): return None, None, None # 7.1.1a - def prepareOutgoingMessage( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - expectResponse, - sendPduHandle - ): + def prepareOutgoingMessage(self, snmpEngine, transportDomain, + transportAddress, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, + pdu, expectResponse, sendPduHandle): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineID = snmpEngineID.syntax @@ -132,7 +121,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): scopedPDU.setComponentByPosition(2) scopedPDU.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False - ) + ) # 7.1.7 msg = self._snmpMsgSpec @@ -140,7 +129,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.1.7a msg.setComponentByPosition( 0, self.messageProcessingModelID, verifyConstraints=False - ) + ) headerData = msg.setComponentByPosition(1).getComponentByPosition(1) # 7.1.7b @@ -152,7 +141,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # XXX need to coerce MIB value as it has incompatible constraints set headerData.setComponentByPosition( 1, snmpEngineMaxMessageSize.syntax, verifyConstraints=False - ) + ) # 7.1.7d msgFlags = 0 @@ -165,14 +154,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): else: raise error.ProtocolError( 'Unknown securityLevel %s' % securityLevel - ) + ) if pdu.tagSet in rfc3411.confirmedClassPDUs: msgFlags = msgFlags | 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False - ) + ) # 7.1.7e # XXX need to coerce MIB value as it has incompatible constraints set @@ -184,8 +173,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): smHandler = snmpEngine.securityModels[securityModel] else: raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityModel - ) + errorIndication=errind.unsupportedSecurityModel + ) # 7.1.9.a if pdu.tagSet in rfc3411.unconfirmedClassPDUs: @@ -198,12 +187,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # Clear possible auth&priv flags headerData.setComponentByPosition( 2, self._msgFlags[msgFlags & 0xfc], verifyConstraints=False - ) + ) # XXX scopedPDU = self.__scopedPDU scopedPDU.setComponentByPosition( 0, self._emptyStr, verifyConstraints=False - ) + ) scopedPDU.setComponentByPosition(1, contextName) scopedPDU.setComponentByPosition(2) @@ -221,18 +210,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % (securityModel, securityEngineId, securityName, securityLevel)) # 7.1.9.b - ( securityParameters, - wholeMsg ) = smHandler.generateRequestMsg( - snmpEngine, - self.messageProcessingModelID, - msg, - snmpEngineMaxMessageSize.syntax, - securityModel, - securityEngineId, - securityName, - securityLevel, - scopedPDU - ) + (securityParameters, + wholeMsg) = smHandler.generateRequestMsg( + snmpEngine, self.messageProcessingModelID, msg, + snmpEngineMaxMessageSize.syntax, securityModel, + securityEngineId, securityName, securityLevel, scopedPDU + ) # Message size constraint verification if len(wholeMsg) > snmpEngineMaxMessageSize.syntax: @@ -241,23 +224,18 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.1.9.c if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX rfc bug? why stateReference should be created? - self._cache.pushByMsgId( - msgID, - sendPduHandle=sendPduHandle, - msgID=msgID, - snmpEngineID=snmpEngineID, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - contextEngineId=contextEngineId, - contextName=contextName, - transportDomain=transportDomain, - transportAddress=transportAddress - ) + self._cache.pushByMsgId(msgID, sendPduHandle=sendPduHandle, + msgID=msgID, snmpEngineID=snmpEngineID, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + transportDomain=transportDomain, + transportAddress=transportAddress) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc3412.prepareOutgoingMessage', + snmpEngine, 'rfc3412.prepareOutgoingMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, wholeMsg=wholeMsg, @@ -272,25 +250,13 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): snmpEngine, 'rfc3412.prepareOutgoingMessage' ) - return ( transportDomain, - transportAddress, - wholeMsg ) - - def prepareResponseMessage( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - maxSizeResponseScopedPDU, # n.b. not actually used here - stateReference, - statusInformation - ): + return transportDomain, transportAddress, wholeMsg + + def prepareResponseMessage(self, snmpEngine, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, + pdu, maxSizeResponseScopedPDU, stateReference, + statusInformation): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineID = snmpEngineID.syntax @@ -324,15 +290,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): pduType is not None and \ pduType not in rfc3411.confirmedClassPDUs: raise error.StatusInformation( - errorIndication = errind.loopTerminated - ) + errorIndication=errind.loopTerminated + ) # 7.1.3c reportPDU = rfc1905.ReportPDU() - pMod.apiPDU.setVarBinds( - reportPDU, - ((statusInformation['oid'], statusInformation['val']),) - ) + pMod.apiPDU.setVarBinds(reportPDU, ((statusInformation['oid'], statusInformation['val']),)) pMod.apiPDU.setErrorStatus(reportPDU, 0) pMod.apiPDU.setErrorIndex(reportPDU, 0) if pdu is None: @@ -379,22 +342,19 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): scopedPDU.setComponentByPosition(2) scopedPDU.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False - ) + ) # 7.1.7 msg = self._snmpMsgSpec # 7.1.7a - msg.setComponentByPosition( - 0, self.messageProcessingModelID, verifyConstraints=False - ) + msg.setComponentByPosition(0, self.messageProcessingModelID, + verifyConstraints=False) headerData = msg.setComponentByPosition(1).getComponentByPosition(1) # 7.1.7b - headerData.setComponentByPosition( - 0, msgID, verifyConstraints=False - ) + headerData.setComponentByPosition(0, msgID, verifyConstraints=False) snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') @@ -413,48 +373,38 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): elif securityLevel == 3: msgFlags = msgFlags | 0x03 else: - raise error.ProtocolError( - 'Unknown securityLevel %s' % securityLevel - ) + raise error.ProtocolError('Unknown securityLevel %s' % securityLevel) if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed? msgFlags = msgFlags | 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False - ) + ) # 7.1.7e headerData.setComponentByPosition( 3, securityModel, verifyConstraints=False - ) + ) debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),)) if securityModel in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[securityModel] else: - raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityModel - ) + raise error.StatusInformation(errorIndication=errind.unsupportedSecurityModel) debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % (securityModel, snmpEngineID, securityName, securityLevel)) # 7.1.8a try: - ( securityParameters, - wholeMsg ) = smHandler.generateResponseMsg( - snmpEngine, - self.messageProcessingModelID, - msg, - snmpEngineMaxMessageSize.syntax, - securityModel, - snmpEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ) + (securityParameters, + wholeMsg) = smHandler.generateResponseMsg( + snmpEngine, self.messageProcessingModelID, msg, + snmpEngineMaxMessageSize.syntax, securityModel, + snmpEngineID, securityName, securityLevel, scopedPDU, + securityStateReference + ) except error.StatusInformation: # 7.1.8.b raise @@ -482,36 +432,26 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): snmpEngine, 'rfc3412.prepareResponseMessage' ) - return ( transportDomain, transportAddress, wholeMsg ) + return transportDomain, transportAddress, wholeMsg # 7.2.1 - def prepareDataElements( - self, - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ): + def prepareDataElements(self, snmpEngine, transportDomain, + transportAddress, wholeMsg): # 7.2.2 try: - msg, restOfwholeMsg = decoder.decode( - wholeMsg, asn1Spec=self._snmpMsgSpec - ) + msg, restOfwholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec) + except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 - raise error.StatusInformation( - errorIndication = errind.parseError - ) + raise error.StatusInformation(errorIndication=errind.parseError) debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) if eoo.endOfOctets.isSameTypeWith(msg): - raise error.StatusInformation( - errorIndication=errind.parseError - ) + raise error.StatusInformation(errorIndication=errind.parseError) # 7.2.3 headerData = msg.getComponentByPosition(1) @@ -528,9 +468,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if securityModel not in snmpEngine.securityModels: snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpUnknownSecurityModels') snmpUnknownSecurityModels.syntax = snmpUnknownSecurityModels.syntax + 1 - raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityModel - ) + raise error.StatusInformation(errorIndication=errind.unsupportedSecurityModel) # 7.2.5 if msgFlags & 0x03 == 0x00: @@ -542,9 +480,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): else: snmpInvalidMsgs = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInvalidMsgs') snmpInvalidMsgs.syntax = snmpInvalidMsgs.syntax + 1 - raise error.StatusInformation( - errorIndication = errind.invalidMsg - ) + raise error.StatusInformation(errorIndication=errind.invalidMsg) if msgFlags & 0x04: reportableFlag = 1 @@ -554,21 +490,15 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.2.6 smHandler = snmpEngine.securityModels[securityModel] try: - ( securityEngineId, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) = smHandler.processIncomingMsg( - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg - ) + (securityEngineId, securityName, + scopedPDU, maxSizeResponseScopedPDU, + securityStateReference) = smHandler.processIncomingMsg( + snmpEngine, messageProcessingModel, maxMessageSize, + securityParameters, securityModel, securityLevel, + wholeMsg, msg + ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded') + except error.StatusInformation: statusInformation, origTraceback = sys.exc_info()[1:3] debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM failed, statusInformation %s' % statusInformation) @@ -576,9 +506,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.2.6a if 'oid' in statusInformation: # 7.2.6a1 - securityStateReference = statusInformation[ - 'securityStateReference' - ] + securityStateReference = statusInformation['securityStateReference'] contextEngineId = statusInformation['contextEngineId'] contextName = statusInformation['contextName'] if 'scopedPDU' in statusInformation: @@ -586,46 +514,32 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): pdu = scopedPDU.getComponentByPosition(2).getComponent() else: pdu = None - maxSizeResponseScopedPDU = statusInformation[ - 'maxSizeResponseScopedPDU' - ] + maxSizeResponseScopedPDU = statusInformation['maxSizeResponseScopedPDU'] securityName = None # XXX secmod cache used # 7.2.6a2 stateReference = self._cache.newStateReference() self._cache.pushByStateRef( - stateReference, - msgVersion=messageProcessingModel, - msgID=msgID, - contextEngineId=contextEngineId, - contextName=contextName, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, + stateReference, msgVersion=messageProcessingModel, + msgID=msgID, contextEngineId=contextEngineId, + contextName=contextName, securityModel=securityModel, + securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, reportableFlag=reportableFlag, msgMaxSize=maxMessageSize, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress - ) + ) # 7.2.6a3 try: snmpEngine.msgAndPduDsp.returnResponsePdu( - snmpEngine, - 3, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - 1, - pdu, - maxSizeResponseScopedPDU, - stateReference, + snmpEngine, 3, securityModel, securityName, + securityLevel, contextEngineId, contextName, + 1, pdu, maxSizeResponseScopedPDU, stateReference, statusInformation - ) + ) except error.StatusInformation: pass @@ -684,8 +598,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): except error.ProtocolError: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( - errorIndication = errind.dataMismatch - ) + errorIndication=errind.dataMismatch + ) # 7.2.10b sendPduHandle = cachedReqParams['sendPduHandle'] else: @@ -699,19 +613,16 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): varBinds = pMod.apiPDU.getVarBinds(pdu) if varBinds: statusInformation = error.StatusInformation( - errorIndication=_snmpErrors.get( - varBinds[0][0], 'errorReportReceived' - ), - oid=varBinds[0][0], - val=varBinds[0][1], + errorIndication=_snmpErrors.get(varBinds[0][0], + 'errorReportReceived'), + oid=varBinds[0][0], val=varBinds[0][1], sendPduHandle=sendPduHandle - ) + ) # 7.2.11b (incomplete implementation) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc3412.prepareDataElements:internal', + snmpEngine, 'rfc3412.prepareDataElements:internal', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -749,12 +660,11 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): contextName != cachedReqParams['contextName']: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( - errorIndication = errind.dataMismatch - ) + errorIndication=errind.dataMismatch + ) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc3412.prepareDataElements:response', + snmpEngine, 'rfc3412.prepareDataElements:response', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -774,19 +684,11 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): stateReference = None # 7.2.12d - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) + return (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, pdu, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, + stateReference) # 7.2.13 if pduType in rfc3411.confirmedClassPDUs: @@ -794,23 +696,18 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if securityEngineId != snmpEngineID: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( - errorIndication = errind.engineIDMismatch - ) + errorIndication=errind.engineIDMismatch + ) # 7.2.13b stateReference = self._cache.newStateReference() self._cache.pushByStateRef( - stateReference, - msgVersion=messageProcessingModel, - msgID=msgID, - contextEngineId=contextEngineId, - contextName=contextName, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, + stateReference, msgVersion=messageProcessingModel, + msgID=msgID, contextEngineId=contextEngineId, + contextName=contextName, securityModel=securityModel, + securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, - reportableFlag=reportableFlag, - msgMaxSize=maxMessageSize, + reportableFlag=reportableFlag, msgMaxSize=maxMessageSize, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress @@ -819,8 +716,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): debug.logger & debug.flagMP and debug.logger('prepareDataElements: new stateReference %s' % stateReference) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc3412.prepareDataElements:confirmed', + snmpEngine, 'rfc3412.prepareDataElements:confirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -836,18 +732,10 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): ) # 7.2.13c - return (messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, + return (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, pdu, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, stateReference) # 7.2.14 @@ -856,8 +744,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): stateReference = self._cache.newStateReference() snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc3412.prepareDataElements:unconfirmed', + snmpEngine, 'rfc3412.prepareDataElements:unconfirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, @@ -875,24 +762,16 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # This is not specified explicitly in RFC smHandler.releaseStateInformation(securityStateReference) - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) + return (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, pdu, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, + stateReference) smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( - errorIndication = errind.unsupportedPDUtype - ) + errorIndication=errind.unsupportedPDUtype + ) def __expireEnginesInfo(self): if self.__expirationTimer in self.__engineIdCacheExpQueue: @@ -904,5 +783,4 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): def receiveTimerTick(self, snmpEngine, timeNow): self.__expireEnginesInfo() - AbstractMessageProcessingModel.receiveTimerTick(self, snmpEngine, - timeNow) + AbstractMessageProcessingModel.receiveTimerTick(self, snmpEngine, timeNow) diff --git a/pysnmp/proto/proxy/rfc2576.py b/pysnmp/proto/proxy/rfc2576.py index 3168ac69..7ba050bd 100644 --- a/pysnmp/proto/proxy/rfc2576.py +++ b/pysnmp/proto/proxy/rfc2576.py @@ -15,7 +15,7 @@ __v1ToV2ValueMap = { v1.Gauge.tagSet: v2c.Gauge32(), v1.TimeTicks.tagSet: v2c.TimeTicks(), v1.Opaque.tagSet: v2c.Opaque() - } +} __v2ToV1ValueMap = { # XXX do not re-create same-type items? v2c.Integer32.tagSet: v1.Integer(), @@ -27,7 +27,7 @@ __v2ToV1ValueMap = { # XXX do not re-create same-type items? v2c.Gauge32.tagSet: v1.Gauge(), v2c.TimeTicks.tagSet: v1.TimeTicks(), v2c.Opaque.tagSet: v1.Opaque() - } +} # PDU map @@ -37,7 +37,7 @@ __v1ToV2PduMap = { v1.SetRequestPDU.tagSet: v2c.SetRequestPDU(), v1.GetResponsePDU.tagSet: v2c.ResponsePDU(), v1.TrapPDU.tagSet: v2c.SNMPv2TrapPDU() - } +} __v2ToV1PduMap = { v2c.GetRequestPDU.tagSet: v1.GetRequestPDU(), @@ -46,7 +46,7 @@ __v2ToV1PduMap = { v2c.ResponsePDU.tagSet: v1.GetResponsePDU(), v2c.SNMPv2TrapPDU.tagSet: v1.TrapPDU(), v2c.GetBulkRequestPDU.tagSet: v1.GetNextRequestPDU() # 4.1.1 - } +} # Trap map @@ -57,7 +57,7 @@ __v1ToV2TrapMap = { 3: (1,3,6,1,6,3,1,1,5,4), 4: (1,3,6,1,6,3,1,1,5,5), 5: (1,3,6,1,6,3,1,1,5,6) - } +} __v2ToV1TrapMap = { (1,3,6,1,6,3,1,1,5,1): 0, @@ -66,7 +66,7 @@ __v2ToV1TrapMap = { (1,3,6,1,6,3,1,1,5,4): 3, (1,3,6,1,6,3,1,1,5,5): 4, (1,3,6,1,6,3,1,1,5,6): 5 - } +} # 4.3 @@ -87,7 +87,7 @@ __v2ToV1ErrorMap = { 14: 5, 15: 5, 16: 2 - } +} __zeroInt = v1.Integer(0) @@ -112,16 +112,14 @@ def v1ToV2(v1Pdu, origV2Pdu=None): # 3.1.3 else: - snmpTrapOIDParam = v2c.ObjectIdentifier( - __v1ToV2TrapMap[genericTrap] - ) + snmpTrapOIDParam = v2c.ObjectIdentifier(__v1ToV2TrapMap[genericTrap]) # 3.1.4 (XXX snmpTrapCommunity.0 is missing here) v2VarBinds.append((v2c.apiTrapPDU.sysUpTime, sysUpTime)) v2VarBinds.append((v2c.apiTrapPDU.snmpTrapOID, snmpTrapOIDParam)) v2VarBinds.append( (v2c.apiTrapPDU.snmpTrapAddress, v1.apiTrapPDU.getAgentAddr(v1Pdu)) - ) + ) v2VarBinds.append((v2c.apiTrapPDU.snmpTrapCommunity, v2c.OctetString(""))) v2VarBinds.append((v2c.apiTrapPDU.snmpTrapEnterprise, v1.apiTrapPDU.getEnterprise(v1Pdu))) @@ -137,7 +135,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None): v1Val = v1Val.getComponent() v2VarBinds.append( (oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val)) - ) + ) if pduType in rfc3411.responseClassPDUs: # 4.1.2.2.1&2 @@ -270,7 +268,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None): v1.apiPDU.setErrorStatus(v1Pdu, 2) v1.apiPDU.setErrorIndex(v1Pdu, idx+1) - idx = idx - 1 + idx -= 1 # 4.1.2.3.1 v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu) @@ -292,7 +290,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None): for oid, v2Val in v2VarBinds: v1VarBinds.append( (oid, __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val)) - ) + ) if pduType in rfc3411.notificationClassPDUs: v1.apiTrapPDU.setVarBinds(v1Pdu, v1VarBinds) @@ -301,7 +299,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None): v1.apiPDU.setRequestID( v1Pdu, v2c.apiPDU.getRequestID(v2Pdu) - ) + ) debug.logger & debug.flagPrx and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint()) diff --git a/pysnmp/proto/rfc1155.py b/pysnmp/proto/rfc1155.py index 483d301d..4018e924 100644 --- a/pysnmp/proto/rfc1155.py +++ b/pysnmp/proto/rfc1155.py @@ -8,15 +8,15 @@ __all__ = ['Opaque', 'NetworkAddress', 'ObjectName', 'TimeTicks', class IpAddress(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) - ) + ) subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( 4, 4 - ) + ) def prettyIn(self, value): if isinstance(value, str) and len(value) != 4: try: - value = [ int(x) for x in value.split('.') ] + value = [int(x) for x in value.split('.')] except: raise error.ProtocolError('Bad IP address syntax %s' % value) if len(value) != 4: @@ -25,45 +25,43 @@ class IpAddress(univ.OctetString): def prettyOut(self, value): if value: - return '.'.join( - [ '%d' % x for x in self.__class__(value).asNumbers() ] - ) + return '.'.join(['%d' % x for x in self.__class__(value).asNumbers()]) else: return '' class Counter(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01) - ) + ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 - ) + ) class NetworkAddress(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('internet', IpAddress()) - ) + ) class Gauge(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) - ) + ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 - ) + ) class TimeTicks(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) - ) + ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 - ) + ) class Opaque(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) - ) + ) class ObjectName(univ.ObjectIdentifier): pass @@ -75,9 +73,7 @@ class TypeCoercionHackMixIn: # XXX componentType = self._componentType if componentType: if idx >= len(componentType): - raise PyAsn1Error( - 'Component type error out of range' - ) + raise PyAsn1Error('Component type error out of range') t = componentType[idx].getType() if not t.getTagSet().isSuperTagSetOf(value.getTagSet()): raise PyAsn1Error('Component type error %r vs %r' % (t, value)) @@ -88,7 +84,7 @@ class SimpleSyntax(TypeCoercionHackMixIn, univ.Choice): namedtype.NamedType('string', univ.OctetString()), namedtype.NamedType('object', univ.ObjectIdentifier()), namedtype.NamedType('empty', univ.Null()) - ) + ) class ApplicationSyntax(TypeCoercionHackMixIn, univ.Choice): componentType = namedtype.NamedTypes( @@ -97,10 +93,10 @@ class ApplicationSyntax(TypeCoercionHackMixIn, univ.Choice): namedtype.NamedType('gauge', Gauge()), namedtype.NamedType('ticks', TimeTicks()), namedtype.NamedType('arbitrary', Opaque()) - ) + ) class ObjectSyntax(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('simple', SimpleSyntax()), namedtype.NamedType('application-wide', ApplicationSyntax()) - ) + ) diff --git a/pysnmp/proto/rfc1901.py b/pysnmp/proto/rfc1901.py index c50f3b83..48f55a61 100644 --- a/pysnmp/proto/rfc1901.py +++ b/pysnmp/proto/rfc1901.py @@ -8,4 +8,4 @@ class Message(univ.Sequence): namedtype.NamedType('version', _version), namedtype.NamedType('community', univ.OctetString()), namedtype.NamedType('data', rfc1905.PDUs()) - ) + ) diff --git a/pysnmp/proto/rfc1902.py b/pysnmp/proto/rfc1902.py index 9c9eb4f9..229f29eb 100644 --- a/pysnmp/proto/rfc1902.py +++ b/pysnmp/proto/rfc1902.py @@ -684,8 +684,8 @@ class ApplicationSyntax(rfc1155.TypeCoercionHackMixIn, univ.Choice): namedtype.NamedType('timeticks-value', TimeTicks()), namedtype.NamedType('arbitrary-value', Opaque()), namedtype.NamedType('big-counter-value', Counter64()), -# This conflicts with Counter32 -# namedtype.NamedType('unsigned-integer-value', Unsigned32()), + # This conflicts with Counter32 + #namedtype.NamedType('unsigned-integer-value', Unsigned32()), namedtype.NamedType('gauge32-value', Gauge32()) ) # BITS misplaced? diff --git a/pysnmp/proto/rfc3411.py b/pysnmp/proto/rfc3411.py index 465e0e85..74ee4d01 100644 --- a/pysnmp/proto/rfc3411.py +++ b/pysnmp/proto/rfc3411.py @@ -7,28 +7,28 @@ readClassPDUs = { rfc1905.GetRequestPDU.tagSet: 1, rfc1905.GetNextRequestPDU.tagSet: 1, rfc1905.GetBulkRequestPDU.tagSet: 1 - } +} writeClassPDUs = { rfc1157.SetRequestPDU.tagSet: 1, rfc1905.SetRequestPDU.tagSet: 1 - } +} responseClassPDUs = { rfc1157.GetResponsePDU.tagSet: 1, rfc1905.ResponsePDU.tagSet: 1, rfc1905.ReportPDU.tagSet: 1 - } +} notificationClassPDUs = { rfc1157.TrapPDU.tagSet: 1, rfc1905.SNMPv2TrapPDU.tagSet: 1, rfc1905.InformRequestPDU.tagSet: 1 - } +} internalClassPDUs = { rfc1905.ReportPDU.tagSet: 1 - } +} confirmedClassPDUs = { rfc1157.GetRequestPDU.tagSet: 1, @@ -39,7 +39,7 @@ confirmedClassPDUs = { rfc1905.GetBulkRequestPDU.tagSet: 1, rfc1905.SetRequestPDU.tagSet: 1, rfc1905.InformRequestPDU.tagSet: 1 - } +} unconfirmedClassPDUs = { rfc1157.GetResponsePDU.tagSet: 1, @@ -47,4 +47,4 @@ unconfirmedClassPDUs = { rfc1157.TrapPDU.tagSet: 1, rfc1905.ReportPDU.tagSet: 1, rfc1905.SNMPv2TrapPDU.tagSet: 1 - } +} diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py index 2b888214..c05bb188 100644 --- a/pysnmp/proto/rfc3412.py +++ b/pysnmp/proto/rfc3412.py @@ -133,20 +133,11 @@ class MsgAndPduDispatcher: (transportDomain, transportAddress, outgoingMessage) = mpHandler.prepareOutgoingMessage( - snmpEngine, - origTransportDomain, - origTransportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - expectResponse, - sendPduHandle - ) + snmpEngine, origTransportDomain, origTransportAddress, + messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, PDU, expectResponse, sendPduHandle + ) debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded') except PySnmpError: @@ -224,19 +215,11 @@ class MsgAndPduDispatcher: (transportDomain, transportAddress, outgoingMessage) = mpHandler.prepareResponseMessage( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) + snmpEngine, messageProcessingModel, securityModel, + securityName, securityLevel, contextEngineId, contextName, + pduVersion, PDU, maxSizeResponseScopedPDU, stateReference, + statusInformation + ) debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded') @@ -268,11 +251,9 @@ class MsgAndPduDispatcher: ) # 4.1.2.4 - snmpEngine.transportDispatcher.sendMessage( - outgoingMessage, - transportDomain, - transportAddress - ) + snmpEngine.transportDispatcher.sendMessage(outgoingMessage, + transportDomain, + transportAddress) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.returnResponsePdu' @@ -313,24 +294,13 @@ class MsgAndPduDispatcher: # 4.2.1.4 try: - (messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, + (messageProcessingModel, securityModel, securityName, + securityLevel, contextEngineId, contextName, + pduVersion, PDU, pduType, sendPduHandle, + maxSizeResponseScopedPDU, statusInformation, stateReference) = mpHandler.prepareDataElements( - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ) + snmpEngine, transportDomain, transportAddress, wholeMsg + ) debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded') @@ -379,19 +349,12 @@ class MsgAndPduDispatcher: (destTransportDomain, destTransportAddress, outgoingMessage) = mpHandler.prepareResponseMessage( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) + snmpEngine, messageProcessingModel, + securityModel, securityName, securityLevel, + contextEngineId, contextName, pduVersion, + PDU, maxSizeResponseScopedPDU, stateReference, + statusInformation + ) except error.StatusInformation: debug.logger & debug.flagDsp and debug.logger('receiveMessage: report failed, statusInformation %s' % sys.exc_info()[1]) @@ -400,8 +363,7 @@ class MsgAndPduDispatcher: # 4.2.2.1.2.c try: snmpEngine.transportDispatcher.sendMessage( - outgoingMessage, - destTransportDomain, + outgoingMessage, destTransportDomain, destTransportAddress ) @@ -525,13 +487,11 @@ class MsgAndPduDispatcher: if not statusInformation: statusInformation = error.StatusInformation( errorIndication=errind.requestTimedOut - ) + ) - self.releaseStateInformation( - snmpEngine, - cachedParams['sendPduHandle'], - cachedParams['messageProcessingModel'] - ) + self.releaseStateInformation(snmpEngine, + cachedParams['sendPduHandle'], + cachedParams['messageProcessingModel']) processResponsePdu(snmpEngine, None, None, None, None, None, None, None, None, statusInformation, diff --git a/pysnmp/proto/secmod/base.py b/pysnmp/proto/secmod/base.py index d4daaace..b3b55820 100644 --- a/pysnmp/proto/secmod/base.py +++ b/pysnmp/proto/secmod/base.py @@ -6,53 +6,22 @@ class AbstractSecurityModel: def __init__(self): self._cache = cache.Cache() - def processIncomingMsg( - self, - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg, - ): - raise error.ProtocolError( - 'Security model %s not implemented' % self - ) + def processIncomingMsg(self, snmpEngine, messageProcessingModel, + maxMessageSize, securityParameters, + securityModel, securityLevel, wholeMsg, msg): + raise error.ProtocolError('Security model %s not implemented' % self) - def generateRequestMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - ): - raise error.ProtocolError( - 'Security model %s not implemented' % self - ) + def generateRequestMsg(self, snmpEngine, messageProcessingModel, + globalData, maxMessageSize, securityModel, + securityEngineID, securityName, securityLevel, + scopedPDU): + raise error.ProtocolError('Security model %s not implemented' % self) - def generateResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): - raise error.ProtocolError( - 'Security model %s not implemented' % self - ) + def generateResponseMsg(self, snmpEngine, messageProcessingModel, + globalData, maxMessageSize, securityModel, + securityEngineID, securityName, securityLevel, + scopedPDU, securityStateReference): + raise error.ProtocolError('Security model %s not implemented' % self) def releaseStateInformation(self, stateReference): self._cache.pop(stateReference) diff --git a/pysnmp/proto/secmod/cache.py b/pysnmp/proto/secmod/cache.py index 99eae4a3..2fe245b7 100644 --- a/pysnmp/proto/secmod/cache.py +++ b/pysnmp/proto/secmod/cache.py @@ -16,8 +16,7 @@ class Cache: securityData = self.__cacheEntries[stateReference] else: raise error.ProtocolError( - 'Cache miss for stateReference=%s at %s' % - (stateReference, self) - ) + 'Cache miss for stateReference=%s at %s' % (stateReference, self) + ) del self.__cacheEntries[stateReference] return securityData diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py index 68b5c190..8d0d0d4d 100644 --- a/pysnmp/proto/secmod/rfc2576.py +++ b/pysnmp/proto/secmod/rfc2576.py @@ -31,19 +31,14 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): while 1: try: - nextMibNode = snmpTargetParamsSecurityName.getNextNode( - nextMibNode.name - ) + nextMibNode = snmpTargetParamsSecurityName.getNextNode(nextMibNode.name) + except NoSuchInstanceError: break - instId = nextMibNode.name[ - len(snmpTargetParamsSecurityName.name): - ] + instId = nextMibNode.name[len(snmpTargetParamsSecurityName.name):] - mibNode = snmpTargetParamsSecurityModel.getNode( - snmpTargetParamsSecurityModel.name + instId - ) + mibNode = snmpTargetParamsSecurityModel.getNode(snmpTargetParamsSecurityModel.name + instId) if mibNode.syntax not in self.__nameToModelMap: self.__nameToModelMap[nextMibNode.syntax] = set() @@ -57,63 +52,56 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): snmpCommunityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityName') if self.__securityBranchId != snmpCommunityName.branchVersionId: - ( snmpCommunitySecurityName, - snmpCommunityContextEngineId, - snmpCommunityContextName ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-COMMUNITY-MIB', - 'snmpCommunitySecurityName', - 'snmpCommunityContextEngineID', - 'snmpCommunityContextName', - ) + (snmpCommunitySecurityName, + snmpCommunityContextEngineId, + snmpCommunityContextName) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-COMMUNITY-MIB', 'snmpCommunitySecurityName', + 'snmpCommunityContextEngineID', 'snmpCommunityContextName' + ) self.__securityMap = {} nextMibNode = snmpCommunityName while 1: try: - nextMibNode = snmpCommunityName.getNextNode( - nextMibNode.name - ) + nextMibNode = snmpCommunityName.getNextNode(nextMibNode.name) + except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpCommunityName.name):] - _securityName = snmpCommunitySecurityName.getNode( - snmpCommunitySecurityName.name + instId - ).syntax + _securityName = snmpCommunitySecurityName.getNode(snmpCommunitySecurityName.name + instId).syntax - _contextEngineId = snmpCommunityContextEngineId.getNode( - snmpCommunityContextEngineId.name + instId - ).syntax + _contextEngineId = snmpCommunityContextEngineId.getNode(snmpCommunityContextEngineId.name + instId).syntax - _contextName = snmpCommunityContextName.getNode( - snmpCommunityContextName.name + instId - ).syntax + _contextName = snmpCommunityContextName.getNode(snmpCommunityContextName.name + instId).syntax - self.__securityMap[(_securityName, _contextEngineId, _contextName)] = nextMibNode.syntax + self.__securityMap[(_securityName, + _contextEngineId, + _contextName)] = nextMibNode.syntax self.__securityBranchId = snmpCommunityName.branchVersionId debug.logger & debug.flagSM and debug.logger('_sec2com: built securityName to communityName map, version %s: %s' % (self.__securityBranchId, self.__securityMap)) try: - return self.__securityMap[(securityName, contextEngineId, contextName)] + return self.__securityMap[(securityName, + contextEngineId, + contextName)] + except KeyError: raise error.StatusInformation( - errorIndication = errind.unknownCommunityName + errorIndication=errind.unknownCommunityName ) def _com2sec(self, snmpEngine, communityName, transportInformation): snmpTargetAddrTAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrTAddress') if self.__transportBranchId != snmpTargetAddrTAddress.branchVersionId: - ( SnmpTagValue, - snmpTargetAddrTDomain, - snmpTargetAddrTagList ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', - 'SnmpTagValue', - 'snmpTargetAddrTDomain', - 'snmpTargetAddrTagList' + (SnmpTagValue, snmpTargetAddrTDomain, + snmpTargetAddrTagList) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrTDomain', + 'snmpTargetAddrTagList' ) self.__emptyTag = SnmpTagValue('') @@ -121,44 +109,33 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): self.__transportToTagMap = {} nextMibNode = snmpTargetAddrTagList - while 1: + while True: try: - nextMibNode = snmpTargetAddrTagList.getNextNode( - nextMibNode.name - ) + nextMibNode = snmpTargetAddrTagList.getNextNode(nextMibNode.name) except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpTargetAddrTagList.name):] - targetAddrTDomain = snmpTargetAddrTDomain.getNode( - snmpTargetAddrTDomain.name + instId - ).syntax - targetAddrTAddress = snmpTargetAddrTAddress.getNode( - snmpTargetAddrTAddress.name + instId - ).syntax + targetAddrTDomain = snmpTargetAddrTDomain.getNode(snmpTargetAddrTDomain.name + instId).syntax + targetAddrTAddress = snmpTargetAddrTAddress.getNode(snmpTargetAddrTAddress.name + instId).syntax targetAddrTDomain = tuple(targetAddrTDomain) if targetAddrTDomain[:len(udp.snmpUDPDomain)] == udp.snmpUDPDomain: SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') - targetAddrTAddress = tuple( - SnmpUDPAddress(targetAddrTAddress) - ) + targetAddrTAddress = tuple(SnmpUDPAddress(targetAddrTAddress)) elif targetAddrTDomain[:len(udp6.snmpUDP6Domain)] == udp6.snmpUDP6Domain: TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') - targetAddrTAddress = tuple( - TransportAddressIPv6(targetAddrTAddress) - ) + targetAddrTAddress = tuple(TransportAddressIPv6(targetAddrTAddress)) elif targetAddrTDomain[:len(unix.snmpLocalDomain)] == unix.snmpLocalDomain: targetAddrTAddress = str(targetAddrTAddress) targetAddr = targetAddrTDomain, targetAddrTAddress - targetAddrTagList = snmpTargetAddrTagList.getNode( - snmpTargetAddrTagList.name + instId - ).syntax + targetAddrTagList = snmpTargetAddrTagList.getNode(snmpTargetAddrTagList.name + instId).syntax if targetAddr not in self.__transportToTagMap: self.__transportToTagMap[targetAddr] = set() if targetAddrTagList: self.__transportToTagMap[targetAddr].update( - [ SnmpTagValue(x) for x in targetAddrTagList.asOctets().split() ] + [SnmpTagValue(x) + for x in targetAddrTagList.asOctets().split()] ) else: self.__transportToTagMap[targetAddr].add(self.__emptyTag) @@ -167,7 +144,6 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): debug.logger & debug.flagSM and debug.logger('_com2sec: built transport-to-tag map version %s: %s' % (self.__transportBranchId, self.__transportToTagMap)) - snmpTargetParamsSecurityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsSecurityName') if self.__paramsBranchId != snmpTargetParamsSecurityName.branchVersionId: snmpTargetParamsSecurityModel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsSecurityModel') @@ -176,21 +152,16 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): nextMibNode = snmpTargetParamsSecurityName - while 1: + while True: try: - nextMibNode = snmpTargetParamsSecurityName.getNextNode( - nextMibNode.name - ) + nextMibNode = snmpTargetParamsSecurityName.getNextNode(nextMibNode.name) + except NoSuchInstanceError: break - instId = nextMibNode.name[ - len(snmpTargetParamsSecurityName.name): - ] + instId = nextMibNode.name[len(snmpTargetParamsSecurityName.name):] - mibNode = snmpTargetParamsSecurityModel.getNode( - snmpTargetParamsSecurityModel.name + instId - ) + mibNode = snmpTargetParamsSecurityModel.getNode(snmpTargetParamsSecurityModel.name + instId) if nextMibNode.syntax not in self.__nameToModelMap: self.__nameToModelMap[nextMibNode.syntax] = set() @@ -206,46 +177,34 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): snmpCommunityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityName') if self.__communityBranchId != snmpCommunityName.branchVersionId: - ( snmpCommunitySecurityName, - snmpCommunityContextEngineId, - snmpCommunityContextName, - snmpCommunityTransportTag ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-COMMUNITY-MIB', - 'snmpCommunitySecurityName', - 'snmpCommunityContextEngineID', - 'snmpCommunityContextName', - 'snmpCommunityTransportTag' - ) + (snmpCommunitySecurityName, snmpCommunityContextEngineId, + snmpCommunityContextName, + snmpCommunityTransportTag) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-COMMUNITY-MIB', 'snmpCommunitySecurityName', + 'snmpCommunityContextEngineID', 'snmpCommunityContextName', + 'snmpCommunityTransportTag' + ) self.__communityToTagMap = {} self.__tagAndCommunityToSecurityMap = {} nextMibNode = snmpCommunityName - while 1: + while True: try: - nextMibNode = snmpCommunityName.getNextNode( - nextMibNode.name - ) + nextMibNode = snmpCommunityName.getNextNode(nextMibNode.name) + except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpCommunityName.name):] - securityName = snmpCommunitySecurityName.getNode( - snmpCommunitySecurityName.name + instId - ).syntax + securityName = snmpCommunitySecurityName.getNode(snmpCommunitySecurityName.name + instId).syntax - contextEngineId = snmpCommunityContextEngineId.getNode( - snmpCommunityContextEngineId.name + instId - ).syntax + contextEngineId = snmpCommunityContextEngineId.getNode(snmpCommunityContextEngineId.name + instId).syntax - contextName = snmpCommunityContextName.getNode( - snmpCommunityContextName.name + instId - ).syntax + contextName = snmpCommunityContextName.getNode(snmpCommunityContextName.name + instId).syntax - transportTag = snmpCommunityTransportTag.getNode( - snmpCommunityTransportTag.name + instId - ).syntax + transportTag = snmpCommunityTransportTag.getNode(snmpCommunityTransportTag.name + instId).syntax _tagAndCommunity = transportTag, nextMibNode.syntax @@ -264,21 +223,20 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): self.__communityBranchId = snmpCommunityName.branchVersionId debug.logger & debug.flagSM and debug.logger('_com2sec: built communityName to tag map (securityModel %s), version %s: %s' % (self.securityModelID, self.__communityBranchId, self.__communityToTagMap)) + debug.logger & debug.flagSM and debug.logger('_com2sec: built tag & community to securityName map (securityModel %s), version %s: %s' % (self.securityModelID, self.__communityBranchId, self.__tagAndCommunityToSecurityMap)) if communityName in self.__communityToTagMap: if transportInformation in self.__transportToTagMap: tags = self.__transportToTagMap[transportInformation].intersection(self.__communityToTagMap[communityName]) elif self.__emptyTag in self.__communityToTagMap[communityName]: - tags = [ self.__emptyTag ] + tags = [self.__emptyTag] else: - raise error.StatusInformation( - errorIndication = errind.unknownCommunityName - ) + raise error.StatusInformation(errorIndication=errind.unknownCommunityName) candidateSecurityNames = [] - for x in [ self.__tagAndCommunityToSecurityMap[(t, communityName)] for t in tags ]: + for x in [self.__tagAndCommunityToSecurityMap[(t, communityName)] for t in tags]: candidateSecurityNames.extend(list(x)) # 5.2.1 (row selection in snmpCommunityTable) @@ -289,30 +247,18 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): debug.logger & debug.flagSM and debug.logger('_com2sec: securityName candidates for communityName \'%s\' are %s; choosing securityName \'%s\'' % (communityName, candidateSecurityNames, chosenSecurityName[0])) return chosenSecurityName - raise error.StatusInformation( - errorIndication = errind.unknownCommunityName - ) + raise error.StatusInformation(errorIndication=errind.unknownCommunityName) - def generateRequestMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineId, - securityName, - securityLevel, - scopedPDU - ): + def generateRequestMsg(self, snmpEngine, messageProcessingModel, + globalData, maxMessageSize, securityModel, + securityEngineId, securityName, securityLevel, + scopedPDU): msg, = globalData contextEngineId, contextName, pdu = scopedPDU # rfc2576: 5.2.3 - communityName = self._sec2com(snmpEngine, - securityName, - contextEngineId, - contextName) + communityName = self._sec2com(snmpEngine, securityName, + contextEngineId, contextName) debug.logger & debug.flagSM and debug.logger('generateRequestMsg: using community %r for securityModel %r, securityName %r, contextEngineId %r contextName %r' % (communityName, securityModel, securityName, contextEngineId, contextName)) @@ -328,25 +274,15 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): try: return securityParameters, encoder.encode(msg) + except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('generateRequestMsg: serialization failure: %s' % sys.exc_info()[1]) - raise error.StatusInformation( - errorIndication = errind.serializationError - ) + raise error.StatusInformation(errorIndication=errind.serializationError) - def generateResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): + def generateResponseMsg(self, snmpEngine, messageProcessingModel, + globalData, maxMessageSize, securityModel, + securityEngineID, securityName, securityLevel, + scopedPDU, securityStateReference): # rfc2576: 5.2.2 msg, = globalData contextEngineId, contextName, pdu = scopedPDU @@ -359,53 +295,40 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): msg.setComponentByPosition(2) msg.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False - ) + ) debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),)) try: return communityName, encoder.encode(msg) + except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('generateResponseMsg: serialization failure: %s' % sys.exc_info()[1]) - raise error.StatusInformation( - errorIndication = errind.serializationError - ) + raise error.StatusInformation(errorIndication=errind.serializationError) - def processIncomingMsg( - self, - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg - ): + def processIncomingMsg(self, snmpEngine, messageProcessingModel, + maxMessageSize, securityParameters, securityModel, + securityLevel, wholeMsg, msg): # rfc2576: 5.2.1 - ( communityName, transportInformation ) = securityParameters + communityName, transportInformation = securityParameters scope = dict(communityName=communityName, transportInformation=transportInformation) snmpEngine.observer.storeExecutionContext( - snmpEngine, - 'rfc2576.processIncomingMsg:writable', - scope + snmpEngine, 'rfc2576.processIncomingMsg:writable', scope ) try: securityName, contextEngineId, contextName = self._com2sec( - snmpEngine, - scope.get('communityName', communityName), + snmpEngine, scope.get('communityName', communityName), scope.get('transportInformation', transportInformation) ) + except error.StatusInformation: snmpInBadCommunityNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadCommunityNames') snmpInBadCommunityNames.syntax = snmpInBadCommunityNames.syntax+1 - raise error.StatusInformation( - errorIndication = errind.unknownCommunityName - ) + raise error.StatusInformation(errorIndication=errind.unknownCommunityName) snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') @@ -413,24 +336,17 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): debug.logger & debug.flagSM and debug.logger('processIncomingMsg: looked up securityName %r securityModel %r contextEngineId %r contextName %r by communityName %r AND transportInformation %r' % (securityName, self.securityModelID, contextEngineId, contextName, communityName, transportInformation)) - stateReference = self._cache.push( - communityName=communityName - ) + stateReference = self._cache.push(communityName=communityName) - scopedPDU = ( - contextEngineId, contextName, - msg.getComponentByPosition(2).getComponent() - ) + scopedPDU = (contextEngineId, contextName, + msg.getComponentByPosition(2).getComponent()) maxSizeResponseScopedPDU = maxMessageSize - 128 securityStateReference = stateReference debug.logger & debug.flagSM and debug.logger('processIncomingMsg: generated maxSizeResponseScopedPDU %s securityStateReference %s' % (maxSizeResponseScopedPDU, securityStateReference)) - return ( securityEngineID, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) + return (securityEngineID, securityName, scopedPDU, + maxSizeResponseScopedPDU, securityStateReference) class SnmpV2cSecurityModel(SnmpV1SecurityModel): securityModelID = 2 diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py index dcb66e70..a6779352 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py +++ b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py @@ -53,7 +53,7 @@ class HmacMd5(base.AbstractAuthenticationService): # 6.3.1.2e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) - ) + ) # 6.3.1.3 d1 = md5(k1.asOctets()+wholeMsg).digest() @@ -71,7 +71,7 @@ class HmacMd5(base.AbstractAuthenticationService): if len(authParameters) != 12: raise error.StatusInformation( errorIndication=errind.authenticationError - ) + ) # 6.3.2.3 l = wholeMsg.find(authParameters.asOctets()) @@ -89,14 +89,14 @@ class HmacMd5(base.AbstractAuthenticationService): # 6.3.2.4c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) - ) + ) # 6.3.2.4d --> noop # 6.3.2.4e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) - ) + ) # 6.3.2.5a d1 = md5(k1.asOctets()+authenticatedWholeMsg).digest() @@ -111,6 +111,6 @@ class HmacMd5(base.AbstractAuthenticationService): if mac != authParameters: raise error.StatusInformation( errorIndication=errind.authenticationFailure - ) + ) return authenticatedWholeMsg diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py index bdaa522a..3006e550 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py +++ b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py @@ -45,14 +45,14 @@ class HmacSha(base.AbstractAuthenticationService): # 7.3.1.2c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) - ) + ) # 7.3.1.2d -- noop # 7.3.1.2e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) - ) + ) # 7.3.1.3 d1 = sha1(k1.asOctets()+wholeMsg).digest() @@ -70,7 +70,7 @@ class HmacSha(base.AbstractAuthenticationService): if len(authParameters) != 12: raise error.StatusInformation( errorIndication=errind.authenticationError - ) + ) # 7.3.2.3 l = wholeMsg.find(authParameters.asOctets()) @@ -88,14 +88,14 @@ class HmacSha(base.AbstractAuthenticationService): # 7.3.2.4c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) - ) + ) # 7.3.2.4d --> noop # 7.3.2.4e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) - ) + ) # 7.3.2.5a d1 = sha1(k1.asOctets()+authenticatedWholeMsg).digest() @@ -110,6 +110,6 @@ class HmacSha(base.AbstractAuthenticationService): if mac != authParameters: raise error.StatusInformation( errorIndication=errind.authenticationFailure - ) + ) return authenticatedWholeMsg diff --git a/pysnmp/proto/secmod/rfc3414/localkey.py b/pysnmp/proto/secmod/rfc3414/localkey.py index c3be7501..7157c435 100644 --- a/pysnmp/proto/secmod/rfc3414/localkey.py +++ b/pysnmp/proto/secmod/rfc3414/localkey.py @@ -23,9 +23,9 @@ def hashPassphraseMD5(passphrase): else: md.update( ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] - ) + ) mark = e-ringBufferLen - count = count + 1 + count += 1 return md.digest() def localizeKeyMD5(passKey, snmpEngineId): @@ -51,9 +51,9 @@ def hashPassphraseSHA(passphrase): else: md.update( ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] - ) + ) mark = e-ringBufferLen - count = count + 1 + count += 1 return md.digest() def localizeKeySHA(passKey, snmpEngineId): diff --git a/pysnmp/proto/secmod/rfc3414/priv/des.py b/pysnmp/proto/secmod/rfc3414/priv/des.py index 419bd177..39b66aaa 100644 --- a/pysnmp/proto/secmod/rfc3414/priv/des.py +++ b/pysnmp/proto/secmod/rfc3414/priv/des.py @@ -4,11 +4,7 @@ from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import errind, error from pyasn1.type import univ - -try: - from sys import version_info -except ImportError: - version_info = ( 0, 0 ) # a really early version +from sys import version_info try: from Crypto.Cipher import DES @@ -34,7 +30,7 @@ class Des(base.AbstractEncryptionService): else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) + ) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: @@ -44,7 +40,7 @@ class Des(base.AbstractEncryptionService): else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) + ) return localPrivKey[:32] # key+IV # 8.1.1.1 @@ -54,43 +50,40 @@ class Des(base.AbstractEncryptionService): securityEngineBoots = int(snmpEngineBoots) - salt = [ - securityEngineBoots>>24&0xff, - securityEngineBoots>>16&0xff, - securityEngineBoots>>8&0xff, - securityEngineBoots&0xff, - self._localInt>>24&0xff, - self._localInt>>16&0xff, - self._localInt>>8&0xff, - self._localInt&0xff - ] + salt = [securityEngineBoots>>24&0xff, + securityEngineBoots>>16&0xff, + securityEngineBoots>>8&0xff, + securityEngineBoots&0xff, + self._localInt>>24&0xff, + self._localInt>>16&0xff, + self._localInt>>8&0xff, + self._localInt&0xff] if self._localInt == 0xffffffff: self._localInt = 0 else: self._localInt = self._localInt + 1 - return desKey.asOctets(), \ - univ.OctetString(salt).asOctets(), \ - univ.OctetString(map(lambda x,y:x^y,salt,preIV.asNumbers())).asOctets() + return (desKey.asOctets(), + univ.OctetString(salt).asOctets(), + univ.OctetString(map(lambda x,y:x^y,salt,preIV.asNumbers())).asOctets()) def __getDecryptionKey(self, privKey, salt): - return privKey[:8].asOctets(), univ.OctetString( - map(lambda x,y:x^y, salt.asNumbers(), privKey[8:16].asNumbers()) - ).asOctets() + return (privKey[:8].asOctets(), + univ.OctetString(map(lambda x,y:x^y, salt.asNumbers(), privKey[8:16].asNumbers())).asOctets()) # 8.2.4.1 def encryptData(self, encryptKey, privParameters, dataToEncrypt): if DES is None: raise error.StatusInformation( errorIndication=errind.encryptionError - ) + ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 8.3.1.1 desKey, salt, iv = self.__getEncryptionKey( encryptKey, snmpEngineBoots - ) + ) # 8.3.1.2 privParameters = univ.OctetString(salt) @@ -108,7 +101,7 @@ class Des(base.AbstractEncryptionService): if DES is None: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) snmpEngineBoots, snmpEngineTime, salt = privParameters @@ -116,7 +109,7 @@ class Des(base.AbstractEncryptionService): if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) # 8.3.2.2 noop @@ -127,7 +120,7 @@ class Des(base.AbstractEncryptionService): if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) desObj = DES.new(desKey, DES.MODE_CBC, iv) diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py index df22e880..bf244b92 100644 --- a/pysnmp/proto/secmod/rfc3414/service.py +++ b/pysnmp/proto/secmod/rfc3414/service.py @@ -23,23 +23,19 @@ class UsmSecurityParameters(rfc1155.TypeCoercionHackMixIn, univ.Sequence): namedtype.NamedType('msgUserName', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32))), namedtype.NamedType('msgAuthenticationParameters', univ.OctetString()), namedtype.NamedType('msgPrivacyParameters', univ.OctetString()) - ) + ) class SnmpUSMSecurityModel(AbstractSecurityModel): securityModelID = 3 - authServices = { - hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), - hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), - noauth.NoAuth.serviceID: noauth.NoAuth() - } - privServices = { - des.Des.serviceID: des.Des(), - des3.Des3.serviceID: des3.Des3(), - aes.Aes.serviceID: aes.Aes(), - aes192.Aes192.serviceID: aes192.Aes192(), - aes256.Aes256.serviceID: aes256.Aes256(), - nopriv.NoPriv.serviceID: nopriv.NoPriv() - } + authServices = {hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), + hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), + noauth.NoAuth.serviceID: noauth.NoAuth()} + privServices = {des.Des.serviceID: des.Des(), + des3.Des3.serviceID: des3.Des3(), + aes.Aes.serviceID: aes.Aes(), + aes192.Aes192.serviceID: aes192.Aes192(), + aes256.Aes256.serviceID: aes256.Aes256(), + nopriv.NoPriv.serviceID: nopriv.NoPriv() } def __init__(self): AbstractSecurityModel.__init__(self) self.__securityParametersSpec = UsmSecurityParameters() @@ -59,9 +55,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): while 1: try: - nextMibNode = usmUserEngineID.getNextNode( - nextMibNode.name - ) + nextMibNode = usmUserEngineID.getNextNode(nextMibNode.name) + except NoSuchInstanceError: self.__paramsBranchId = usmUserEngineID.branchVersionId debug.logger & debug.flagSM and debug.logger('_sec2usr: built snmpEngineId + securityName to userName map, version %s: %r' % (self.__paramsBranchId, self.__securityToUserMap)) @@ -93,51 +88,29 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): return userName - def __getUserInfo( - self, mibInstrumController, securityEngineID, userName - ): + def __getUserInfo(self, mibInstrumController, securityEngineID, userName): usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' ) - tblIdx = usmUserEntry.getInstIdFromIndices( - securityEngineID, userName - ) + tblIdx = usmUserEntry.getInstIdFromIndices(securityEngineID, userName) # Get userName & securityName - usmUserName = usmUserEntry.getNode( - usmUserEntry.name + (2,) + tblIdx - ).syntax - usmUserSecurityName = usmUserEntry.getNode( - usmUserEntry.name + (3,) + tblIdx - ).syntax + usmUserName = usmUserEntry.getNode(usmUserEntry.name + (2,) + tblIdx).syntax + usmUserSecurityName = usmUserEntry.getNode(usmUserEntry.name + (3,) + tblIdx).syntax # Get protocols - usmUserAuthProtocol = usmUserEntry.getNode( - usmUserEntry.name + (5,) + tblIdx - ).syntax - usmUserPrivProtocol = usmUserEntry.getNode( - usmUserEntry.name + (8,) + tblIdx - ).syntax + usmUserAuthProtocol = usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx).syntax + usmUserPrivProtocol = usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx).syntax # Get keys pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' - ) - pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (1,) + tblIdx - ).syntax - pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (2,) + tblIdx - ).syntax - return ( - usmUserName, - usmUserSecurityName, - usmUserAuthProtocol, - pysnmpUsmKeyAuthLocalized, - usmUserPrivProtocol, - pysnmpUsmKeyPrivLocalized ) - - def __cloneUserInfo( - self, mibInstrumController, securityEngineID, userName - ): + pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (1,) + tblIdx).syntax + pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (2,) + tblIdx).syntax + return (usmUserName, usmUserSecurityName, usmUserAuthProtocol, + pysnmpUsmKeyAuthLocalized, usmUserPrivProtocol, + pysnmpUsmKeyPrivLocalized) + + def __cloneUserInfo(self, mibInstrumController, securityEngineID, + userName): snmpEngineID, = mibInstrumController.mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineID' ) @@ -149,37 +122,21 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): snmpEngineID.syntax, userName ) # Get proto protocols - usmUserName = usmUserEntry.getNode( - usmUserEntry.name + (2,) + tblIdx1 - ) - usmUserSecurityName = usmUserEntry.getNode( - usmUserEntry.name + (3,) + tblIdx1 - ) - usmUserCloneFrom = usmUserEntry.getNode( - usmUserEntry.name + (4,) + tblIdx1 - ) - usmUserAuthProtocol = usmUserEntry.getNode( - usmUserEntry.name + (5,) + tblIdx1 - ) - usmUserPrivProtocol = usmUserEntry.getNode( - usmUserEntry.name + (8,) + tblIdx1 - ) + usmUserName = usmUserEntry.getNode(usmUserEntry.name + (2,) + tblIdx1) + usmUserSecurityName = usmUserEntry.getNode(usmUserEntry.name + (3,) + tblIdx1) + usmUserCloneFrom = usmUserEntry.getNode(usmUserEntry.name + (4,) + tblIdx1) + usmUserAuthProtocol = usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx1) + usmUserPrivProtocol = usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx1) # Get proto keys pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' ) - pysnmpUsmKeyAuth = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (3,) + tblIdx1 - ) - pysnmpUsmKeyPriv = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (4,) + tblIdx1 - ) + pysnmpUsmKeyAuth = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (3,) + tblIdx1) + pysnmpUsmKeyPriv = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (4,) + tblIdx1) # Create new row from proto values - tblIdx2 = usmUserEntry.getInstIdFromIndices( - securityEngineID, userName - ) + tblIdx2 = usmUserEntry.getInstIdFromIndices(securityEngineID, userName) # New row mibInstrumController.writeVars( @@ -187,83 +144,55 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): ) # Set user&securityNames - usmUserEntry.getNode( - usmUserEntry.name + (2,) + tblIdx2 - ).syntax = usmUserName.syntax - usmUserEntry.getNode( - usmUserEntry.name + (3,) + tblIdx2 - ).syntax = usmUserSecurityName.syntax + usmUserEntry.getNode(usmUserEntry.name + (2,) + tblIdx2).syntax = usmUserName.syntax + usmUserEntry.getNode(usmUserEntry.name + (3,) + tblIdx2).syntax = usmUserSecurityName.syntax # Store a reference to original row - usmUserEntry.getNode( - usmUserEntry.name + (4,) + tblIdx2 - ).syntax = usmUserCloneFrom.syntax.clone(tblIdx1) + usmUserEntry.getNode(usmUserEntry.name + (4,) + tblIdx2).syntax = usmUserCloneFrom.syntax.clone(tblIdx1) # Set protocols - usmUserEntry.getNode( - usmUserEntry.name + (5,) + tblIdx2 - ).syntax = usmUserAuthProtocol.syntax - usmUserEntry.getNode( - usmUserEntry.name + (8,) + tblIdx2 - ).syntax = usmUserPrivProtocol.syntax + usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx2).syntax = usmUserAuthProtocol.syntax + usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx2).syntax = usmUserPrivProtocol.syntax # Localize and set keys pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' - ) + ) pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( pysnmpUsmKeyEntry.name + (1,) + tblIdx2 - ) + ) if usmUserAuthProtocol.syntax in self.authServices: localizeKey = self.authServices[usmUserAuthProtocol.syntax].localizeKey - localAuthKey = localizeKey( - pysnmpUsmKeyAuth.syntax, - securityEngineID - ) + localAuthKey = localizeKey(pysnmpUsmKeyAuth.syntax, + securityEngineID) else: raise error.StatusInformation( errorIndication = errind.unsupportedAuthProtocol - ) + ) if localAuthKey is not None: pysnmpUsmKeyAuthLocalized.syntax = pysnmpUsmKeyAuthLocalized.syntax.clone(localAuthKey) pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( pysnmpUsmKeyEntry.name + (2,) + tblIdx2 - ) + ) if usmUserPrivProtocol.syntax in self.privServices: localizeKey = self.privServices[usmUserPrivProtocol.syntax].localizeKey - localPrivKey = localizeKey( - usmUserAuthProtocol.syntax, - pysnmpUsmKeyPriv.syntax, - securityEngineID - ) + localPrivKey = localizeKey(usmUserAuthProtocol.syntax, + pysnmpUsmKeyPriv.syntax, + securityEngineID) else: - raise error.StatusInformation( - errorIndication = errind.unsupportedPrivProtocol - ) + raise error.StatusInformation(errorIndication=errind.unsupportedPrivProtocol) if localPrivKey is not None: pysnmpUsmKeyPrivLocalized.syntax = pysnmpUsmKeyPrivLocalized.syntax.clone(localPrivKey) - return ( - usmUserName.syntax, - usmUserSecurityName.syntax, - usmUserAuthProtocol.syntax, - pysnmpUsmKeyAuthLocalized.syntax, - usmUserPrivProtocol.syntax, - pysnmpUsmKeyPrivLocalized.syntax - ) - - def __generateRequestOrResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): + return (usmUserName.syntax, usmUserSecurityName.syntax, + usmUserAuthProtocol.syntax, pysnmpUsmKeyAuthLocalized.syntax, + usmUserPrivProtocol.syntax, pysnmpUsmKeyPrivLocalized.syntax) + + def __generateRequestOrResponseMsg(self, snmpEngine, + messageProcessingModel, + globalData, maxMessageSize, + securityModel, securityEngineID, + securityName, securityLevel, + scopedPDU, securityStateReference): snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax # 3.1.1 if securityStateReference is not None: @@ -295,40 +224,39 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): elif securityName: # 3.1.1b try: - ( usmUserName, - usmUserSecurityName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - securityEngineID, - self.__sec2usr(snmpEngine, securityName, securityEngineID) - ) + (usmUserName, usmUserSecurityName, usmUserAuthProtocol, + usmUserAuthKeyLocalized, usmUserPrivProtocol, + usmUserPrivKeyLocalized ) = self.__getUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + securityEngineID, + self.__sec2usr(snmpEngine, securityName, securityEngineID) + ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read user info') + except NoSuchInstanceError: pysnmpUsmDiscovery, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery') __reportUnknownName = not pysnmpUsmDiscovery.syntax if not __reportUnknownName: try: - ( usmUserName, - usmUserSecurityName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__cloneUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - securityEngineID, - self.__sec2usr(snmpEngine, securityName) - ) + (usmUserName, usmUserSecurityName, + usmUserAuthProtocol, usmUserAuthKeyLocalized, + usmUserPrivProtocol, + usmUserPrivKeyLocalized) = self.__cloneUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + securityEngineID, + self.__sec2usr(snmpEngine, securityName) + ) + except NoSuchInstanceError: __reportUnknownName = 1 if __reportUnknownName: raise error.StatusInformation( - errorIndication = errind.unknownSecurityName - ) + errorIndication=errind.unknownSecurityName + ) + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info') + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInGenErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') @@ -353,34 +281,28 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): if usmUserAuthProtocol == noauth.NoAuth.serviceID or \ usmUserPrivProtocol == nopriv.NoPriv.serviceID: raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityLevel - ) + errorIndication=errind.unsupportedSecurityLevel + ) # 3.1.3 if securityLevel == 3 or securityLevel == 2: if usmUserAuthProtocol == noauth.NoAuth.serviceID: raise error.StatusInformation( - errorIndication = errind.unsupportedSecurityLevel - ) + errorIndication=errind.unsupportedSecurityLevel + ) securityParameters = self.__securityParametersSpec scopedPDUData = msg.setComponentByPosition(3).getComponentByPosition(3) scopedPDUData.setComponentByPosition( 0, scopedPDU, verifyConstraints=False - ) + ) # 3.1.6a - if securityStateReference is None and ( # request type check added - securityLevel == 3 or securityLevel == 2 - ): + if securityStateReference is None and securityLevel in (2, 3): if securityEngineID in self.__timeline: - ( snmpEngineBoots, - snmpEngineTime, - latestReceivedEngineTime, - latestUpdateTimestamp) = self.__timeline[ - securityEngineID - ] + (snmpEngineBoots, snmpEngineTime, latestReceivedEngineTime, + latestUpdateTimestamp) = self.__timeline[securityEngineID] debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline') else: # 2.3 XXX is this correct? @@ -388,8 +310,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: no timeline for securityEngineID %r' % (securityEngineID,)) # 3.1.6.b elif securityStateReference is not None: # XXX Report? - ( snmpEngineBoots, - snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') + (snmpEngineBoots, + snmpEngineTime) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') snmpEngineBoots = snmpEngineBoots.syntax snmpEngineTime = snmpEngineTime.syntax.clone() debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD') @@ -406,27 +328,27 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): privHandler = self.privServices[usmUserPrivProtocol] else: raise error.StatusInformation( - errorIndication = errind.encryptionError + errorIndication=errind.encryptionError ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU %s' % scopedPDU.prettyPrint()) try: dataToEncrypt = encoder.encode(scopedPDU) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( - errorIndication = errind.serializationError + errorIndication=errind.serializationError ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU encoded into %s' % debug.hexdump(dataToEncrypt)) - ( encryptedData, - privParameters ) = privHandler.encryptData( - usmUserPrivKeyLocalized, - ( snmpEngineBoots, snmpEngineTime, None ), - dataToEncrypt - ) + (encryptedData, + privParameters) = privHandler.encryptData( + usmUserPrivKeyLocalized, + (snmpEngineBoots, snmpEngineTime, None), dataToEncrypt + ) securityParameters.setComponentByPosition( 5, privParameters, verifyConstraints=False @@ -465,134 +387,101 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): authHandler = self.authServices[usmUserAuthProtocol] else: raise error.StatusInformation( - errorIndication = errind.authenticationFailure - ) + errorIndication=errind.authenticationFailure + ) # extra-wild hack to facilitate BER substrate in-place re-write securityParameters.setComponentByPosition( 4, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - ) + ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: securityParameters serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( - errorIndication = errind.serializationError + errorIndication=errind.serializationError ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: auth outgoing msg: %s' % msg.prettyPrint()) try: wholeMsg = encoder.encode(msg) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: msg serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( - errorIndication = errind.serializationError + errorIndication=errind.serializationError ) authenticatedWholeMsg = authHandler.authenticateOutgoingMsg( usmUserAuthKeyLocalized, wholeMsg - ) + ) # 3.1.8b else: securityParameters.setComponentByPosition( 4, '', verifyConstraints=False - ) + ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: secutiryParameters serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( - errorIndication = errind.serializationError + errorIndication=errind.serializationError ) try: debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: plain outgoing msg: %s' % msg.prettyPrint()) authenticatedWholeMsg = encoder.encode(msg) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: msg serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( - errorIndication = errind.serializationError + errorIndication=errind.serializationError ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s outgoing msg: %s' % (securityLevel > 1 and "authenticated" or "plain", debug.hexdump(authenticatedWholeMsg))) # 3.1.9 - return ( - msg.getComponentByPosition(2), - authenticatedWholeMsg - ) - - def generateRequestMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - ): - return self.__generateRequestOrResponseMsg( - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - None - ) - - def generateResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): + return (msg.getComponentByPosition(2), authenticatedWholeMsg) + + def generateRequestMsg(self, snmpEngine, messageProcessingModel, + globalData, maxMessageSize, securityModel, + securityEngineID, securityName, securityLevel, + scopedPDU): + return self.__generateRequestOrResponseMsg(snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + None) + + def generateResponseMsg(self, snmpEngine, messageProcessingModel, + globalData, maxMessageSize, securityModel, + securityEngineID, securityName, securityLevel, + scopedPDU, securityStateReference): return self.__generateRequestOrResponseMsg( - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ) + snmpEngine, messageProcessingModel, globalData, + maxMessageSize, securityModel, securityEngineID, + securityName, securityLevel, scopedPDU, securityStateReference + ) # 3.2 - def processIncomingMsg( - self, - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg # XXX - ): + def processIncomingMsg(self, snmpEngine, messageProcessingModel, + maxMessageSize, securityParameters, + securityModel, securityLevel, wholeMsg, msg): # 3.2.9 -- moved up here to be able to report # maxSizeResponseScopedPDU on error # (48 - maximum SNMPv3 header length) @@ -603,29 +492,25 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): # 3.2.1 try: securityParameters, rest = decoder.decode( - securityParameters, - asn1Spec=self.__securityParametersSpec - ) + securityParameters, asn1Spec=self.__securityParametersSpec + ) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') - snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 - raise error.StatusInformation( - errorIndication=errind.parseError - ) + snmpInASNParseErrs.syntax += 1 + raise error.StatusInformation(errorIndication=errind.parseError) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),)) if eoo.endOfOctets.isSameTypeWith(securityParameters): - raise error.StatusInformation( - errorIndication=errind.parseError - ) + raise error.StatusInformation(errorIndication=errind.parseError) # 3.2.2 msgAuthoritativeEngineID = securityParameters.getComponentByPosition(0) securityStateReference = self._cache.push( msgUserName=securityParameters.getComponentByPosition(3) - ) + ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cache write securityStateReference %s by msgUserName %s' % (securityStateReference, securityParameters.getComponentByPosition(3))) @@ -638,7 +523,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): # 3.2.3 if msgAuthoritativeEngineID not in self.__timeline: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %r' % (msgAuthoritativeEngineID,)) - if not msgAuthoritativeEngineID or \ + if not msgAuthoritativeEngineID or \ not 4 < len(msgAuthoritativeEngineID) < 33: # 3.2.3b usmStatsUnknownEngineIDs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs') @@ -652,8 +537,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): if scopedPduData.getName() != 'plaintext': debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPduData not plaintext %s' % scopedPduData.prettyPrint()) raise error.StatusInformation( - errorIndication = errind.unknownEngineID - ) + errorIndication=errind.unknownEngineID + ) # 7.2.6.a.1 scopedPdu = scopedPduData.getComponent() @@ -661,7 +546,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextName = scopedPdu.getComponentByPosition(1) raise error.StatusInformation( - errorIndication = errind.unknownEngineID, + errorIndication=errind.unknownEngineID, oid=usmStatsUnknownEngineIDs.name, val=usmStatsUnknownEngineIDs.syntax, securityStateReference=securityStateReference, @@ -670,13 +555,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextName=contextName, scopedPDU=scopedPdu, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) + ) else: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: will not discover EngineID') # free securityStateReference XXX raise error.StatusInformation( - errorIndication = errind.unknownEngineID - ) + errorIndication=errind.unknownEngineID + ) snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax @@ -687,56 +572,51 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): if msgUserName: # 3.2.4 try: - ( usmUserName, - usmUserSecurityName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - msgAuthoritativeEngineID, - msgUserName - ) + (usmUserName, usmUserSecurityName, usmUserAuthProtocol, + usmUserAuthKeyLocalized, usmUserPrivProtocol, + usmUserPrivKeyLocalized) = self.__getUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + msgAuthoritativeEngineID, msgUserName + ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read user info from LCD') + except NoSuchInstanceError: pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') __reportUnknownName = not pysnmpUsmDiscoverable.syntax if not __reportUnknownName: try: - ( usmUserName, - usmUserSecurityName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__cloneUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - msgAuthoritativeEngineID, - msgUserName - ) + (usmUserName, usmUserSecurityName, + usmUserAuthProtocol, usmUserAuthKeyLocalized, + usmUserPrivProtocol, + usmUserPrivKeyLocalized) = self.__cloneUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + msgAuthoritativeEngineID, msgUserName + ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cloned user info') + except NoSuchInstanceError: __reportUnknownName = 1 + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %r msgUserName %r' % (msgAuthoritativeEngineID, msgUserName)) if __reportUnknownName: usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 raise error.StatusInformation( - errorIndication = errind.unknownSecurityName, - oid = usmStatsUnknownUserNames.name, - val = usmStatsUnknownUserNames.syntax, + errorIndication=errind.unknownSecurityName, + oid=usmStatsUnknownUserNames.name, + val=usmStatsUnknownUserNames.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) + ) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInGenErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax = snmpInGenErrs.syntax + 1 - raise error.StatusInformation( - errorIndication=errind.invalidMsg - ) + raise error.StatusInformation(errorIndication=errind.invalidMsg) else: # empty username used for engineID discovery usmUserName = usmUserSecurityName = null @@ -795,7 +675,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) + ) # 3.2.6 if securityLevel == 3 or securityLevel == 2: @@ -803,19 +683,21 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): authHandler = self.authServices[usmUserAuthProtocol] else: raise error.StatusInformation( - errorIndication = errind.authenticationFailure - ) + errorIndication=errind.authenticationFailure + ) + try: authenticatedWholeMsg = authHandler.authenticateIncomingMsg( usmUserAuthKeyLocalized, securityParameters.getComponentByPosition(4), wholeMsg - ) + ) + except error.StatusInformation: usmStatsWrongDigests, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsWrongDigests') usmStatsWrongDigests.syntax = usmStatsWrongDigests.syntax+1 raise error.StatusInformation( - errorIndication = errind.authenticationFailure, + errorIndication=errind.authenticationFailure, oid=usmStatsWrongDigests.name, val=usmStatsWrongDigests.syntax, securityStateReference=securityStateReference, @@ -823,7 +705,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) + ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authenticated') @@ -834,14 +716,12 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): securityParameters.getComponentByPosition(2), securityParameters.getComponentByPosition(2), int(time.time()) - ) + ) expireAt = int(self.__expirationTimer + 300 / snmpEngine.transportDispatcher.getTimerResolution()) if expireAt not in self.__timelineExpQueue: self.__timelineExpQueue[expireAt] = [] - self.__timelineExpQueue[expireAt].append( - msgAuthoritativeEngineID - ) + self.__timelineExpQueue[expireAt].append(msgAuthoritativeEngineID) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: store timeline for securityEngineID %r' % (msgAuthoritativeEngineID,)) @@ -849,8 +729,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): if securityLevel == 3 or securityLevel == 2: if msgAuthoritativeEngineID == snmpEngineID: # Authoritative SNMP engine: use local notion (SF bug #1649032) - ( snmpEngineBoots, - snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') + (snmpEngineBoots, snmpEngineTime) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') snmpEngineBoots = snmpEngineBoots.syntax snmpEngineTime = snmpEngineTime.syntax.clone() idleTime = 0 @@ -858,12 +737,11 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): else: # Non-authoritative SNMP engine: use cached estimates if msgAuthoritativeEngineID in self.__timeline: - ( snmpEngineBoots, - snmpEngineTime, - latestReceivedEngineTime, - latestUpdateTimestamp ) = self.__timeline[ - msgAuthoritativeEngineID - ] + (snmpEngineBoots, snmpEngineTime, + latestReceivedEngineTime, + latestUpdateTimestamp ) = self.__timeline[ + msgAuthoritativeEngineID + ] # time passed since last talk with this SNMP engine idleTime = int(time.time())-latestUpdateTimestamp debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read timeline snmpEngineBoots %s snmpEngineTime %s for msgAuthoritativeEngineID %r, idle time %s secs' % (snmpEngineBoots, snmpEngineTime, msgAuthoritativeEngineID, idleTime)) @@ -879,7 +757,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): usmStatsNotInTimeWindows, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsNotInTimeWindows') usmStatsNotInTimeWindows.syntax = usmStatsNotInTimeWindows.syntax+1 raise error.StatusInformation( - errorIndication = errind.notInTimeWindow, + errorIndication=errind.notInTimeWindow, oid=usmStatsNotInTimeWindows.name, val=usmStatsNotInTimeWindows.syntax, securityStateReference=securityStateReference, @@ -887,37 +765,35 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) + ) # 3.2.7b else: # 3.2.7b.1 if msgAuthoritativeEngineBoots > snmpEngineBoots or \ - msgAuthoritativeEngineBoots == snmpEngineBoots and \ - msgAuthoritativeEngineTime > latestReceivedEngineTime: + msgAuthoritativeEngineBoots == snmpEngineBoots and \ + msgAuthoritativeEngineTime > latestReceivedEngineTime: self.__timeline[msgAuthoritativeEngineID] = ( msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineTime, int(time.time()) - ) + ) expireAt = int(self.__expirationTimer + 300 / snmpEngine.transportDispatcher.getTimerResolution()) if expireAt not in self.__timelineExpQueue: self.__timelineExpQueue[expireAt] = [] - self.__timelineExpQueue[expireAt].append( - msgAuthoritativeEngineID - ) + self.__timelineExpQueue[expireAt].append(msgAuthoritativeEngineID) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineID %r' % (msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineID)) # 3.2.7b.2 if snmpEngineBoots == 2147483647 or \ - msgAuthoritativeEngineBoots < snmpEngineBoots or \ - msgAuthoritativeEngineBoots == snmpEngineBoots and \ + msgAuthoritativeEngineBoots < snmpEngineBoots or \ + msgAuthoritativeEngineBoots == snmpEngineBoots and \ abs(idleTime + int(snmpEngineTime) - \ int(msgAuthoritativeEngineTime)) > 150: raise error.StatusInformation( - errorIndication = errind.notInTimeWindow - ) + errorIndication=errind.notInTimeWindow + ) # 3.2.8a if securityLevel == 3: @@ -925,28 +801,29 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): privHandler = self.privServices[usmUserPrivProtocol] else: raise error.StatusInformation( - errorIndication = errind.decryptionError - ) + errorIndication=errind.decryptionError + ) encryptedPDU = scopedPduData.getComponentByPosition(1) if encryptedPDU is None: # no ciphertext raise error.StatusInformation( - errorIndication = errind.decryptionError - ) + errorIndication=errind.decryptionError + ) try: decryptedData = privHandler.decryptData( usmUserPrivKeyLocalized, - ( securityParameters.getComponentByPosition(1), - securityParameters.getComponentByPosition(2), - securityParameters.getComponentByPosition(5) ), - encryptedPDU - ) + (securityParameters.getComponentByPosition(1), + securityParameters.getComponentByPosition(2), + securityParameters.getComponentByPosition(5)), + encryptedPDU + ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: PDU deciphered into %s' % debug.hexdump(decryptedData)) + except error.StatusInformation: usmStatsDecryptionErrors, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsDecryptionErrors') usmStatsDecryptionErrors.syntax = usmStatsDecryptionErrors.syntax+1 raise error.StatusInformation( - errorIndication = errind.decryptionError, + errorIndication=errind.decryptionError, oid=usmStatsDecryptionErrors.name, val=usmStatsDecryptionErrors.syntax, securityStateReference=securityStateReference, @@ -954,17 +831,17 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) + ) scopedPduSpec = scopedPduData.setComponentByPosition(0).getComponentByPosition(0) try: - scopedPDU, rest = decoder.decode( - decryptedData, asn1Spec=scopedPduSpec - ) + scopedPDU, rest = decoder.decode(decryptedData, + asn1Spec=scopedPduSpec) + except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoder failed %s' % sys.exc_info()[0]) raise error.StatusInformation( - errorIndication = errind.decryptionError - ) + errorIndication=errind.decryptionError + ) if eoo.endOfOctets.isSameTypeWith(scopedPDU): raise error.StatusInformation( @@ -975,8 +852,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): scopedPDU = scopedPduData.getComponentByPosition(0) if scopedPDU is None: # no plaintext raise error.StatusInformation( - errorIndication = errind.decryptionError - ) + errorIndication=errind.decryptionError + ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoded %s' % scopedPDU.prettyPrint()) @@ -1000,14 +877,11 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, PDU=scopedPDU - ) + ) # 3.2.12 - return ( msgAuthoritativeEngineID, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) + return (msgAuthoritativeEngineID, securityName, scopedPDU, + maxSizeResponseScopedPDU, securityStateReference) def __expireTimelineInfo(self): if self.__expirationTimer in self.__timelineExpQueue: @@ -1016,7 +890,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): del self.__timeline[engineIdKey] debug.logger & debug.flagSM and debug.logger('__expireTimelineInfo: expiring %r' % (engineIdKey,)) del self.__timelineExpQueue[self.__expirationTimer] - self.__expirationTimer = self.__expirationTimer + 1 + self.__expirationTimer += 1 def receiveTimerTick(self, snmpEngine, timeNow): self.__expireTimelineInfo() diff --git a/pysnmp/proto/secmod/rfc3826/priv/aes.py b/pysnmp/proto/secmod/rfc3826/priv/aes.py index 264ae72a..2d860d89 100644 --- a/pysnmp/proto/secmod/rfc3826/priv/aes.py +++ b/pysnmp/proto/secmod/rfc3826/priv/aes.py @@ -22,40 +22,36 @@ class Aes(base.AbstractEncryptionService): _localInt = random.randrange(0, 0xffffffffffffffff) # 3.1.2.1 def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime): - salt = [ - self._localInt>>56&0xff, - self._localInt>>48&0xff, - self._localInt>>40&0xff, - self._localInt>>32&0xff, - self._localInt>>24&0xff, - self._localInt>>16&0xff, - self._localInt>>8&0xff, - self._localInt&0xff - ] + salt = [self._localInt>>56&0xff, + self._localInt>>48&0xff, + self._localInt>>40&0xff, + self._localInt>>32&0xff, + self._localInt>>24&0xff, + self._localInt>>16&0xff, + self._localInt>>8&0xff, + self._localInt&0xff] if self._localInt == 0xffffffffffffffff: self._localInt = 0 else: - self._localInt = self._localInt + 1 + self._localInt += 1 - return self.__getDecryptionKey( - privKey, snmpEngineBoots, snmpEngineTime, salt - ) + ( univ.OctetString(salt).asOctets(), ) + return self.__getDecryptionKey(privKey, snmpEngineBoots, snmpEngineTime, salt) + (univ.OctetString(salt).asOctets(),) def __getDecryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime, salt): snmpEngineBoots, snmpEngineTime, salt = ( int(snmpEngineBoots), int(snmpEngineTime), salt - ) + ) - iv = [ snmpEngineBoots>>24&0xff, - snmpEngineBoots>>16&0xff, - snmpEngineBoots>>8&0xff, - snmpEngineBoots&0xff, - snmpEngineTime>>24&0xff, - snmpEngineTime>>16&0xff, - snmpEngineTime>>8&0xff, - snmpEngineTime&0xff ] + salt + iv = [snmpEngineBoots>>24&0xff, + snmpEngineBoots>>16&0xff, + snmpEngineBoots>>8&0xff, + snmpEngineBoots&0xff, + snmpEngineTime>>24&0xff, + snmpEngineTime>>16&0xff, + snmpEngineTime>>8&0xff, + snmpEngineTime&0xff] + salt return privKey[:self.keySize].asOctets(), univ.OctetString(iv).asOctets() @@ -67,7 +63,7 @@ class Aes(base.AbstractEncryptionService): else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) + ) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: @@ -77,7 +73,7 @@ class Aes(base.AbstractEncryptionService): else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) + ) return localPrivKey[:16] # 3.2.4.1 @@ -85,14 +81,14 @@ class Aes(base.AbstractEncryptionService): if AES is None: raise error.StatusInformation( errorIndication=errind.encryptionError - ) + ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 3.3.1.1 aesKey, iv, salt = self.__getEncryptionKey( encryptKey, snmpEngineBoots, snmpEngineTime - ) + ) # 3.3.1.3 aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128) @@ -110,7 +106,7 @@ class Aes(base.AbstractEncryptionService): if AES is None: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) snmpEngineBoots, snmpEngineTime, salt = privParameters @@ -118,12 +114,12 @@ class Aes(base.AbstractEncryptionService): if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) # 3.3.2.3 aesKey, iv = self.__getDecryptionKey( decryptKey, snmpEngineBoots, snmpEngineTime, salt - ) + ) aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128) diff --git a/pysnmp/smi/instrum.py b/pysnmp/smi/instrum.py index 922f7e4b..080592b1 100644 --- a/pysnmp/smi/instrum.py +++ b/pysnmp/smi/instrum.py @@ -65,20 +65,11 @@ class MibInstrumController(AbstractMibInstrumController): if self.lastBuildId == self.mibBuilder.lastBuildId: return - ( MibScalarInstance, - MibScalar, - MibTableColumn, - MibTableRow, - MibTable, - MibTree ) = self.mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance', - 'MibScalar', - 'MibTableColumn', - 'MibTableRow', - 'MibTable', - 'MibTree' - ) + (MibScalarInstance, MibScalar, MibTableColumn, MibTableRow, MibTable, + MibTree) = self.mibBuilder.importSymbols( + 'SNMPv2-SMI', 'MibScalarInstance', 'MibScalar', + 'MibTableColumn', 'MibTableRow', 'MibTable', 'MibTree' + ) mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') @@ -246,7 +237,9 @@ class MibInstrumController(AbstractMibInstrumController): def readVars(self, vars, acInfo=(None, None)): return self.flipFlopFsm(self.fsmReadVar, vars, acInfo) + def readNextVars(self, vars, acInfo=(None, None)): return self.flipFlopFsm(self.fsmReadNextVar, vars, acInfo) + def writeVars(self, vars, acInfo=(None, None)): return self.flipFlopFsm(self.fsmWriteVar, vars, acInfo) diff --git a/pysnmp/smi/mibs/SNMPv2-SMI.py b/pysnmp/smi/mibs/SNMPv2-SMI.py index 49883460..86380ac3 100644 --- a/pysnmp/smi/mibs/SNMPv2-SMI.py +++ b/pysnmp/smi/mibs/SNMPv2-SMI.py @@ -15,9 +15,9 @@ Integer, ObjectIdentifier = mibBuilder.importSymbols( (ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint) = mibBuilder.importSymbols( - "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", - "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" -) + "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", + "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" + ) # syntax of objects @@ -370,9 +370,9 @@ class MibTree(ObjectType): (acFun, acCtx) = acInfo if name == self.name: if acFun: - if self.maxAccess not in ( - 'readonly', 'readwrite','readcreate' - ) or acFun(name, self.syntax, idx, 'read', acCtx): + if self.maxAccess not in ('readonly', + 'readwrite','readcreate') or \ + acFun(name, self.syntax, idx, 'read', acCtx): raise error.NoAccessError(idx=idx, name=name) else: try: @@ -786,7 +786,7 @@ class MibTableColumn(MibScalar): return self.__createdInstances[name] = self.protoInstance( self.name, name[len(self.name):], self.syntax.clone() - ) + ) self.__createdInstances[name].createTest(name, val, idx, acInfo) def createCommit(self, name, val, idx, acInfo): @@ -805,9 +805,8 @@ class MibTableColumn(MibScalar): self.branchVersionId += 1 if name in self.__createdInstances: if self.__createdInstances[name] is not None: - self.__createdInstances[name].createCleanup( - name, val, idx, acInfo - ) + self.__createdInstances[name].createCleanup(name, val, idx, + acInfo) del self.__createdInstances[name] elif name in self._vars: self._vars[name].createCleanup(name, val, idx, acInfo) @@ -855,9 +854,8 @@ class MibTableColumn(MibScalar): # Drop instance copy self.branchVersionId += 1 if name in self.__destroyedInstances: - self.__destroyedInstances[name].destroyCleanup( - name, val, idx, acInfo - ) + self.__destroyedInstances[name].destroyCleanup(name, val, + idx, acInfo) debug.logger & debug.flagIns and debug.logger('destroyCleanup: %s=%r' % (name, val)) del self.__destroyedInstances[name] @@ -865,9 +863,7 @@ class MibTableColumn(MibScalar): # Set back column instance if name in self.__destroyedInstances: self._vars[name] = self.__destroyedInstances[name] - self._vars[name].destroyUndo( - name, val, idx, acInfo - ) + self._vars[name].destroyUndo(name, val, idx, acInfo) del self.__destroyedInstances[name] # Set/modify column @@ -876,9 +872,7 @@ class MibTableColumn(MibScalar): # Besides common checks, request row creation on no-instance try: # First try the instance - MibScalar.writeTest( - self, name, val, idx, acInfo - ) + MibScalar.writeTest(self, name, val, idx, acInfo) # ...otherwise proceed with creating new column except (error.NoSuchInstanceError, error.RowCreationWanted): self.__rowOpWanted[name] = error.RowCreationWanted() @@ -892,31 +886,21 @@ class MibTableColumn(MibScalar): def __delegateWrite(self, subAction, name, val, idx, acInfo): if name not in self.__rowOpWanted: - getattr(MibScalar, 'write'+subAction)( - self, name, val, idx, acInfo - ) + getattr(MibScalar, 'write'+subAction)(self, name, val, idx, acInfo) return if isinstance(self.__rowOpWanted[name], error.RowCreationWanted): - getattr(self, 'create'+subAction)( - name, val, idx, acInfo - ) + getattr(self, 'create'+subAction)(name, val, idx, acInfo) if isinstance(self.__rowOpWanted[name], error.RowDestructionWanted): - getattr(self, 'destroy'+subAction)( - name, val, idx, acInfo - ) + getattr(self, 'destroy'+subAction)(name, val, idx, acInfo) def writeCommit(self, name, val, idx, acInfo): - self.__delegateWrite( - 'Commit', name, val, idx, acInfo - ) + self.__delegateWrite('Commit', name, val, idx, acInfo) if name in self.__rowOpWanted: raise self.__rowOpWanted[name] def writeCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 - self.__delegateWrite( - 'Cleanup', name, val, idx, acInfo - ) + self.__delegateWrite('Cleanup', name, val, idx, acInfo) if name in self.__rowOpWanted: e = self.__rowOpWanted[name] del self.__rowOpWanted[name] @@ -924,9 +908,7 @@ class MibTableColumn(MibScalar): raise e def writeUndo(self, name, val, idx, acInfo): - self.__delegateWrite( - 'Undo', name, val, idx, acInfo - ) + self.__delegateWrite('Undo', name, val, idx, acInfo) if name in self.__rowOpWanted: e = self.__rowOpWanted[name] del self.__rowOpWanted[name] @@ -1015,18 +997,14 @@ class MibTableRow(MibTree): baseIndices = [] for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) - syntax, instId = self.setFromName( - mibObj.syntax, instId, impliedFlag - ) + syntax, instId = self.setFromName(mibObj.syntax, instId, + impliedFlag) if self.name == mibObj.name[:-1]: baseIndices.append((mibObj.name, syntax)) if instId: - raise error.SmiError( - 'Excessive instance identifier sub-OIDs left at %s: %s' % - (self, instId) - ) + raise error.SmiError('Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId)) if not baseIndices: return @@ -1077,9 +1055,8 @@ class MibTableRow(MibTree): instId = nameSuffix for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) - syntax, instId = self.setFromName( - mibObj.syntax, instId, impliedFlag - ) + syntax, instId = self.setFromName(mibObj.syntax, instId, + impliedFlag) indexVals[mibObj.name] = syntax for name, var in self._vars.items(): diff --git a/pysnmp/smi/mibs/SNMPv2-TC.py b/pysnmp/smi/mibs/SNMPv2-TC.py index 23ca95c4..81d0796d 100644 --- a/pysnmp/smi/mibs/SNMPv2-TC.py +++ b/pysnmp/smi/mibs/SNMPv2-TC.py @@ -13,9 +13,9 @@ NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") (ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint) = mibBuilder.importSymbols( - "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", - "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" -) + "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", + "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" + ) Counter32, Unsigned32, TimeTicks, Counter64 = mibBuilder.importSymbols( 'SNMPv2-SMI', 'Counter32', 'Unsigned32', 'TimeTicks', 'Counter64' @@ -54,13 +54,11 @@ class TextualConvention: def prettyOut(self, value): # override asn1 type method """Implements DISPLAY-HINT evaluation""" - if self.displayHint and ( - self.__integer.isSuperTypeOf(self) or - self.__unsigned32.isSuperTypeOf(self) or - self.__timeticks.isSuperTypeOf(self) or - self.__counter32.isSuperTypeOf(self) or - self.__counter64.isSuperTypeOf(self) - ): + if self.displayHint and (self.__integer.isSuperTypeOf(self) or + self.__unsigned32.isSuperTypeOf(self) or + self.__timeticks.isSuperTypeOf(self) or + self.__counter32.isSuperTypeOf(self) or + self.__counter64.isSuperTypeOf(self)): _ = lambda t, f=0: (t, f) t, f = _(*self.displayHint.split('-')) if t == 'x': diff --git a/pysnmp/smi/view.py b/pysnmp/smi/view.py index 0b4800e1..df28c2cb 100644 --- a/pysnmp/smi/view.py +++ b/pysnmp/smi/view.py @@ -4,7 +4,7 @@ from pysnmp.smi.indices import OrderedDict, OidOrderedDict from pysnmp.smi import error from pysnmp import debug -__all__ = [ 'MibViewController' ] +__all__ = ['MibViewController'] if sys.version_info[0] <= 2: import types @@ -29,7 +29,7 @@ class MibViewController: MibScalarInstance, = self.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance' - ) + ) # # Create indices @@ -55,7 +55,7 @@ class MibViewController: modNames.sort(key=__sortFun) # Index modules names - for modName in [ '' ] + modNames: + for modName in [''] + modNames: # Modules index self.__mibSymbolsIdx[modName] = mibMod = { 'oidToLabelIdx': OidOrderedDict(), @@ -63,7 +63,7 @@ class MibViewController: 'varToNameIdx': {}, 'typeToModIdx': OrderedDict(), 'oidToModIdx': {} - } + } if not modName: globMibMod = mibMod @@ -78,7 +78,7 @@ class MibViewController: raise error.SmiError( 'Duplicate SMI type %s::%s, has %s' % \ (modName, n, mibMod['typeToModIdx'][n]) - ) + ) globMibMod['typeToModIdx'][n] = modName mibMod['typeToModIdx'][n] = modName elif isinstance(v, instanceTypes): @@ -88,7 +88,7 @@ class MibViewController: raise error.SmiError( 'Duplicate MIB variable %s::%s has %s' % \ (modName, n, mibMod['varToNameIdx'][n]) - ) + ) globMibMod['varToNameIdx'][n] = v.name mibMod['varToNameIdx'][n] = v.name # Potentionally ambiguous mapping ahead @@ -99,7 +99,7 @@ class MibViewController: else: raise error.SmiError( 'Unexpected object %s::%s' % (modName, n) - ) + ) # Build oid->long-label index oidToLabelIdx = self.__mibSymbolsIdx['']['oidToLabelIdx'] @@ -162,7 +162,7 @@ class MibViewController: except KeyError: raise error.SmiError( 'No module next to %s at %s' % (modName, self) - ) + ) # MIB tree node management @@ -178,7 +178,7 @@ class MibViewController: return nodeName, nodeName, () oid, label, suffix = self.__getOidLabel( nodeName[:-1], oidToLabelIdx, labelToOidIdx - ) + ) suffix = suffix + nodeName[-1:] resLabel = label + tuple([ str(x) for x in suffix ]) if resLabel in labelToOidIdx: @@ -193,17 +193,15 @@ class MibViewController: if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) + raise error.SmiError('No module %s at %s' % (modName, self)) oid, label, suffix = self.__getOidLabel( nodeName, mibMod['oidToLabelIdx'], mibMod['labelToOidIdx'] - ) + ) if oid == label: raise error.NoSuchObjectError( str='Can\'t resolve node name %s::%s at %s' % (modName, nodeName, self) - ) + ) debug.logger & debug.flagMIB and debug.logger('getNodeNameByOid: resolved %s:%s -> %s.%s' % (modName, nodeName, label, suffix)) return oid, label, suffix @@ -212,15 +210,13 @@ class MibViewController: if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) + raise error.SmiError('No module %s at %s' % (modName, self)) if nodeName in mibMod['varToNameIdx']: oid = mibMod['varToNameIdx'][nodeName] else: raise error.NoSuchObjectError( str='No such symbol %s::%s at %s' % (modName, nodeName, self) - ) + ) debug.logger & debug.flagMIB and debug.logger('getNodeNameByDesc: resolved %s:%s -> %s' % (modName, nodeName, oid)) return self.getNodeNameByOid(oid, modName) @@ -232,22 +228,16 @@ class MibViewController: return self.getNodeNameByOid(nodeName, modName) except error.NoSuchObjectError: # ...on failure, try as MIB symbol - oid, label, suffix = self.getNodeNameByDesc( - nodeName[0], modName - ) + oid, label, suffix = self.getNodeNameByDesc(nodeName[0], modName) # ...with trailing suffix - return self.getNodeNameByOid( - oid + suffix + nodeName[1:], modName - ) + return self.getNodeNameByOid(oid + suffix + nodeName[1:], modName) def getOrderedNodeName(self, index, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) + raise error.SmiError('No module %s at %s' % (modName, self)) if not mibMod['oidToLabelIdx']: raise error.NoSuchObjectError( str='No variables at MIB module %s at %s' % (modName, self) @@ -275,7 +265,7 @@ class MibViewController: except KeyError: raise error.NoSuchObjectError( str='No name next to %s::%s at %s' % (modName, nodeName, self) - ) + ) def getParentNodeName(self, nodeName, modName=''): oid, label, suffix = self.getNodeName(nodeName, modName) @@ -283,7 +273,7 @@ class MibViewController: raise error.NoSuchObjectError( str='No parent name for %s::%s at %s' % (modName, nodeName, self) - ) + ) return oid[:-1], label[:-1], oid[-1:] + suffix def getNodeLocation(self, nodeName, modName=''): @@ -299,13 +289,13 @@ class MibViewController: else: raise error.SmiError( 'No module %s at %s' % (modName, self) - ) + ) if typeName in mibMod['typeToModIdx']: m = mibMod['typeToModIdx'][typeName] else: raise error.NoSuchObjectError( str='No such type %s::%s at %s' % (modName, typeName, self) - ) + ) return m, typeName def getOrderedTypeName(self, index, modName=''): @@ -313,13 +303,11 @@ class MibViewController: if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) + raise error.SmiError('No module %s at %s' % (modName, self)) if not mibMod['typeToModIdx']: raise error.NoSuchObjectError( str='No types at MIB module %s at %s' % (modName, self) - ) + ) t = mibMod['typeToModIdx'].keys()[index] return mibMod['typeToModIdx'][t], t @@ -336,4 +324,4 @@ class MibViewController: except KeyError: raise error.NoSuchObjectError( str='No type next to %s::%s at %s' % (modName, typeName, self) - ) + ) |