From 90bbf397ad3dd49db7f83d541afff51f17e63054 Mon Sep 17 00:00:00 2001 From: Ilya Etingof Date: Sat, 2 Apr 2016 23:43:14 +0200 Subject: pep8 reformatted --- pysnmp/carrier/asyncio/base.py | 1 + pysnmp/carrier/asyncio/dgram/base.py | 8 +- pysnmp/carrier/asyncio/dgram/udp.py | 4 + pysnmp/carrier/asyncio/dgram/udp6.py | 6 +- pysnmp/carrier/asyncio/dispatch.py | 9 +- pysnmp/carrier/asyncore/base.py | 10 +- pysnmp/carrier/asyncore/dgram/base.py | 30 +++--- pysnmp/carrier/asyncore/dgram/udp.py | 3 + pysnmp/carrier/asyncore/dgram/udp6.py | 5 +- pysnmp/carrier/asyncore/dgram/unix.py | 11 +- pysnmp/carrier/asyncore/dispatch.py | 3 +- pysnmp/carrier/base.py | 31 +++--- pysnmp/carrier/error.py | 1 + pysnmp/carrier/sockfix.py | 8 +- pysnmp/carrier/twisted/base.py | 5 +- pysnmp/carrier/twisted/dgram/base.py | 1 + pysnmp/carrier/twisted/dgram/udp.py | 12 ++- pysnmp/carrier/twisted/dgram/unix.py | 9 +- pysnmp/carrier/twisted/dispatch.py | 2 + pysnmp/entity/config.py | 126 ++++++++++++++++------ pysnmp/entity/engine.py | 39 ++++--- pysnmp/entity/observer.py | 4 +- pysnmp/entity/rfc3413/cmdgen.py | 80 +++++++++----- pysnmp/entity/rfc3413/cmdrsp.py | 48 ++++++--- pysnmp/entity/rfc3413/config.py | 32 +++--- pysnmp/entity/rfc3413/context.py | 21 ++-- pysnmp/entity/rfc3413/mibvar.py | 33 +++--- pysnmp/entity/rfc3413/ntforg.py | 87 +++++++++++----- pysnmp/entity/rfc3413/ntfrcv.py | 19 ++-- pysnmp/entity/rfc3413/oneliner/cmdgen.py | 22 ++-- pysnmp/entity/rfc3413/oneliner/ntforg.py | 25 +++-- pysnmp/hlapi/__init__.py | 6 ++ pysnmp/hlapi/asyncio/__init__.py | 6 ++ pysnmp/hlapi/asyncio/cmdgen.py | 15 ++- pysnmp/hlapi/asyncio/ntforg.py | 3 + pysnmp/hlapi/asyncio/transport.py | 13 ++- pysnmp/hlapi/asyncore/__init__.py | 6 ++ pysnmp/hlapi/asyncore/cmdgen.py | 15 ++- pysnmp/hlapi/asyncore/ntforg.py | 14 +-- pysnmp/hlapi/asyncore/sync/__init__.py | 6 ++ pysnmp/hlapi/asyncore/sync/cmdgen.py | 44 +++++--- pysnmp/hlapi/asyncore/sync/compat/cmdgen.py | 42 ++++---- pysnmp/hlapi/asyncore/sync/compat/ntforg.py | 5 +- pysnmp/hlapi/asyncore/sync/ntforg.py | 4 + pysnmp/hlapi/asyncore/transport.py | 14 ++- pysnmp/hlapi/auth.py | 9 +- pysnmp/hlapi/context.py | 2 + pysnmp/hlapi/lcd.py | 28 +++-- pysnmp/hlapi/transport.py | 6 +- pysnmp/hlapi/varbinds.py | 7 +- pysnmp/proto/acmod/rfc3415.py | 28 +++-- pysnmp/proto/api/__init__.py | 6 ++ pysnmp/proto/api/v1.py | 131 +++++++++++++++-------- pysnmp/proto/api/v2c.py | 42 +++++--- pysnmp/proto/api/verdec.py | 1 + pysnmp/proto/mpmod/base.py | 4 +- pysnmp/proto/mpmod/cache.py | 6 +- pysnmp/proto/mpmod/rfc2576.py | 91 +++++++++------- pysnmp/proto/mpmod/rfc3412.py | 156 +++++++++++++++++----------- pysnmp/proto/proxy/rfc2576.py | 51 +++++---- pysnmp/proto/rfc1157.py | 12 +-- pysnmp/proto/rfc1901.py | 4 +- pysnmp/proto/rfc1905.py | 12 +-- pysnmp/proto/secmod/eso/priv/aes192.py | 1 + pysnmp/proto/secmod/eso/priv/aes256.py | 1 + pysnmp/proto/secmod/eso/priv/aesbase.py | 13 ++- pysnmp/proto/secmod/eso/priv/des3.py | 70 +++++++------ pysnmp/proto/secmod/rfc3414/auth/base.py | 1 + 68 files changed, 1029 insertions(+), 541 deletions(-) diff --git a/pysnmp/carrier/asyncio/base.py b/pysnmp/carrier/asyncio/base.py index 002239bb..217092a6 100644 --- a/pysnmp/carrier/asyncio/base.py +++ b/pysnmp/carrier/asyncio/base.py @@ -33,6 +33,7 @@ from pysnmp.carrier.asyncio.dispatch import AsyncioDispatcher from pysnmp.carrier.base import AbstractTransport + class AbstractAsyncioTransport(AbstractTransport): protoTransportDispatcher = AsyncioDispatcher """Base Asyncio Transport, to be used with AsyncioDispatcher""" diff --git a/pysnmp/carrier/asyncio/dgram/base.py b/pysnmp/carrier/asyncio/dgram/base.py index 5c3b78b6..3abcc3a3 100644 --- a/pysnmp/carrier/asyncio/dgram/base.py +++ b/pysnmp/carrier/asyncio/dgram/base.py @@ -35,6 +35,7 @@ import traceback from pysnmp.carrier.asyncio.base import AbstractAsyncioTransport from pysnmp.carrier import error from pysnmp import debug + try: import asyncio except ImportError: @@ -42,14 +43,16 @@ except ImportError: loop = asyncio.get_event_loop() + class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport): """Base Asyncio datagram Transport, to be used with AsyncioDispatcher""" sockFamily = None addressType = lambda x: x transport = None - def __init__(self, *args, **kwargs): + def __init__(self, sock=None, sockMap=None): self._writeQ = [] + self._lport = None def datagram_received(self, datagram, transportAddress): if self._cbFun is None: @@ -95,7 +98,8 @@ class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport): return self def closeTransport(self): - self._lport.cancel() + if self._lport is not None: + self._lport.cancel() if self.transport is not None: self.transport.close() AbstractAsyncioTransport.closeTransport(self) diff --git a/pysnmp/carrier/asyncio/dgram/udp.py b/pysnmp/carrier/asyncio/dgram/udp.py index aa73fb10..f80de36b 100644 --- a/pysnmp/carrier/asyncio/dgram/udp.py +++ b/pysnmp/carrier/asyncio/dgram/udp.py @@ -33,6 +33,7 @@ import socket from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncio.dgram.base import DgramAsyncioProtocol + try: import asyncio except ImportError: @@ -42,11 +43,14 @@ loop = asyncio.get_event_loop() domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) + class UdpTransportAddress(tuple, AbstractTransportAddress): pass + class UdpAsyncioTransport(DgramAsyncioProtocol): sockFamily = socket.AF_INET addressType = UdpTransportAddress + UdpTransport = UdpAsyncioTransport diff --git a/pysnmp/carrier/asyncio/dgram/udp6.py b/pysnmp/carrier/asyncio/dgram/udp6.py index ad3c28dd..290c03bd 100644 --- a/pysnmp/carrier/asyncio/dgram/udp6.py +++ b/pysnmp/carrier/asyncio/dgram/udp6.py @@ -7,6 +7,7 @@ import socket from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncio.dgram.base import DgramAsyncioProtocol + try: import asyncio except ImportError: @@ -16,9 +17,11 @@ loop = asyncio.get_event_loop() domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2) + class Udp6TransportAddress(tuple, AbstractTransportAddress): pass + class Udp6AsyncioTransport(DgramAsyncioProtocol): sockFamily = socket.has_ipv6 and socket.AF_INET6 or None addressType = Udp6TransportAddress @@ -28,9 +31,10 @@ class Udp6AsyncioTransport(DgramAsyncioProtocol): return self.addressType((transportAddress[0].split('%')[0], transportAddress[1], 0, # flowinfo - 0)) # scopeid + 0)) # scopeid else: 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 0cfa4ceb..cb4c0941 100644 --- a/pysnmp/carrier/asyncio/dispatch.py +++ b/pysnmp/carrier/asyncio/dispatch.py @@ -34,6 +34,7 @@ import sys import traceback from pysnmp.carrier.base import AbstractTransportDispatcher from pysnmp.error import PySnmpError + try: import asyncio except ImportError: @@ -41,8 +42,10 @@ except ImportError: loop = asyncio.get_event_loop() + class AsyncioDispatcher(AbstractTransportDispatcher): """AsyncioDispatcher based on asyncio event loop""" + def __init__(self, *args, **kwargs): AbstractTransportDispatcher.__init__(self) self.__transportCount = 0 @@ -70,7 +73,7 @@ class AsyncioDispatcher(AbstractTransportDispatcher): self.loopingcall = asyncio.async(self.handle_timeout()) AbstractTransportDispatcher.registerTransport( self, tDomain, transport - ) + ) self.__transportCount += 1 def unregisterTransport(self, tDomain): @@ -84,9 +87,10 @@ class AsyncioDispatcher(AbstractTransportDispatcher): self.loopingcall.cancel() self.loopingcall = None + # Trollius or Tulip? if not hasattr(asyncio, "From"): - exec("""\ + exec ("""\ @asyncio.coroutine def handle_timeout(self): while True: @@ -94,4 +98,3 @@ def handle_timeout(self): self.handleTimerTick(loop.time()) AsyncioDispatcher.handle_timeout = handle_timeout\ """) - diff --git a/pysnmp/carrier/asyncore/base.py b/pysnmp/carrier/asyncore/base.py index da68774d..04044775 100644 --- a/pysnmp/carrier/asyncore/base.py +++ b/pysnmp/carrier/asyncore/base.py @@ -4,13 +4,15 @@ # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # -import socket, sys +import socket +import sys import asyncore from pysnmp.carrier import error from pysnmp.carrier.base import AbstractTransport from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp import debug + class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): protoTransportDispatcher = AsyncoreDispatcher sockFamily = sockType = None @@ -25,11 +27,11 @@ class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): if self.sockFamily is None: raise error.CarrierError( 'Address family %s not supported' % self.__class__.__name__ - ) + ) if self.sockType is None: raise error.CarrierError( 'Socket type %s not supported' % self.__class__.__name__ - ) + ) try: sock = socket.socket(self.sockFamily, self.sockType) except socket.error: @@ -42,7 +44,7 @@ class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): sock.setsockopt(socket.SOL_SOCKET, b, self.bufferSize) debug.logger & debug.flagIO and debug.logger('%s: socket %d buffer size increased from %d to %d for buffer %d' % (self.__class__.__name__, sock.fileno(), bsize, self.bufferSize, b)) except Exception: - debug.logger & debug.flagIO and debug.logger('%s: socket buffer size option mangling failure for buffer %d: %s' % (self.__class__.__name__, b, sys.exc_info()[1])) + debug.logger & debug.flagIO and debug.logger('%s: socket buffer size option mangling failure for buffer: %s' % (self.__class__.__name__, sys.exc_info()[1])) # The socket map is managed by the AsyncoreDispatcher on # which this transport is registered. Here we just prepare diff --git a/pysnmp/carrier/asyncore/dgram/base.py b/pysnmp/carrier/asyncore/dgram/base.py index c64b7e89..49b7846e 100644 --- a/pysnmp/carrier/asyncore/dgram/base.py +++ b/pysnmp/carrier/asyncore/dgram/base.py @@ -4,7 +4,9 @@ # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # -import socket, errno, sys +import socket +import errno +import sys from pysnmp.carrier.asyncore.base import AbstractSocketTransport from pysnmp.carrier import sockfix, sockmsg, error from pysnmp import debug @@ -21,17 +23,21 @@ if hasattr(errno, 'EBADFD'): # bad FD may happen upon FD closure on n-1 select() event sockErrors[errno.EBADFD] = True + class DgramSocketTransport(AbstractSocketTransport): sockType = socket.SOCK_DGRAM retryCount = 3 retryInterval = 1 addressType = lambda x: x + def __init__(self, sock=None, sockMap=None): self.__outQueue = [] self._sendto = lambda s, b, a: s.sendto(b, a) + def __recvfrom(s, sz): d, a = s.recvfrom(sz) return d, self.addressType(a) + self._recvfrom = __recvfrom AbstractSocketTransport.__init__(self, sock, sockMap) @@ -40,10 +46,11 @@ class DgramSocketTransport(AbstractSocketTransport): try: self.socket.bind(iface) except socket.error: - raise error.CarrierError('bind() for %s failed: %s' % (iface is None and "" or iface, sys.exc_info()[1])) + raise error.CarrierError( + 'bind() for %s failed: %s' % (iface is None and "" or iface, sys.exc_info()[1])) return self - def openServerMode(self, iface=None): + def openServerMode(self, iface): try: self.socket.bind(iface) except socket.error: @@ -62,7 +69,7 @@ class DgramSocketTransport(AbstractSocketTransport): def enablePktInfo(self, flag=1): if not hasattr(self.socket, 'sendmsg') or \ - not hasattr(self.socket, 'recvmsg'): + not hasattr(self.socket, 'recvmsg'): raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version') try: @@ -100,7 +107,7 @@ class DgramSocketTransport(AbstractSocketTransport): def sendMessage(self, outgoingMessage, transportAddress): self.__outQueue.append( (outgoingMessage, self.normalizeAddress(transportAddress)) - ) + ) debug.logger & debug.flagIO and debug.logger('sendMessage: outgoingMessage queued (%d octets) %s' % (len(outgoingMessage), debug.hexdump(outgoingMessage))) def normalizeAddress(self, transportAddress): @@ -114,8 +121,8 @@ class DgramSocketTransport(AbstractSocketTransport): # one evil OS does not seem to support getsockname() for DGRAM sockets try: return self.socket.getsockname() - except: - return ('0.0.0.0', 0) + except Exception: + return '0.0.0.0', 0 # asyncore API def handle_connect(self): @@ -145,11 +152,10 @@ class DgramSocketTransport(AbstractSocketTransport): def handle_read(self): try: - incomingMessage, transportAddress = self._recvfrom( - self.socket, 65535 - ) + incomingMessage, transportAddress = self._recvfrom(self.socket, 65535) transportAddress = self.normalizeAddress(transportAddress) - debug.logger & debug.flagIO and debug.logger('handle_read: transportAddress %r -> %r incomingMessage (%d octets) %s' % (transportAddress, transportAddress.getLocalAddress(), len(incomingMessage), debug.hexdump(incomingMessage))) + debug.logger & debug.flagIO and debug.logger( + 'handle_read: transportAddress %r -> %r incomingMessage (%d octets) %s' % (transportAddress, transportAddress.getLocalAddress(), len(incomingMessage), debug.hexdump(incomingMessage))) if not incomingMessage: self.handle_close() return @@ -165,4 +171,4 @@ class DgramSocketTransport(AbstractSocketTransport): raise error.CarrierError('recvfrom() failed: %s' % (sys.exc_info()[1],)) def handle_close(self): - pass # no datagram connection + pass # no datagram connection diff --git a/pysnmp/carrier/asyncore/dgram/udp.py b/pysnmp/carrier/asyncore/dgram/udp.py index f8b5ac1b..09b783dd 100644 --- a/pysnmp/carrier/asyncore/dgram/udp.py +++ b/pysnmp/carrier/asyncore/dgram/udp.py @@ -10,11 +10,14 @@ from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) + class UdpTransportAddress(tuple, AbstractTransportAddress): pass + class UdpSocketTransport(DgramSocketTransport): sockFamily = AF_INET addressType = UdpTransportAddress + UdpTransport = UdpSocketTransport diff --git a/pysnmp/carrier/asyncore/dgram/udp6.py b/pysnmp/carrier/asyncore/dgram/udp6.py index 947ecd23..c659dc35 100644 --- a/pysnmp/carrier/asyncore/dgram/udp6.py +++ b/pysnmp/carrier/asyncore/dgram/udp6.py @@ -11,9 +11,11 @@ import socket domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2) + class Udp6TransportAddress(tuple, AbstractTransportAddress): pass + class Udp6SocketTransport(DgramSocketTransport): sockFamily = socket.has_ipv6 and socket.AF_INET6 or None addressType = Udp6TransportAddress @@ -22,7 +24,7 @@ class Udp6SocketTransport(DgramSocketTransport): if '%' in transportAddress[0]: # strip zone ID ta = self.addressType((transportAddress[0].split('%')[0], transportAddress[1], - 0, # flowinfo + 0, # flowinfo 0)) # scopeid else: ta = self.addressType((transportAddress[0], @@ -34,4 +36,5 @@ class Udp6SocketTransport(DgramSocketTransport): else: return ta.setLocalAddress(self.getLocalAddress()) + Udp6Transport = Udp6SocketTransport diff --git a/pysnmp/carrier/asyncore/dgram/unix.py b/pysnmp/carrier/asyncore/dgram/unix.py index f8b193eb..7bac79af 100644 --- a/pysnmp/carrier/asyncore/dgram/unix.py +++ b/pysnmp/carrier/asyncore/dgram/unix.py @@ -6,6 +6,7 @@ # import os import random + try: from socket import AF_UNIX except ImportError: @@ -17,12 +18,15 @@ domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) random.seed() + class UnixTransportAddress(str, AbstractTransportAddress): pass + class UnixSocketTransport(DgramSocketTransport): sockFamily = AF_UNIX addressType = UnixTransportAddress + _iface = '' def openClientMode(self, iface=None): if iface is None: @@ -35,21 +39,22 @@ class UnixSocketTransport(DgramSocketTransport): if os.path.exists(iface): os.remove(iface) DgramSocketTransport.openClientMode(self, iface) - self.__iface = iface + self._iface = iface return self def openServerMode(self, iface): DgramSocketTransport.openServerMode(self, iface) - self.__iface = iface + self._iface = iface return self def closeTransport(self): DgramSocketTransport.closeTransport(self) try: - os.remove(self.__iface) + os.remove(self._iface) except OSError: pass + UnixTransport = UnixSocketTransport # Compatibility stub diff --git a/pysnmp/carrier/asyncore/dispatch.py b/pysnmp/carrier/asyncore/dispatch.py index ae602549..78f6dcf8 100644 --- a/pysnmp/carrier/asyncore/dispatch.py +++ b/pysnmp/carrier/asyncore/dispatch.py @@ -12,9 +12,10 @@ from asyncore import loop from pysnmp.carrier.base import AbstractTransportDispatcher from pysnmp.error import PySnmpError + class AsyncoreDispatcher(AbstractTransportDispatcher): def __init__(self): - self.__sockMap = {} # use own map for MT safety + self.__sockMap = {} # use own map for MT safety self.timeout = 0.5 AbstractTransportDispatcher.__init__(self) diff --git a/pysnmp/carrier/base.py b/pysnmp/carrier/base.py index 3aa2de4e..653ea3fe 100644 --- a/pysnmp/carrier/base.py +++ b/pysnmp/carrier/base.py @@ -6,6 +6,7 @@ # from pysnmp.carrier import error + class TimerCallable: def __init__(self, cbFun, callInterval): self.__cbFun = cbFun @@ -35,6 +36,7 @@ class TimerCallable: def __ge__(self, cbFun): return self.__cbFun >= cbFun + class AbstractTransportDispatcher: def __init__(self): self.__transports = {} @@ -54,7 +56,7 @@ class AbstractTransportDispatcher: else: raise error.CarrierError( 'Unregistered transport %s' % (incomingTransport,) - ) + ) if self.__routingCbFun: recvId = self.__routingCbFun( @@ -69,7 +71,7 @@ class AbstractTransportDispatcher: ) else: raise error.CarrierError( - 'No callback for "%r" found - loosing incoming event'%(recvId,) + 'No callback for "%r" found - loosing incoming event' % (recvId,) ) # Dispatcher API @@ -111,7 +113,7 @@ class AbstractTransportDispatcher: if tDomain in self.__transports: raise error.CarrierError( 'Transport %s already registered' % (tDomain,) - ) + ) transport.registerCbFun(self._cbFun) self.__transports[tDomain] = transport self.__transportDomainMap[transport] = tDomain @@ -120,7 +122,7 @@ class AbstractTransportDispatcher: if tDomain not in self.__transports: raise error.CarrierError( 'Transport %s not registered' % (tDomain,) - ) + ) self.__transports[tDomain].unregisterCbFun() del self.__transportDomainMap[self.__transports[tDomain]] del self.__transports[tDomain] @@ -130,18 +132,18 @@ class AbstractTransportDispatcher: return self.__transports[transportDomain] raise error.CarrierError( 'Transport %s not registered' % (transportDomain,) - ) + ) def sendMessage(self, outgoingMessage, transportDomain, transportAddress): if transportDomain in self.__transports: self.__transports[transportDomain].sendMessage( outgoingMessage, transportAddress - ) + ) else: raise error.CarrierError( 'No suitable transport domain for %s' % (transportDomain,) - ) + ) def getTimerResolution(self): return self.__timerResolution @@ -156,7 +158,7 @@ class AbstractTransportDispatcher: return self.__ticks def handleTimerTick(self, timeNow): - if self.__nextTime == 0: # initial initialization + if self.__nextTime == 0: # initial initialization self.__nextTime = timeNow + self.__timerResolution - self.__timerDelta if self.__nextTime >= timeNow: @@ -180,10 +182,7 @@ class AbstractTransportDispatcher: del self.__jobs[jobId] def jobsArePending(self): - if self.__jobs: - return 1 - else: - return 0 + return bool(self.__jobs) def runDispatcher(self, timeout=0.0): raise error.CarrierError('Method not implemented') @@ -196,8 +195,10 @@ class AbstractTransportDispatcher: self.unregisterRecvCbFun() self.unregisterTimerCbFun() + class AbstractTransportAddress: _localAddress = None + def setLocalAddress(self, s): self._localAddress = s return self @@ -208,10 +209,12 @@ class AbstractTransportAddress: def clone(self, localAddress=None): return self.__class__(self).setLocalAddress(localAddress is None and self.getLocalAddress() or localAddress) + class AbstractTransport: protoTransportDispatcher = None addressType = AbstractTransportAddress _cbFun = None + @classmethod def isCompatibleWithDispatcher(cls, transportDispatcher): return isinstance(transportDispatcher, cls.protoTransportDispatcher) @@ -220,7 +223,7 @@ class AbstractTransport: if self._cbFun: raise error.CarrierError( 'Callback function %s already registered at %s' % (self._cbFun, self) - ) + ) self._cbFun = cbFun def unregisterCbFun(self): @@ -234,7 +237,7 @@ class AbstractTransport: def openClientMode(self, iface=None): raise error.CarrierError('Method not implemented') - def openServerMode(self, iface=None): + def openServerMode(self, iface): raise error.CarrierError('Method not implemented') def sendMessage(self, outgoingMessage, transportAddress): diff --git a/pysnmp/carrier/error.py b/pysnmp/carrier/error.py index cdc3b308..290eb659 100644 --- a/pysnmp/carrier/error.py +++ b/pysnmp/carrier/error.py @@ -6,5 +6,6 @@ # from pysnmp import error + class CarrierError(error.PySnmpError): pass diff --git a/pysnmp/carrier/sockfix.py b/pysnmp/carrier/sockfix.py index 3abcd932..4c84321a 100644 --- a/pysnmp/carrier/sockfix.py +++ b/pysnmp/carrier/sockfix.py @@ -7,11 +7,11 @@ import socket symbols = { - 'IP_PKTINFO': 8, - 'IP_TRANSPARENT': 19, - 'SOL_IPV6': 41, + 'IP_PKTINFO': 8, + 'IP_TRANSPARENT': 19, + 'SOL_IPV6': 41, 'IPV6_RECVPKTINFO': 49, - 'IPV6_PKTINFO': 50 + 'IPV6_PKTINFO': 50 } for symbol in symbols: diff --git a/pysnmp/carrier/twisted/base.py b/pysnmp/carrier/twisted/base.py index 60f300ef..590717df 100644 --- a/pysnmp/carrier/twisted/base.py +++ b/pysnmp/carrier/twisted/base.py @@ -15,7 +15,10 @@ from pysnmp.carrier.twisted.dispatch import TwistedDispatcher from pysnmp.carrier.base import AbstractTransport + class AbstractTwistedTransport(AbstractTransport): protoTransportDispatcher = TwistedDispatcher - def __init__(self): + + def __init__(self, sock=None, sockMap=None): self._writeQ = [] + DgramTwistedTransport.__init__(self) diff --git a/pysnmp/carrier/twisted/dgram/base.py b/pysnmp/carrier/twisted/dgram/base.py index 4c556a4a..9dd2334b 100644 --- a/pysnmp/carrier/twisted/dgram/base.py +++ b/pysnmp/carrier/twisted/dgram/base.py @@ -11,6 +11,7 @@ from pysnmp.carrier.twisted.base import AbstractTwistedTransport from pysnmp.carrier import error from pysnmp import debug + class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport): """Base Twisted datagram Transport, to be used with TwistedDispatcher""" diff --git a/pysnmp/carrier/twisted/dgram/udp.py b/pysnmp/carrier/twisted/dgram/udp.py index 658359f6..3bf06413 100644 --- a/pysnmp/carrier/twisted/dgram/udp.py +++ b/pysnmp/carrier/twisted/dgram/udp.py @@ -12,11 +12,14 @@ from pysnmp.carrier import error domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) + class UdpTransportAddress(tuple, AbstractTransportAddress): pass + class UdpTwistedTransport(DgramTwistedTransport): addressType = UdpTransportAddress + _lport = None # AbstractTwistedTransport API @@ -37,8 +40,11 @@ class UdpTwistedTransport(DgramTwistedTransport): return self def closeTransport(self): - d = self._lport.stopListening() - d and d.addCallback(lambda x: None) - DgramTwistedTransport.closeTransport(self) + if self._lport is not None: + d = self._lport.stopListening() + if d: + d.addCallback(lambda x: None) + DgramTwistedTransport.closeTransport(self) + UdpTransport = UdpTwistedTransport diff --git a/pysnmp/carrier/twisted/dgram/unix.py b/pysnmp/carrier/twisted/dgram/unix.py index 5dc84bd3..61ccff93 100644 --- a/pysnmp/carrier/twisted/dgram/unix.py +++ b/pysnmp/carrier/twisted/dgram/unix.py @@ -17,6 +17,7 @@ class UnixTransportAddress(str, AbstractTransportAddress): class UnixTwistedTransport(DgramTwistedTransport): addressType = UnixTransportAddress + _lport = None # AbstractTwistedTransport API @@ -27,7 +28,7 @@ class UnixTwistedTransport(DgramTwistedTransport): raise error.CarrierError(sys.exc_info()[1]) return self - def openServerMode(self, iface=None): + def openServerMode(self, iface): try: self._lport = reactor.listenUNIXDatagram(iface, self) except Exception: @@ -36,8 +37,10 @@ class UnixTwistedTransport(DgramTwistedTransport): return self def closeTransport(self): - d = self._lport.stopListening() - d and d.addCallback(lambda x: None) + if self._lport is not None: + d = self._lport.stopListening() + if d: + d.addCallback(lambda x: None) DgramTwistedTransport.closeTransport(self) UnixTransport = UnixTwistedTransport diff --git a/pysnmp/carrier/twisted/dispatch.py b/pysnmp/carrier/twisted/dispatch.py index 4cadec32..04cf9fae 100644 --- a/pysnmp/carrier/twisted/dispatch.py +++ b/pysnmp/carrier/twisted/dispatch.py @@ -17,8 +17,10 @@ from twisted.internet import reactor, task from pysnmp.carrier.base import AbstractTransportDispatcher from pysnmp.error import PySnmpError + class TwistedDispatcher(AbstractTransportDispatcher): """TransportDispatcher based on twisted.internet.reactor""" + def __init__(self, *args, **kwargs): AbstractTransportDispatcher.__init__(self) self.__transportCount = 0 diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py index f66b0b54..10acd25b 100644 --- a/pysnmp/entity/config.py +++ b/pysnmp/entity/config.py @@ -46,13 +46,16 @@ privServices = {des.Des.serviceID: des.Des(), aes256.Aes256.serviceID: aes256.Aes256(), nopriv.NoPriv.serviceID: nopriv.NoPriv()} + def __cookV1SystemInfo(snmpEngine, communityIndex): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - snmpCommunityEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') + snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpCommunityEntry, = mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') tblIdx = snmpCommunityEntry.getInstIdFromIndices(communityIndex) return snmpCommunityEntry, tblIdx, snmpEngineID + def addV1System(snmpEngine, communityIndex, communityName, contextEngineId=None, contextName=None, transportTag=None, securityName=None): @@ -81,6 +84,7 @@ def addV1System(snmpEngine, communityIndex, communityName, (snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo')) ) + def delV1System(snmpEngine, communityIndex): (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) @@ -88,21 +92,26 @@ def delV1System(snmpEngine, communityIndex): ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) + def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + if securityEngineId is None: snmpEngineID = snmpEngineID.syntax else: snmpEngineID = snmpEngineID.syntax.clone(securityEngineId) - usmUserEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') + usmUserEntry, = mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') tblIdx1 = usmUserEntry.getInstIdFromIndices(snmpEngineID, securityName) - pysnmpUsmSecretEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') + pysnmpUsmSecretEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) return snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 + def addV3User(snmpEngine, userName, authProtocol=usmNoAuthProtocol, authKey=None, privProtocol=usmNoPrivProtocol, privKey=None, @@ -110,18 +119,20 @@ def addV3User(snmpEngine, userName, securityName=None, # deprecated parameters follow contextEngineId=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + if securityName is None: securityName = userName if securityEngineId is None: # backward compatibility securityEngineId = contextEngineId - (snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, - tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) + (snmpEngineID, usmUserEntry, tblIdx1, + pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) # Load augmenting table before creating new row in base one - pysnmpUsmKeyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') + pysnmpUsmKeyEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') # Load clone-from (may not be needed) - zeroDotZero, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') + zeroDotZero, = mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) @@ -176,6 +187,7 @@ def addV3User(snmpEngine, userName, (pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo')) ) + def delV3User(snmpEngine, userName, securityEngineId=None, @@ -196,7 +208,7 @@ def delV3User(snmpEngine, varBinds = initialVarBinds = ( (usmUserEntry.name + (1,), None), # usmUserEngineID (usmUserEntry.name + (2,), None), # usmUserName - (usmUserEntry.name + (4,), None) # usmUserCloneFrom + (usmUserEntry.name + (4,), None) # usmUserCloneFrom ) while varBinds: varBinds = snmpEngine.msgAndPduDsp.mibInstrumController.readNextVars( @@ -210,11 +222,15 @@ def delV3User(snmpEngine, delV3User(snmpEngine, varBinds[1][1], varBinds[0][1]) varBinds = initialVarBinds + def __cookTargetParamsInfo(snmpEngine, name): - snmpTargetParamsEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpTargetParamsEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) return snmpTargetParamsEntry, tblIdx + # mpModel: 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): if mpModel == 0: @@ -240,32 +256,39 @@ def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): (snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo')) ) + def delTargetParams(snmpEngine, name): snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) ) + def __cookTargetAddrInfo(snmpEngine, addrName): - snmpTargetAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') - snmpSourceAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpTargetAddrEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') + snmpSourceAddrEntry, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrEntry') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) return snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx + def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, params, timeout=None, retryCount=None, tagList=null, sourceAddress=None): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + SnmpUDPAddress, = mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') transportAddress = SnmpUDPAddress(transportAddress) if sourceAddress is None: sourceAddress = ('0.0.0.0', 0) sourceAddress = SnmpUDPAddress(sourceAddress) elif transportDomain[:len(snmpUDP6Domain)] == snmpUDP6Domain: - TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + TransportAddressIPv6, = mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') transportAddress = TransportAddressIPv6(transportAddress) if sourceAddress is None: sourceAddress = ('::', 0) @@ -286,6 +309,7 @@ def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, (snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo')) ) + def delTargetAddr(snmpEngine, addrName): (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) @@ -293,10 +317,12 @@ def delTargetAddr(snmpEngine, addrName): ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) ) + def addTransport(snmpEngine, transportDomain, transport): if snmpEngine.transportDispatcher: if not transport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): - raise error.PySnmpError('Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher)) + raise error.PySnmpError( + 'Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher)) else: snmpEngine.registerTransportDispatcher( transport.protoTransportDispatcher() @@ -304,16 +330,16 @@ def addTransport(snmpEngine, transportDomain, transport): # here we note that we have created transportDispatcher automatically snmpEngine.setUserContext(automaticTransportDispatcher=0) - snmpEngine.transportDispatcher.registerTransport(transportDomain, - transport) + snmpEngine.transportDispatcher.registerTransport(transportDomain, transport) automaticTransportDispatcher = snmpEngine.getUserContext( 'automaticTransportDispatcher' ) if automaticTransportDispatcher is not None: snmpEngine.setUserContext( - automaticTransportDispatcher=automaticTransportDispatcher+1 + automaticTransportDispatcher=automaticTransportDispatcher + 1 ) + def getTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return @@ -322,6 +348,7 @@ def getTransport(snmpEngine, transportDomain): except error.PySnmpError: return + def delTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return @@ -342,28 +369,33 @@ def delTransport(snmpEngine, transportDomain): snmpEngine.delUserContext(automaticTransportDispatcher) return transport + addSocketTransport = addTransport delSocketTransport = delTransport + # VACM shortcuts def addContext(snmpEngine, contextName): - vacmContextEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry' - ) + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmContextEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmContextEntry.name + (1,) + tblIdx, contextName),) ) + def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): - vacmSecurityToGroupEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' - ) + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmSecurityToGroupEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', + 'vacmSecurityToGroupEntry') tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices(securityModel, securityName) return vacmSecurityToGroupEntry, tblIdx + def addVacmGroup(snmpEngine, groupName, securityModel, securityName): (vacmSecurityToGroupEntry, tblIdx) = __cookVacmGroupInfo(snmpEngine, securityModel, securityName) @@ -377,6 +409,7 @@ def addVacmGroup(snmpEngine, groupName, securityModel, securityName): (vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo')) ) + def delVacmGroup(snmpEngine, securityModel, securityName): vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( snmpEngine, securityModel, securityName @@ -385,20 +418,24 @@ def delVacmGroup(snmpEngine, securityModel, securityName): ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) ) + def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel): - vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmAccessEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') tblIdx = vacmAccessEntry.getInstIdFromIndices(groupName, contextName, securityModel, securityLevel) return vacmAccessEntry, tblIdx + def addVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel, prefix, readView, writeView, notifyView): vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel) - addContext(snmpEngine, contextName) # this is leaky + addContext(snmpEngine, contextName) # this is leaky snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) @@ -414,6 +451,7 @@ def addVacmAccess(snmpEngine, groupName, contextName, securityModel, (vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo')) ) + def delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel): vacmAccessEntry, tblIdx = __cookVacmAccessInfo(snmpEngine, groupName, @@ -423,13 +461,17 @@ def delVacmAccess(snmpEngine, groupName, contextName, securityModel, ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) ) + def __cookVacmViewInfo(snmpEngine, viewName, subTree): - vacmViewTreeFamilyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + vacmViewTreeFamilyEntry, = mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' ) tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree) return vacmViewTreeFamilyEntry, tblIdx + def addVacmView(snmpEngine, viewName, viewType, subTree, mask): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, subTree) @@ -444,6 +486,7 @@ def addVacmView(snmpEngine, viewName, viewType, subTree, mask): (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo')) ) + def delVacmView(snmpEngine, viewName, subTree): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo(snmpEngine, viewName, subTree) @@ -451,15 +494,19 @@ def delVacmView(snmpEngine, viewName, subTree): ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) ) + # VACM simplicity wrappers def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + groupName = 'v-%s-%d' % (hash(securityName), securityModel) - SnmpSecurityLevel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') + SnmpSecurityLevel, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') securityLevel = SnmpSecurityLevel(securityLevel) return (groupName, securityLevel, 'r' + groupName, 'w' + groupName, 'n' + groupName) + def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): @@ -476,6 +523,7 @@ def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, if notifySubTree: addVacmView(snmpEngine, notifyView, "included", notifySubTree, null) + def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=()): (groupName, securityLevel, readView, writeView, @@ -496,48 +544,59 @@ def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, snmpEngine, notifyView, notifySubTree ) + # Obsolete shortcuts for add/delVacmUser() wrappers def addRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree) + def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree) + def addRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, subTree) + def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, subTree) + def addTrapUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, (), (), subTree) + def delTrapUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, (), (), subTree) + # Notification target setup def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, filterSubtree=None): - snmpNotifyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') tblIdx1 = snmpNotifyEntry.getInstIdFromIndices(notificationName) - snmpNotifyFilterProfileEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') + snmpNotifyFilterProfileEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', + 'snmpNotifyFilterProfileEntry') tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices(paramsName) profileName = '%s-filter' % hash(notificationName) if filterSubtree: - snmpNotifyFilterEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') + snmpNotifyFilterEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', + 'snmpNotifyFilterEntry') tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices(profileName, filterSubtree) else: @@ -547,6 +606,7 @@ def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, tblIdx3) + def addNotificationTarget(snmpEngine, notificationName, paramsName, transportTag, notifyType=None, filterSubtree=None, filterMask=None, filterType=None): @@ -585,6 +645,7 @@ def addNotificationTarget(snmpEngine, notificationName, paramsName, (snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo')) ) + def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtree=None): (snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, @@ -607,6 +668,7 @@ def delNotificationTarget(snmpEngine, notificationName, paramsName, ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) ) + # rfc3415: A.1 def setInitialVacmParameters(snmpEngine): # rfc3415: A.1.1 --> initial-semi-security-configuration diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py index 76323d7b..868dbf37 100644 --- a/pysnmp/entity/engine.py +++ b/pysnmp/entity/engine.py @@ -9,10 +9,10 @@ import sys import tempfile from pysnmp.proto.rfc3412 import MsgAndPduDispatcher from pysnmp.proto.mpmod.rfc2576 import SnmpV1MessageProcessingModel, \ - SnmpV2cMessageProcessingModel + SnmpV2cMessageProcessingModel from pysnmp.proto.mpmod.rfc3412 import SnmpV3MessageProcessingModel from pysnmp.proto.secmod.rfc2576 import SnmpV1SecurityModel, \ - SnmpV2cSecurityModel + SnmpV2cSecurityModel from pysnmp.proto.secmod.rfc3414 import SnmpUSMSecurityModel from pysnmp.proto.acmod import rfc3415, void from pysnmp.entity import observer @@ -21,6 +21,7 @@ from pysnmp import error __all__ = ['SnmpEngine'] + class SnmpEngine: """Creates SNMP engine object. @@ -51,6 +52,7 @@ class SnmpEngine: >>> """ + def __init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None): self.cache = {} @@ -63,11 +65,11 @@ class SnmpEngine: self.msgAndPduDsp = msgAndPduDsp self.messageProcessingSubsystems = { SnmpV1MessageProcessingModel.messageProcessingModelID: - SnmpV1MessageProcessingModel(), + SnmpV1MessageProcessingModel(), SnmpV2cMessageProcessingModel.messageProcessingModelID: - SnmpV2cMessageProcessingModel(), + SnmpV2cMessageProcessingModel(), SnmpV3MessageProcessingModel.messageProcessingModelID: - SnmpV3MessageProcessingModel() + SnmpV3MessageProcessingModel() } self.securityModels = { SnmpV1SecurityModel.securityModelID: SnmpV1SecurityModel(), @@ -85,11 +87,14 @@ class SnmpEngine: raise error.PySnmpError( 'MIB instrumentation does not yet exist' ) - snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize) - snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') + snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineBoots') snmpEngineBoots.syntax += 1 - origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') if snmpEngineID is None: self.snmpEngineID = origSnmpEngineID.syntax @@ -97,7 +102,8 @@ class SnmpEngine: origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) self.snmpEngineID = origSnmpEngineID.syntax - debug.logger & debug.flagApp and debug.logger('SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint()) + debug.logger & debug.flagApp and debug.logger( + 'SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint()) # Attempt to make some of snmp Engine settings persistent. # This should probably be generalized as a non-volatile MIB store. @@ -115,12 +121,12 @@ class SnmpEngine: f = os.path.join(persistentPath, 'boots') try: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(open(f).read()) - except: + except Exception: pass try: snmpEngineBoots.syntax += 1 - except: + except Exception: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(1) try: @@ -128,14 +134,16 @@ class SnmpEngine: os.write(fd, snmpEngineBoots.syntax.prettyPrint()) os.close(fd) os.rename(fn, f) - except: - debug.logger & debug.flagApp and debug.logger('SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) + except Exception: + debug.logger & debug.flagApp and debug.logger( + 'SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) else: - debug.logger & debug.flagApp and debug.logger('SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) + debug.logger & debug.flagApp and debug.logger( + 'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) def __repr__(self): return '%s(snmpEngineID=%r)' % \ - (self.__class__.__name__, self.snmpEngineID) + (self.__class__.__name__, self.snmpEngineID) # Transport dispatcher bindings @@ -193,4 +201,3 @@ class SnmpEngine: del self.cache['__%s' % arg] except KeyError: pass - diff --git a/pysnmp/entity/observer.py b/pysnmp/entity/observer.py index c18546da..2e137129 100644 --- a/pysnmp/entity/observer.py +++ b/pysnmp/entity/observer.py @@ -6,6 +6,7 @@ # from pysnmp import error + class MetaObserver: """This is a simple facility for exposing internal SNMP Engine working details to pysnmp applications. These details are @@ -21,6 +22,7 @@ class MetaObserver: to exist to functions that are at the same or deeper level of invocation relative to execution point specified. """ + def __init__(self): self.__observers = {} self.__contexts = {} @@ -32,7 +34,7 @@ class MetaObserver: else: self.__contexts[cbFun] = kwargs.get('cbCtx') for execpoint in execpoints: - if not execpoint in self.__observers: + if execpoint not in self.__observers: self.__observers[execpoint] = [] self.__observers[execpoint].append(cbFun) diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py index 200326f3..e174c379 100644 --- a/pysnmp/entity/rfc3413/cmdgen.py +++ b/pysnmp/entity/rfc3413/cmdgen.py @@ -17,16 +17,17 @@ getNextHandle = nextid.Integer(0x7fffffff) __null = univ.Null('') + def getNextVarBinds(varBinds, origVarBinds=None): errorIndication = None idx = nonNulls = len(varBinds) rspVarBinds = [] while idx: - idx = idx - 1 + idx -= 1 if varBinds[idx][1].tagSet in (rfc1905.NoSuchObject.tagSet, rfc1905.NoSuchInstance.tagSet, rfc1905.EndOfMibView.tagSet): - nonNulls = nonNulls - 1 + nonNulls -= 1 elif origVarBinds is not None: if v2c.ObjectIdentifier(origVarBinds[idx][0]).asTuple() >= varBinds[idx][0].asTuple(): errorIndication = errind.oidNotIncreasing @@ -38,8 +39,10 @@ def getNextVarBinds(varBinds, origVarBinds=None): return errorIndication, rspVarBinds + class CommandGenerator: _null = univ.Null('') + def __init__(self): self.__pendingReqs = {} @@ -64,16 +67,17 @@ class CommandGenerator: # 3.1.3 if statusInformation: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) errorIndication = statusInformation['errorIndication'] # SNMP engine discovery will take extra retries, allow that if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID) and \ - origRetries == origRetryCount + 2 or \ - errorIndication not in (errind.notInTimeWindow, - errind.unknownEngineID) and \ - origRetries == origRetryCount: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) + origRetries == origRetryCount + 2 or \ + errorIndication not in (errind.notInTimeWindow, errind.unknownEngineID) and \ + origRetries == origRetryCount: + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) cbFun(snmpEngine, origSendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return @@ -99,19 +103,22 @@ class CommandGenerator: except StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % (sendPduHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % ( + sendPduHandle, statusInformation)) cbFun(snmpEngine, origSendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return if origMessageProcessingModel != messageProcessingModel or \ - origSecurityModel != securityModel or \ - origSecurityName != origSecurityName or \ - origContextEngineId and origContextEngineId != contextEngineId or \ - origContextName and origContextName != contextName or \ - origPduVersion != pduVersion: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) + origSecurityModel != securityModel or \ + origSecurityName != origSecurityName or \ + origContextEngineId and origContextEngineId != contextEngineId or \ + origContextName and origContextName != contextName or \ + origPduVersion != pduVersion: + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) @@ -123,7 +130,8 @@ class CommandGenerator: # 3.1.2 if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu): - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) return @@ -138,9 +146,10 @@ class CommandGenerator: securityLevel) = config.getTargetInfo(snmpEngine, targetName) # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() - SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') + SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') # Cast possible strings into bytes if contextEngineId: @@ -176,13 +185,17 @@ class CommandGenerator: retryCount, 0 ) - debug.logger & debug.flagApp and debug.logger('sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % (sendPduHandle, timeout, timeoutInTicks, retryCount)) + debug.logger & debug.flagApp and debug.logger( + 'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % ( + sendPduHandle, timeout, timeoutInTicks, retryCount)) return sendRequestHandle + # backward compatibility stub CommandGeneratorBase = CommandGenerator + class GetCommandGenerator(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -204,6 +217,7 @@ class GetCommandGenerator(CommandGenerator): contextName, reqPDU, self.processResponseVarBinds, (cbFun, cbCtx)) + class SetCommandGenerator(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -225,6 +239,7 @@ class SetCommandGenerator(CommandGenerator): contextName, reqPDU, self.processResponseVarBinds, (cbFun, cbCtx)) + class NextCommandGeneratorSingleRun(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -247,6 +262,7 @@ class NextCommandGeneratorSingleRun(CommandGenerator): (targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) + class NextCommandGenerator(NextCommandGeneratorSingleRun): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -272,11 +288,12 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): v2c.apiPDU.getErrorStatus(PDU), v2c.apiPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) return # app says enough if not varBinds: - return # no more objects available + return # no more objects available v2c.apiPDU.setRequestID(reqPDU, v2c.getNextRequestID()) v2c.apiPDU.setVarBinds(reqPDU, varBinds) @@ -290,11 +307,13 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): except StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) + class BulkCommandGeneratorSingleRun(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -324,6 +343,7 @@ class BulkCommandGeneratorSingleRun(CommandGenerator): contextEngineId, contextName, reqPDU, cbFun, cbCtx)) + class BulkCommandGenerator(BulkCommandGeneratorSingleRun): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): @@ -353,16 +373,16 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): v2c.apiBulkPDU.getErrorStatus(PDU), v2c.apiBulkPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) - return # app says enough + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) + return # app says enough if not varBinds: - return # no more objects available + return # no more objects available v2c.apiBulkPDU.setRequestID(reqPDU, v2c.getNextRequestID()) v2c.apiBulkPDU.setVarBinds(reqPDU, varBinds) - try: self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, @@ -372,10 +392,13 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): except StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % ( + sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) + # # Obsolete, compatibility interfaces. # @@ -386,12 +409,14 @@ def __sendReqCbFun(snmpEngine, sendRequestHandle, errorIndication, return cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx) + def _sendReq(self, snmpEngine, targetName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName=''): return self.sendVarBinds(snmpEngine, targetName, contextEngineId, contextName, varBinds, __sendReqCbFun, (cbFun, cbCtx)) + def _sendBulkReq(self, snmpEngine, targetName, nonRepeaters, maxRepetitions, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName=''): @@ -399,6 +424,7 @@ def _sendBulkReq(self, snmpEngine, targetName, nonRepeaters, maxRepetitions, contextName, nonRepeaters, maxRepetitions, varBinds, __sendReqCbFun, (cbFun, cbCtx)) + # install compatibility wrappers GetCommandGenerator.sendReq = _sendReq SetCommandGenerator.sendReq = _sendReq diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py index aa512170..60c64ad3 100644 --- a/pysnmp/entity/rfc3413/cmdrsp.py +++ b/pysnmp/entity/rfc3413/cmdrsp.py @@ -11,6 +11,7 @@ from pysnmp.proto.proxy import rfc2576 import pysnmp.smi.error from pysnmp import debug + # 3.2 class CommandResponderBase: acmID = 3 # default MIB access control method to use @@ -19,7 +20,7 @@ class CommandResponderBase: def __init__(self, snmpEngine, snmpContext): snmpEngine.msgAndPduDsp.registerContextEngineId( snmpContext.contextEngineId, self.pduTypes, self.processPdu - ) + ) self.snmpContext = snmpContext self.__pendingReqs = {} @@ -44,7 +45,10 @@ class CommandResponderBase: v2c.apiPDU.setErrorIndex(PDU, errorIndex) v2c.apiPDU.setVarBinds(PDU, varBinds) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % (stateReference, errorStatus, errorIndex, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % ( + stateReference, errorStatus, errorIndex, varBinds) + ) self.sendPdu(snmpEngine, stateReference, PDU) @@ -79,8 +83,10 @@ class CommandResponderBase: ) except error.StatusInformation: - debug.logger & debug.flagApp and debug.logger('sendPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') + debug.logger & debug.flagApp and debug.logger( + 'sendPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpSilentDrops') snmpSilentDrops.syntax += 1 _getRequestType = rfc1905.GetRequestPDU.tagSet @@ -105,7 +111,7 @@ class CommandResponderBase: # 3.2.1 if PDU.tagSet not in rfc3411.readClassPDUs and \ - PDU.tagSet not in rfc3411.writeClassPDUs: + PDU.tagSet not in rfc3411.writeClassPDUs: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) # 3.2.2 --> no-op @@ -125,16 +131,18 @@ class CommandResponderBase: varBinds = v2c.apiPDU.getVarBinds(PDU) errorStatus, errorIndex = 'noError', 0 - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) try: self.handleMgmtOperation(snmpEngine, stateReference, - contextName, PDU, + contextName, PDU, (self.__verifyAccess, snmpEngine)) # SNMPv2 SMI exceptions except pysnmp.smi.error.GenError: errorIndication = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) if 'oid' in errorIndication: # Request REPORT generation statusInformation['oid'] = errorIndication['oid'] @@ -195,17 +203,19 @@ class CommandResponderBase: # Map ACM errors onto SMI ones except error.StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + '__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) errorIndication = statusInformation['errorIndication'] # 3.2.5... if errorIndication == errind.noSuchView or \ - errorIndication == errind.noAccessEntry or \ - errorIndication == errind.noGroupName: + errorIndication == errind.noAccessEntry or \ + errorIndication == errind.noGroupName: raise pysnmp.smi.error.AuthorizationError(name=name, idx=idx) elif errorIndication == errind.otherError: raise pysnmp.smi.error.GenError(name=name, idx=idx) elif errorIndication == errind.noSuchContext: - snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-TARGET-MIB', 'snmpUnknownContexts') + snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-TARGET-MIB', 'snmpUnknownContexts') snmpUnknownContexts.syntax += 1 # Request REPORT generation raise pysnmp.smi.error.GenError(name=name, idx=idx, @@ -218,11 +228,12 @@ class CommandResponderBase: else: # rfc2576: 4.1.2.1 if securityModel == 1 and syntax is not None and \ - self._counter64Type == syntax.getTagSet() and \ - self._getNextRequestType == pduType: + self._counter64Type == syntax.getTagSet() and \ + self._getNextRequestType == pduType: # This will cause MibTree to skip this OID-value raise pysnmp.smi.error.NoAccessError(name=name, idx=idx) + class GetCommandResponder(CommandResponderBase): pduTypes = (rfc1905.GetRequestPDU.tagSet,) @@ -236,6 +247,7 @@ class GetCommandResponder(CommandResponderBase): mgmtFun(v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx))) self.releaseStateInformation(stateReference) + class NextCommandResponder(CommandResponderBase): pduTypes = (rfc1905.GetNextRequestPDU.tagSet,) @@ -257,6 +269,7 @@ class NextCommandResponder(CommandResponderBase): break self.releaseStateInformation(stateReference) + class BulkCommandResponder(CommandResponderBase): pduTypes = (rfc1905.GetBulkRequestPDU.tagSet,) maxVarBinds = 64 @@ -276,10 +289,10 @@ class BulkCommandResponder(CommandResponderBase): N = min(int(nonRepeaters), len(reqVarBinds)) M = int(maxRepetitions) - R = max(len(reqVarBinds)-N, 0) + R = max(len(reqVarBinds) - N, 0) if R: - M = min(M, self.maxVarBinds/R) + M = min(M, self.maxVarBinds / R) debug.logger & debug.flagApp and debug.logger('handleMgmtOperation: N %d, M %d, R %d' % (N, M, R)) @@ -294,7 +307,7 @@ class BulkCommandResponder(CommandResponderBase): while M and R: rspVarBinds.extend(mgmtFun(varBinds, (acFun, acCtx))) varBinds = rspVarBinds[-R:] - M = M - 1 + M -= 1 if len(rspVarBinds): self.sendVarBinds(snmpEngine, stateReference, 0, 0, rspVarBinds) @@ -302,6 +315,7 @@ class BulkCommandResponder(CommandResponderBase): else: raise pysnmp.smi.error.SmiError() + class SetCommandResponder(CommandResponderBase): pduTypes = (rfc1905.SetRequestPDU.tagSet,) diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py index adbf6dae..a73f9168 100644 --- a/pysnmp/entity/rfc3413/config.py +++ b/pysnmp/entity/rfc3413/config.py @@ -7,6 +7,7 @@ from pysnmp.smi.error import SmiError, NoSuchInstanceError from pysnmp.entity import config + def getTargetAddr(snmpEngine, snmpTargetAddrName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -30,10 +31,10 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetAddrParams) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', - 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', - 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' - ) + 'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', + 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', + 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' + ) snmpSourceAddrTAddress, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(snmpTargetAddrName) @@ -63,12 +64,14 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName): transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain) if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', + 'SnmpUDPAddress') snmpTargetAddrTAddress = transport.addressType( SnmpUDPAddress(snmpTargetAddrTAddress) ).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress)) elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain: - TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') snmpTargetAddrTAddress = transport.addressType( TransportAddressIPv6(snmpTargetAddrTAddress) ).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress)) @@ -111,10 +114,10 @@ def getTargetParams(snmpEngine, paramsName): (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel', - 'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName', - 'snmpTargetParamsSecurityLevel' - ) + 'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel', + 'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName', + 'snmpTargetParamsSecurityLevel' + ) tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(paramsName) @@ -143,6 +146,7 @@ def getTargetParams(snmpEngine, paramsName): return nameToParamsMap[paramsName] + def getTargetInfo(snmpEngine, snmpTargetAddrName): # Transport endpoint (snmpTargetAddrTDomain, @@ -162,6 +166,7 @@ def getTargetInfo(snmpEngine, snmpTargetAddrName): snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) + def getNotificationInfo(snmpEngine, notificationTarget): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -206,6 +211,7 @@ def getNotificationInfo(snmpEngine, notificationTarget): return targetToNotifyMap[notificationTarget] + def getTargetNames(snmpEngine, tag): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder @@ -226,9 +232,9 @@ def getTargetNames(snmpEngine, tag): (SnmpTagValue, snmpTargetAddrName, snmpTargetAddrTagList) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', - 'snmpTargetAddrTagList' - ) + 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', + 'snmpTargetAddrTagList' + ) mibNode = snmpTargetAddrTagList while True: try: diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py index 512c93fb..e0b73ef4 100644 --- a/pysnmp/entity/rfc3413/context.py +++ b/pysnmp/entity/rfc3413/context.py @@ -9,9 +9,11 @@ from pyasn1.compat.octets import null from pysnmp import error from pysnmp import debug + class SnmpContext: def __init__(self, snmpEngine, contextEngineId=None): - snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') if contextEngineId is None: # Default to local snmpEngineId self.contextEngineId = snmpEngineId.syntax @@ -19,16 +21,17 @@ class SnmpContext: self.contextEngineId = snmpEngineId.syntax.clone(contextEngineId) debug.logger & debug.flagIns and debug.logger('SnmpContext: contextEngineId \"%r\"' % (self.contextEngineId,)) self.contextNames = { - null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name - } + null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name + } def registerContextName(self, contextName, mibInstrum=None): contextName = univ.OctetString(contextName).asOctets() if contextName in self.contextNames: raise error.PySnmpError( 'Duplicate contextName %s' % contextName - ) - debug.logger & debug.flagIns and debug.logger('registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum)) + ) + debug.logger & debug.flagIns and debug.logger( + 'registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum)) if mibInstrum is None: self.contextNames[contextName] = self.contextNames[null] else: @@ -37,7 +40,8 @@ class SnmpContext: def unregisterContextName(self, contextName): contextName = univ.OctetString(contextName).asOctets() if contextName in self.contextNames: - debug.logger & debug.flagIns and debug.logger('unregisterContextName: unregistered contextName %r' % contextName) + debug.logger & debug.flagIns and debug.logger( + 'unregisterContextName: unregistered contextName %r' % contextName) del self.contextNames[contextName] def getMibInstrum(self, contextName=null): @@ -46,7 +50,8 @@ class SnmpContext: debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName %r not registered' % contextName) raise error.PySnmpError( 'Missing contextName %s' % contextName - ) + ) else: - debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName])) + debug.logger & debug.flagIns and debug.logger( + 'getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName])) return self.contextNames[contextName] diff --git a/pysnmp/entity/rfc3413/mibvar.py b/pysnmp/entity/rfc3413/mibvar.py index 7cc46123..fdcef9f5 100644 --- a/pysnmp/entity/rfc3413/mibvar.py +++ b/pysnmp/entity/rfc3413/mibvar.py @@ -10,16 +10,17 @@ from pyasn1.type import univ from pysnmp.smi.error import NoSuchObjectError + # Name def mibNameToOid(mibView, name): if isinstance(name[0], tuple): f = lambda x='', y='': (x, y) modName, symName = f(*name[0]) - if modName: # load module if needed + if modName: # load module if needed mibView.mibBuilder.loadModules(modName) else: - mibView.mibBuilder.loadModules() # load all (slow) + mibView.mibBuilder.loadModules() # load all (slow) if symName: oid, label, suffix = mibView.getNodeNameByDesc(symName, modName) else: @@ -28,12 +29,12 @@ def mibNameToOid(mibView, name): modName, symName, _s = mibView.getNodeLocation(oid) mibNode, = mibView.mibBuilder.importSymbols( modName, symName - ) - if hasattr(mibNode, 'createTest'): # table column XXX + ) + if hasattr(mibNode, 'createTest'): # table column XXX modName, symName, _s = mibView.getNodeLocation(oid[:-1]) rowNode, = mibView.mibBuilder.importSymbols(modName, symName) return oid, rowNode.getInstIdFromIndices(*suffix) - else: # scalar or incomplete spec + else: # scalar or incomplete spec return oid, suffix elif not isinstance(name, tuple): name = tuple(univ.ObjectIdentifier(name)) @@ -42,8 +43,10 @@ def mibNameToOid(mibView, name): return oid, suffix + __scalarSuffix = (univ.Integer(0),) + def oidToMibName(mibView, oid): if not isinstance(oid, tuple): oid = tuple(univ.ObjectIdentifier(oid)) @@ -51,27 +54,29 @@ def oidToMibName(mibView, oid): modName, symName, __suffix = mibView.getNodeLocation(_oid) mibNode, = mibView.mibBuilder.importSymbols( modName, symName - ) - if hasattr(mibNode, 'createTest'): # table column + ) + if hasattr(mibNode, 'createTest'): # table column __modName, __symName, __s = mibView.getNodeLocation(_oid[:-1]) rowNode, = mibView.mibBuilder.importSymbols(__modName, __symName) return (symName, modName), rowNode.getIndicesFromInstId(suffix) - elif not suffix: # scalar + elif not suffix: # scalar return (symName, modName), suffix - elif suffix == (0,): # scalar + elif suffix == (0,): # scalar return (symName, modName), __scalarSuffix else: raise NoSuchObjectError( - str='No MIB registered that defines %s object, closest known parent is %s (%s::%s)' % (univ.ObjectIdentifier(oid), univ.ObjectIdentifier(mibNode.name), modName, symName) - ) + str='No MIB registered that defines %s object, closest known parent is %s (%s::%s)' % ( + univ.ObjectIdentifier(oid), univ.ObjectIdentifier(mibNode.name), modName, symName) + ) + # Value def cloneFromMibValue(mibView, modName, symName, value): mibNode, = mibView.mibBuilder.importSymbols( modName, symName - ) - if hasattr(mibNode, 'syntax'): # scalar + ) + if hasattr(mibNode, 'syntax'): # scalar return mibNode.syntax.clone(value) else: - return # identifier + return # identifier diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py index 66d7f33d..c9bd69c4 100644 --- a/pysnmp/entity/rfc3413/ntforg.py +++ b/pysnmp/entity/rfc3413/ntforg.py @@ -17,8 +17,10 @@ from pysnmp import debug getNextHandle = nextid.Integer(0x7fffffff) + class NotificationOriginator: acmID = 3 # default MIB access control method to use + def __init__(self, snmpContext=None): self.__pendingReqs = {} self.__pendingNotifications = {} @@ -43,15 +45,19 @@ class NotificationOriginator: snmpEngine.transportDispatcher.jobFinished(id(self)) if statusInformation: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % (sendRequestHandle, sendPduHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % ( + sendRequestHandle, sendPduHandle, statusInformation)) if origRetries == origRetryCount: - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % (sendRequestHandle, sendPduHandle, origRetries)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % ( + sendRequestHandle, sendPduHandle, origRetries)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(origTimeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = float(origTimeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() # User-side API assumes SMIv2 if messageProcessingModel == 0: @@ -73,14 +79,18 @@ class NotificationOriginator: ) except error.StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % ( + sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return snmpEngine.transportDispatcher.jobStarted(id(self)) - debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % (sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount)) + debug.logger & debug.flagApp and debug.logger( + 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % ( + sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( @@ -118,7 +128,7 @@ class NotificationOriginator: # 3.3.5 if reqPDU.tagSet in rfc3411.confirmedClassPDUs: # Convert timeout in seconds into timeout in timer ticks - timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() sendRequestHandle = getNextHandle() @@ -131,7 +141,8 @@ class NotificationOriginator: self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) - debug.logger & debug.flagApp and debug.logger('sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) + debug.logger & debug.flagApp and debug.logger( + 'sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( @@ -160,10 +171,14 @@ class NotificationOriginator: self.__pendingNotifications[notificationHandle].remove(sendRequestHandle) - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, errorIndication %s, pending requests %s' % (notificationHandle, sendRequestHandle, errorIndication, self.__pendingNotifications[notificationHandle])) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, errorIndication %s, pending requests %s' % ( + notificationHandle, sendRequestHandle, errorIndication, self.__pendingNotifications[notificationHandle])) if not self.__pendingNotifications[notificationHandle]: - debug.logger & debug.flagApp and debug.logger('processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % (notificationHandle, sendRequestHandle)) + debug.logger & debug.flagApp and debug.logger( + 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % ( + notificationHandle, sendRequestHandle)) del self.__pendingNotifications[notificationHandle] cbFun(snmpEngine, sendRequestHandle, errorIndication, pdu and v2c.apiPDU.getErrorStatus(pdu) or 0, @@ -177,10 +192,13 @@ class NotificationOriginator: # def sendVarBinds(self, snmpEngine, notificationTarget, contextEngineId, contextName, varBinds=(), cbFun=None, cbCtx=None): - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % (notificationTarget, contextEngineId or '', contextName, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % ( + notificationTarget, contextEngineId or '', contextName, varBinds)) if contextName: - __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') + __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-FRAMEWORK-MIB', 'SnmpAdminString') contextName = __SnmpAdminString(contextName) # 3.3 @@ -188,12 +206,16 @@ class NotificationOriginator: notificationHandle = getNextHandle() - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % (notificationHandle, notifyTag, notifyType)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % ( + notificationHandle, notifyTag, notifyType)) varBinds = [(v2c.ObjectIdentifier(x), y) for x, y in varBinds] # 3.3.2 & 3.3.3 - snmpTrapOID, sysUpTime = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpTrapOID', 'sysUpTime') + snmpTrapOID, sysUpTime = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpTrapOID', + 'sysUpTime') for idx in range(len(varBinds)): if idx and varBinds[idx][0] == sysUpTime.getName(): @@ -211,6 +233,8 @@ class NotificationOriginator: varBinds.insert(1, (v2c.ObjectIdentifier(snmpTrapOID.getName()), snmpTrapOID.getSyntax())) + sendRequestHandle = -1 + debug.logger & debug.flagApp and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,)) for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): @@ -221,13 +245,16 @@ class NotificationOriginator: securityLevel) = config.getTargetParams(snmpEngine, params) # 3.3.1 XXX -# XXX filtering's yet to be implemented -# filterProfileName = config.getNotifyFilterProfile(params) + # XXX filtering's yet to be implemented + # filterProfileName = config.getNotifyFilterProfile(params) -# (filterSubtree, filterMask, -# filterType) = config.getNotifyFilter(filterProfileName) + # (filterSubtree, filterMask, + # filterType) = config.getNotifyFilter(filterProfileName) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % (notificationHandle, notifyTag, transportDomain, transportAddress, securityModel, securityName, securityLevel)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % ( + notificationHandle, notifyTag, transportDomain, transportAddress, securityModel, + securityName, securityLevel)) for varName, varVal in varBinds: if varName in (sysUpTime.name, snmpTrapOID.name): @@ -238,10 +265,13 @@ class NotificationOriginator: securityLevel, 'notify', contextName, varName ) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) except error.StatusInformation: - debug.logger & debug.flagApp and debug.logger('sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % (varName, securityName)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % ( + varName, securityName)) return # 3.3.4 @@ -265,9 +295,11 @@ class NotificationOriginator: except error.StatusInformation: statusInformation = sys.exc_info()[1] - debug.logger & debug.flagApp and debug.logger('sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % ( + sendRequestHandle, statusInformation)) if notificationHandle not in self.__pendingNotifications or \ - not self.__pendingNotifications[notificationHandle]: + not self.__pendingNotifications[notificationHandle]: if notificationHandle in self.__pendingNotifications: del self.__pendingNotifications[notificationHandle] if cbFun: @@ -276,17 +308,22 @@ class NotificationOriginator: cbCtx) return notificationHandle - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % (notificationHandle, sendRequestHandle, timeout)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % ( + notificationHandle, sendRequestHandle, timeout)) if notifyType == 2: if notificationHandle not in self.__pendingNotifications: self.__pendingNotifications[notificationHandle] = set() self.__pendingNotifications[notificationHandle].add(sendRequestHandle) - debug.logger & debug.flagApp and debug.logger('sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % (notificationHandle, sendRequestHandle)) + debug.logger & debug.flagApp and debug.logger( + 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % ( + notificationHandle, sendRequestHandle)) return notificationHandle + # # Obsolete, compatibility interfaces. # @@ -303,6 +340,7 @@ def _sendNotificationCbFun(snmpEngine, sendRequestHandle, errorIndication, # a backward compatible way of calling user function cbFun(sendRequestHandle, errorIndication, cbCtx) + def _sendNotification(self, snmpEngine, notificationTarget, notificationName, additionalVarBinds=(), cbFun=None, cbCtx=None, contextName=null, instanceIndex=None): @@ -342,6 +380,7 @@ def _sendNotification(self, snmpEngine, notificationTarget, notificationName, contextName, varBinds + list(additionalVarBinds), _sendNotificationCbFun, (cbFun, cbCtx)) + # install compatibility wrapper NotificationOriginator.sendNotification = _sendNotification diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py index 2b79f9f1..55b2841c 100644 --- a/pysnmp/entity/rfc3413/ntfrcv.py +++ b/pysnmp/entity/rfc3413/ntfrcv.py @@ -11,6 +11,7 @@ from pysnmp.proto.api import v1, v2c # backend is always SMIv2 compliant from pysnmp.proto.proxy import rfc2576 from pysnmp import debug + # 3.4 class NotificationReceiver: pduTypes = (v1.TrapPDU.tagSet, v2c.SNMPv2TrapPDU.tagSet, @@ -18,7 +19,7 @@ class NotificationReceiver: def __init__(self, snmpEngine, cbFun, cbCtx=None): snmpEngine.msgAndPduDsp.registerContextEngineId( - null, self.pduTypes, self.processPdu # '' is a wildcard + null, self.pduTypes, self.processPdu # '' is a wildcard ) self.__cbFunVer = 0 self.__cbFun = cbFun @@ -46,7 +47,8 @@ class NotificationReceiver: errorIndex = 0 varBinds = v2c.apiPDU.getVarBinds(PDU) - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) # 3.4 if PDU.tagSet in rfc3411.confirmedClassPDUs: @@ -59,7 +61,8 @@ class NotificationReceiver: v2c.apiPDU.setErrorIndex(rspPDU, errorIndex) v2c.apiPDU.setVarBinds(rspPDU, varBinds) - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint())) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint())) # Agent-side API complies with SMIv2 if messageProcessingModel == 0: @@ -76,8 +79,10 @@ class NotificationReceiver: stateReference, statusInformation) except error.StatusInformation: - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpSilentDrops') snmpSilentDrops.syntax += 1 elif PDU.tagSet in rfc3411.unconfirmedClassPDUs: @@ -85,7 +90,9 @@ class NotificationReceiver: else: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) - debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (stateReference, self.__cbFun, self.__cbCtx, varBinds)) + debug.logger & debug.flagApp and debug.logger( + 'processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % ( + stateReference, self.__cbFun, self.__cbCtx, varBinds)) if self.__cbFunVer: self.__cbFun(snmpEngine, stateReference, contextEngineId, diff --git a/pysnmp/entity/rfc3413/oneliner/cmdgen.py b/pysnmp/entity/rfc3413/oneliner/cmdgen.py index 61bfbbbc..411fc40c 100644 --- a/pysnmp/entity/rfc3413/oneliner/cmdgen.py +++ b/pysnmp/entity/rfc3413/oneliner/cmdgen.py @@ -18,6 +18,7 @@ __all__ = ['AsynCommandGenerator', 'CommandGenerator', 'MibVariable'] MibVariable = ObjectIdentity + class AsynCommandGenerator: _null = univ.Null('') @@ -26,7 +27,7 @@ class AsynCommandGenerator: def __init__(self, snmpEngine=None): if snmpEngine is None: - self.snmpEngine = snmpEngine = SnmpEngine() + self.snmpEngine = SnmpEngine() else: self.snmpEngine = snmpEngine @@ -95,7 +96,6 @@ class AsynCommandGenerator: if contextName is null and authData.contextName: contextName = authData.contextName - return setCmd( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId, contextName), *varBinds, @@ -159,8 +159,10 @@ class AsynCommandGenerator: asyncBulkCmd = bulkCmd + class CommandGenerator: _null = univ.Null('') + def __init__(self, snmpEngine=None, asynCmdGen=None): # compatibility attributes self.snmpEngine = snmpEngine or SnmpEngine() @@ -172,8 +174,8 @@ class CommandGenerator: kwargs['lookupValues'] = False errorIndication, errorStatus, errorIndex, varBinds = None, 0, 0, [] for errorIndication, \ - errorStatus, errorIndex, \ - varBinds \ + errorStatus, errorIndex, \ + varBinds \ in sync.getCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), @@ -189,8 +191,8 @@ class CommandGenerator: kwargs['lookupValues'] = False errorIndication, errorStatus, errorIndex, rspVarBinds = None, 0, 0, [] for errorIndication, \ - errorStatus, errorIndex, \ - rspVarBinds \ + errorStatus, errorIndex, \ + rspVarBinds \ in sync.setCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), @@ -210,8 +212,8 @@ class CommandGenerator: errorIndication, errorStatus, errorIndex = None, 0, 0 varBindTable = [] for errorIndication, \ - errorStatus, errorIndex, \ - varBinds \ + errorStatus, errorIndex, \ + varBinds \ in sync.nextCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), @@ -235,8 +237,8 @@ class CommandGenerator: errorIndication, errorStatus, errorIndex = None, 0, 0 varBindTable = [] for errorIndication, \ - errorStatus, errorIndex, \ - varBinds \ + errorStatus, errorIndex, \ + varBinds \ in sync.bulkCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), diff --git a/pysnmp/entity/rfc3413/oneliner/ntforg.py b/pysnmp/entity/rfc3413/oneliner/ntforg.py index ddb7438f..2436b5ba 100644 --- a/pysnmp/entity/rfc3413/oneliner/ntforg.py +++ b/pysnmp/entity/rfc3413/oneliner/ntforg.py @@ -21,6 +21,7 @@ __all__ = ['AsynNotificationOriginator', MibVariable = ObjectIdentity + class ErrorIndicationReturn: def __init__(self, *vars): self.__vars = vars @@ -29,7 +30,7 @@ class ErrorIndicationReturn: return self.__vars[i] def __nonzero__(self): - return self.__vars[0] and 1 or 0 + return bool(self) def __bool__(self): return bool(self.__vars[0]) @@ -37,9 +38,11 @@ class ErrorIndicationReturn: def __str__(self): return str(self.__vars[0]) + class AsynNotificationOriginator: vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() + def __init__(self, snmpEngine=None, snmpContext=None): if snmpEngine is None: self.snmpEngine = snmpEngine = SnmpEngine() @@ -133,8 +136,10 @@ class AsynNotificationOriginator: asyncSendNotification = sendNotification + class NotificationOriginator: vbProcessor = NotificationOriginatorVarBinds() + def __init__(self, snmpEngine=None, snmpContext=None, asynNtfOrg=None): # compatibility attributes self.snmpEngine = snmpEngine or SnmpEngine() @@ -162,15 +167,15 @@ class NotificationOriginator: for errorIndication, \ errorStatus, errorIndex, \ rspVarBinds \ - in sync.sendNotification(self.snmpEngine, authData, - transportTarget, - ContextData( - kwargs.get('contextEngineId'), - kwargs.get('contextName', null) - ), - notifyType, - notificationType.addVarBinds(*varBinds), - **kwargs): + in sync.sendNotification(self.snmpEngine, authData, + transportTarget, + ContextData( + kwargs.get('contextEngineId'), + kwargs.get('contextName', null) + ), + notifyType, + notificationType.addVarBinds(*varBinds), + **kwargs): if notifyType == 'inform': return errorIndication, errorStatus, errorIndex, rspVarBinds else: diff --git a/pysnmp/hlapi/__init__.py b/pysnmp/hlapi/__init__.py index 44b7bb79..4680bd85 100644 --- a/pysnmp/hlapi/__init__.py +++ b/pysnmp/hlapi/__init__.py @@ -1,3 +1,9 @@ +# +# This file is part of pysnmp software. +# +# Copyright (c) 2005-2016, Ilya Etingof +# License: http://pysnmp.sf.net/license.html +# from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * diff --git a/pysnmp/hlapi/asyncio/__init__.py b/pysnmp/hlapi/asyncio/__init__.py index 9ec0fdfc..371931eb 100644 --- a/pysnmp/hlapi/asyncio/__init__.py +++ b/pysnmp/hlapi/asyncio/__init__.py @@ -1,3 +1,9 @@ +# +# This file is part of pysnmp software. +# +# Copyright (c) 2005-2016, Ilya Etingof +# License: http://pysnmp.sf.net/license.html +# from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.entity.engine import * diff --git a/pysnmp/hlapi/asyncio/cmdgen.py b/pysnmp/hlapi/asyncio/cmdgen.py index bd82e611..d9a8d4d6 100644 --- a/pysnmp/hlapi/asyncio/cmdgen.py +++ b/pysnmp/hlapi/asyncio/cmdgen.py @@ -38,6 +38,7 @@ from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.asyncio.transport import * from pysnmp.entity.rfc3413 import cmdgen + try: import asyncio except ImportError: @@ -50,6 +51,7 @@ lcd = CommandGeneratorLcdConfigurator() isEndOfMib = lambda x: not cmdgen.getNextVarBinds(x)[1] + @asyncio.coroutine def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): @@ -125,6 +127,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -147,6 +150,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, ) return future + @asyncio.coroutine def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): @@ -222,6 +226,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -244,6 +249,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, ) return future + @asyncio.coroutine def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): @@ -323,6 +329,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): @@ -330,7 +337,8 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, if future.cancelled(): return future.set_result( - (errorIndication, errorStatus, errorIndex, [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable]) + (errorIndication, errorStatus, errorIndex, + [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable]) ) addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) @@ -345,6 +353,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, ) return future + @asyncio.coroutine def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): @@ -435,6 +444,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): @@ -442,7 +452,8 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, if future.cancelled(): return future.set_result( - (errorIndication, errorStatus, errorIndex, [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable]) + (errorIndication, errorStatus, errorIndex, + [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable]) ) addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) diff --git a/pysnmp/hlapi/asyncio/ntforg.py b/pysnmp/hlapi/asyncio/ntforg.py index cd0394a2..13ec63bd 100644 --- a/pysnmp/hlapi/asyncio/ntforg.py +++ b/pysnmp/hlapi/asyncio/ntforg.py @@ -15,6 +15,7 @@ from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.asyncio.transport import * from pysnmp.entity.rfc3413 import ntforg + try: import asyncio except ImportError: @@ -25,6 +26,7 @@ __all__ = ['sendNotification'] vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() + @asyncio.coroutine def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): @@ -115,6 +117,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): diff --git a/pysnmp/hlapi/asyncio/transport.py b/pysnmp/hlapi/asyncio/transport.py index b066b7ff..39a8edc4 100644 --- a/pysnmp/hlapi/asyncio/transport.py +++ b/pysnmp/hlapi/asyncio/transport.py @@ -4,13 +4,15 @@ # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # -import socket, sys +import socket +import sys from pysnmp.carrier.asyncio.dgram import udp, udp6 from pysnmp.hlapi.transport import AbstractTransportTarget from pysnmp.error import PySnmpError __all__ = ['Udp6TransportTarget', 'UdpTransportTarget'] + class UdpTransportTarget(AbstractTransportTarget): """Creates UDP/IPv4 configuration entry and initialize socket API if needed. @@ -47,6 +49,7 @@ class UdpTransportTarget(AbstractTransportTarget): """ transportDomain = udp.domainName protoTransport = udp.UdpAsyncioTransport + def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], @@ -55,7 +58,9 @@ class UdpTransportTarget(AbstractTransportTarget): socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: - raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( + '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + class Udp6TransportTarget(AbstractTransportTarget): """Creates UDP/IPv6 configuration entry and initialize socket API if needed. @@ -105,6 +110,7 @@ class Udp6TransportTarget(AbstractTransportTarget): """ transportDomain = udp6.domainName protoTransport = udp6.Udp6AsyncioTransport + def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], @@ -113,4 +119,5 @@ class Udp6TransportTarget(AbstractTransportTarget): socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: - raise PySnmpError('Bad IPv6/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + raise PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( + '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) diff --git a/pysnmp/hlapi/asyncore/__init__.py b/pysnmp/hlapi/asyncore/__init__.py index a6d2ecef..c1840741 100644 --- a/pysnmp/hlapi/asyncore/__init__.py +++ b/pysnmp/hlapi/asyncore/__init__.py @@ -1,3 +1,9 @@ +# +# This file is part of pysnmp software. +# +# Copyright (c) 2005-2016, Ilya Etingof +# License: http://pysnmp.sf.net/license.html +# from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * diff --git a/pysnmp/hlapi/asyncore/cmdgen.py b/pysnmp/hlapi/asyncore/cmdgen.py index 83f9efa8..776824d9 100644 --- a/pysnmp/hlapi/asyncore/cmdgen.py +++ b/pysnmp/hlapi/asyncore/cmdgen.py @@ -19,6 +19,7 @@ lcd = CommandGeneratorLcdConfigurator() isEndOfMib = lambda x: not cmdgen.getNextVarBinds(x)[1] + def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GET query. @@ -108,6 +109,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -129,6 +131,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, options.get('cbFun'), options.get('cbCtx')) ) + def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP SET query. @@ -218,6 +221,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -237,6 +241,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, options.get('cbFun'), options.get('cbCtx')) ) + def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GETNEXT query. @@ -328,12 +333,14 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, cbFun, cbCtx = cbCtx return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, - [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable], + [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in + varBindTable], cbCtx) addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) @@ -345,6 +352,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, options.get('cbFun'), options.get('cbCtx')) ) + def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): """Performs SNMP GETBULK query. @@ -447,12 +455,15 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, cbFun, cbCtx = cbCtx return cbFun(snmpEngine, sendRequestHandle, errorIndication, - errorStatus, errorIndex, [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable], cbCtx) + errorStatus, errorIndex, + [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in + varBindTable], cbCtx) addrName, paramsName = lcd.configure(snmpEngine, authData, transportTarget) return cmdgen.BulkCommandGenerator().sendVarBinds( diff --git a/pysnmp/hlapi/asyncore/ntforg.py b/pysnmp/hlapi/asyncore/ntforg.py index abd173c6..03636bfa 100644 --- a/pysnmp/hlapi/asyncore/ntforg.py +++ b/pysnmp/hlapi/asyncore/ntforg.py @@ -17,6 +17,7 @@ __all__ = ['sendNotification'] vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() + def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, cbFun=None, cbCtx=None, lookupMib=False): @@ -46,7 +47,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData, Indicates type of notification to be sent. Recognized literal values are *trap* or *inform*. - varBinds: tuple + varBinds : tuple Single :py:class:`~pysnmp.smi.rfc1902.NotificationType` class instance representing a minimum sequence of MIB variables required for particular notification type. Alternatively, @@ -54,15 +55,6 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData, objects could be passed instead. In the latter case it is up to the user to ensure proper Notification PDU contents. - cbInfo : tuple - - * `cbFun` - user-supplied callable that is invoked to pass - SNMP response to *INFORM* notification or error to user at - a later point of time. The `cbFun` callable is never invoked - for *TRAP* notifications. - * `cbCtx` - user-supplied object passing additional parameters - to/from `cbFun`. Default is `None`. - Other Parameters ---------------- cbFun : callable @@ -125,6 +117,8 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData, >>> """ + + # noinspection PyShadowingNames def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, cbFun, cbCtx = cbCtx diff --git a/pysnmp/hlapi/asyncore/sync/__init__.py b/pysnmp/hlapi/asyncore/sync/__init__.py index e2848cc1..54db456c 100644 --- a/pysnmp/hlapi/asyncore/sync/__init__.py +++ b/pysnmp/hlapi/asyncore/sync/__init__.py @@ -1,3 +1,9 @@ +# +# This file is part of pysnmp software. +# +# Copyright (c) 2005-2016, Ilya Etingof +# License: http://pysnmp.sf.net/license.html +# from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * diff --git a/pysnmp/hlapi/asyncore/sync/cmdgen.py b/pysnmp/hlapi/asyncore/sync/cmdgen.py index 7d891439..6d6bd233 100644 --- a/pysnmp/hlapi/asyncore/sync/cmdgen.py +++ b/pysnmp/hlapi/asyncore/sync/cmdgen.py @@ -16,9 +16,11 @@ __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd'] if version_info[:2] < (2, 6): __all__.append('next') + # noinspection PyShadowingBuiltins def next(iter): return iter.next() + def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GET queries. @@ -89,6 +91,8 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -121,6 +125,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, if not varBinds: break + def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP SET queries. @@ -192,6 +197,8 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, >>> """ + + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -224,6 +231,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, if not varBinds: break + def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GETNEXT queries. @@ -316,6 +324,8 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, >>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] ) (None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) """ + + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): @@ -351,11 +361,11 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, errorIndex = cbCtx['errorIndex'] if ignoreNonIncreasingOid and errorIndication and \ - isinstance(errorIndication, errind.OidNotIncreasing): + isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: - yield errorIndication, errorStatus, errorIndex, varBinds + yield (errorIndication, errorStatus, errorIndex, varBinds) return elif errorStatus: if errorStatus == 2: @@ -363,7 +373,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) - yield errorIndication, errorStatus, errorIndex, varBinds + yield (errorIndication, errorStatus, errorIndex, varBinds) return else: varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0] @@ -381,17 +391,17 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, errorIndication = errorStatus = errorIndex = None varBinds = [] - initialVarBinds = (yield errorIndication, errorStatus,\ - errorIndex, varBinds) + initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds) if initialVarBinds: varBinds = initialVarBinds initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] if maxRows and totalRows >= maxRows or \ - maxCalls and totalCalls >= maxCalls: + maxCalls and totalCalls >= maxCalls: return + def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): """Creates a generator to perform one or more SNMP GETBULK queries. @@ -499,6 +509,8 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, >>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] ) (None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) """ + + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): @@ -524,7 +536,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, while not stopFlag: if maxRows and totalRows < maxRows: - maxRepetitions = min(maxRepetitions, maxRows-totalRows) + maxRepetitions = min(maxRepetitions, maxRows - totalRows) cmdgen.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, @@ -544,8 +556,8 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, errorIndication = None if errorIndication: - yield errorIndication, errorStatus, errorIndex, \ - varBindTable and varBindTable[0] or [] + yield (errorIndication, errorStatus, errorIndex, + varBindTable and varBindTable[0] or []) if errorIndication != errind.requestTimedOut: return elif errorStatus: @@ -554,14 +566,13 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) - yield errorIndication, errorStatus, errorIndex, \ - varBindTable and varBindTable[0] or [] + yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or []) return else: for i in range(len(varBindTable)): stopFlag = True if len(varBindTable[i]) != len(initialVars): - varBindTable = i and varBindTable[:i-1] or [] + varBindTable = i and varBindTable[:i - 1] or [] break for j in range(len(varBindTable[i])): name, val = varBindTable[i][j] @@ -572,11 +583,11 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, if isinstance(val, Null): nullVarBinds[j] = True elif not lexicographicMode and \ - not initialVars[j].isPrefixOf(name): + not initialVars[j].isPrefixOf(name): varBindTable[i][j] = name, endOfMibView nullVarBinds[j] = True if stopFlag: - varBindTable = i and varBindTable[:i-1] or [] + varBindTable = i and varBindTable[:i - 1] or [] break totalRows += len(varBindTable) @@ -584,15 +595,14 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, if maxRows and totalRows >= maxRows: if totalRows > maxRows: - varBindTable = varBindTable[:-(totalRows-maxRows)] + varBindTable = varBindTable[:-(totalRows - maxRows)] stopFlag = True if maxCalls and totalCalls >= maxCalls: stopFlag = True for varBinds in varBindTable: - initialVarBinds = (yield errorIndication, errorStatus,\ - errorIndex, varBinds) + initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds) if initialVarBinds: varBinds = initialVarBinds diff --git a/pysnmp/hlapi/asyncore/sync/compat/cmdgen.py b/pysnmp/hlapi/asyncore/sync/compat/cmdgen.py index 1f6b1ece..13ad3bfa 100644 --- a/pysnmp/hlapi/asyncore/sync/compat/cmdgen.py +++ b/pysnmp/hlapi/asyncore/sync/compat/cmdgen.py @@ -14,12 +14,15 @@ from pyasn1.type.univ import Null __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'next'] + +# noinspection PyShadowingBuiltins def next(iter): return iter.next() + def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): - + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -48,9 +51,10 @@ def getCmd(snmpEngine, authData, transportTarget, contextData, yield errorIndication, errorStatus, errorIndex, varBinds + def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): - + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): @@ -69,16 +73,17 @@ def setCmd(snmpEngine, authData, transportTarget, contextData, snmpEngine.transportDispatcher.runDispatcher() - yield cbCtx['errorIndication'], \ - cbCtx['errorStatus'], cbCtx['errorIndex'], \ - cbCtx['varBinds'] + yield (cbCtx['errorIndication'], + cbCtx['errorStatus'], cbCtx['errorIndex'], + cbCtx['varBinds']) if cbCtx['errorIndication'] != errind.requestTimedOut: break + def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): - + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): @@ -113,7 +118,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, errorIndex = cbCtx['errorIndex'] if ignoreNonIncreasingOid and errorIndication and \ - isinstance(errorIndication, errind.OidNotIncreasing): + isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: @@ -144,12 +149,13 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData, yield errorIndication, errorStatus, errorIndex, varBinds if maxRows and totalRows >= maxRows or \ - maxCalls and totalCalls >= maxCalls: + maxCalls and totalCalls >= maxCalls: return + def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): - + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): @@ -175,7 +181,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, while not stopFlag: if maxRows and totalRows < maxRows: - maxRepetitions = min(maxRepetitions, maxRows-totalRows) + maxRepetitions = min(maxRepetitions, maxRows - totalRows) cmdgen.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, @@ -195,8 +201,8 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, errorIndication = None if errorIndication: - yield errorIndication, errorStatus, errorIndex, \ - varBindTable and varBindTable[0] or [] + yield (errorIndication, errorStatus, errorIndex, + varBindTable and varBindTable[0] or []) if errorIndication != errind.requestTimedOut: return elif errorStatus: @@ -205,14 +211,14 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) - yield errorIndication, errorStatus, errorIndex, \ - varBindTable and varBindTable[0] or [] + yield (errorIndication, errorStatus, errorIndex, + varBindTable and varBindTable[0] or []) return else: for i in range(len(varBindTable)): stopFlag = True if len(varBindTable[i]) != len(initialVars): - varBindTable = i and varBindTable[:i-1] or [] + varBindTable = i and varBindTable[:i - 1] or [] break for j in range(len(varBindTable[i])): name, val = varBindTable[i][j] @@ -223,11 +229,11 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, if isinstance(val, Null): nullVarBinds[j] = True elif not lexicographicMode and \ - not initialVars[j].isPrefixOf(name): + not initialVars[j].isPrefixOf(name): varBindTable[i][j] = name, endOfMibView nullVarBinds[j] = True if stopFlag: - varBindTable = i and varBindTable[:i-1] or [] + varBindTable = i and varBindTable[:i - 1] or [] break totalRows += len(varBindTable) @@ -235,7 +241,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData, if maxRows and totalRows >= maxRows: if totalRows > maxRows: - varBindTable = varBindTable[:-(totalRows-maxRows)] + varBindTable = varBindTable[:-(totalRows - maxRows)] stopFlag = True if maxCalls and totalCalls >= maxCalls: diff --git a/pysnmp/hlapi/asyncore/sync/compat/ntforg.py b/pysnmp/hlapi/asyncore/sync/compat/ntforg.py index 88b37041..01e3914a 100644 --- a/pysnmp/hlapi/asyncore/sync/compat/ntforg.py +++ b/pysnmp/hlapi/asyncore/sync/compat/ntforg.py @@ -10,16 +10,19 @@ from pysnmp.hlapi.asyncore import ntforg __all__ = ['sendNotification', 'next'] + +# noinspection PyShadowingBuiltins def next(iter): return iter.next() + # # Synchronous one-liner SNMP Notification Originator application # def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): - + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): diff --git a/pysnmp/hlapi/asyncore/sync/ntforg.py b/pysnmp/hlapi/asyncore/sync/ntforg.py index a4f22115..2f60d94a 100644 --- a/pysnmp/hlapi/asyncore/sync/ntforg.py +++ b/pysnmp/hlapi/asyncore/sync/ntforg.py @@ -12,9 +12,11 @@ __all__ = ['sendNotification'] if version_info[:2] < (2, 6): __all__.append('next') + # noinspection PyShadowingBuiltins def next(iter): return iter.next() + def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): """Creates a generator to send one or more SNMP notifications. @@ -96,6 +98,8 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData, >>> """ + + # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): diff --git a/pysnmp/hlapi/asyncore/transport.py b/pysnmp/hlapi/asyncore/transport.py index ffa4b785..39450781 100644 --- a/pysnmp/hlapi/asyncore/transport.py +++ b/pysnmp/hlapi/asyncore/transport.py @@ -4,13 +4,15 @@ # Copyright (c) 2005-2016, Ilya Etingof # License: http://pysnmp.sf.net/license.html # -import socket, sys +import socket +import sys from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pysnmp.hlapi.transport import AbstractTransportTarget from pysnmp import error __all__ = ['UnixTransportTarget', 'Udp6TransportTarget', 'UdpTransportTarget'] + class UdpTransportTarget(AbstractTransportTarget): """Creates UDP/IPv4 configuration entry and initialize socket API if needed. @@ -47,6 +49,7 @@ class UdpTransportTarget(AbstractTransportTarget): """ transportDomain = udp.domainName protoTransport = udp.UdpSocketTransport + def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], @@ -55,7 +58,9 @@ class UdpTransportTarget(AbstractTransportTarget): socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: - raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( + '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + class Udp6TransportTarget(AbstractTransportTarget): """Creates UDP/IPv6 configuration entry and initialize socket API if needed. @@ -102,6 +107,7 @@ class Udp6TransportTarget(AbstractTransportTarget): """ transportDomain = udp6.domainName protoTransport = udp6.Udp6SocketTransport + def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], @@ -110,7 +116,9 @@ class Udp6TransportTarget(AbstractTransportTarget): socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: - raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( + '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + class UnixTransportTarget(AbstractTransportTarget): transportDomain = unix.domainName diff --git a/pysnmp/hlapi/auth.py b/pysnmp/hlapi/auth.py index 2af90cef..821c0c3a 100644 --- a/pysnmp/hlapi/auth.py +++ b/pysnmp/hlapi/auth.py @@ -15,6 +15,7 @@ __all__ = ['CommunityData', 'UsmUserData', 'usmHMACSHAAuthProtocol', 'usmNoAuthProtocol', 'usmNoPrivProtocol'] + class CommunityData: """Creates SNMP v1/v2c configuration entry. @@ -59,11 +60,12 @@ class CommunityData: >>> """ - mpModel = 1 # Default is SMIv2 + mpModel = 1 # Default is SMIv2 securityModel = mpModel + 1 securityLevel = 'noAuthNoPriv' contextName = null tag = null + def __init__(self, communityIndex, communityName=None, mpModel=None, contextEngineId=None, contextName=None, tag=None, securityName=None): @@ -119,6 +121,7 @@ class CommunityData: securityName is None and self.securityName or securityName ) + #: No Authentication Protocol. usmNoAuthProtocol = config.usmNoAuthProtocol #: The HMAC-MD5-96 Digest Authentication Protocol (:RFC:`3414#section-6`) @@ -139,6 +142,7 @@ usmAesCfb192Protocol = config.usmAesCfb192Protocol #: The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_) usmAesCfb256Protocol = config.usmAesCfb256Protocol + class UsmUserData: """Creates SNMP v3 User Security Model (USM) configuration entry. @@ -208,6 +212,7 @@ class UsmUserData: securityModel = 3 mpModel = 3 contextName = null + # the contextEngineId/contextName values stored here should # be used for USM configuration only, not for PDU contents def __init__(self, userName, @@ -257,7 +262,7 @@ class UsmUserData: raise TypeError('%s is not hashable' % self.__class__.__name__) def __repr__(self): - return '%s(userName=%r, authKey=, privKey=, authProtocol=%r, privProtocol=%r, securityEngineId=%r, securityName=%r)'%( + return '%s(userName=%r, authKey=, privKey=, authProtocol=%r, privProtocol=%r, securityEngineId=%r, securityName=%r)' % ( self.__class__.__name__, self.userName, self.authProtocol, diff --git a/pysnmp/hlapi/context.py b/pysnmp/hlapi/context.py index 14ceecda..363efeac 100644 --- a/pysnmp/hlapi/context.py +++ b/pysnmp/hlapi/context.py @@ -8,6 +8,7 @@ from pyasn1.compat.octets import null __all__ = ['ContextData'] + class ContextData: """Creates UDP/IPv6 configuration entry and initialize socket API if needed. @@ -44,6 +45,7 @@ class ContextData: ContextData(contextEngineId=None, contextName='mycontext') """ + def __init__(self, contextEngineId=None, contextName=null): self.contextEngineId = contextEngineId self.contextName = contextName diff --git a/pysnmp/hlapi/lcd.py b/pysnmp/hlapi/lcd.py index 53a46edf..f96b695b 100644 --- a/pysnmp/hlapi/lcd.py +++ b/pysnmp/hlapi/lcd.py @@ -11,9 +11,11 @@ from pysnmp.hlapi.auth import * __all__ = ['CommandGeneratorLcdConfigurator', 'NotificationOriginatorLcdConfigurator'] + class AbstractLcdConfigurator: nextID = nextid.Integer(0xffffffff) cacheKeys = [] + def _getCache(self, snmpEngine): cacheId = self.__class__.__name__ cache = snmpEngine.getUserContext(cacheId) @@ -22,15 +24,17 @@ class AbstractLcdConfigurator: snmpEngine.setUserContext(**{cacheId: cache}) return cache - def configure(self, snmpEngine, authData, transportTarget): + def configure(self, snmpEngine, authData, transportTarget, *options): pass def unconfigure(self, snmpEngine, authData=None): pass + class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator): cacheKeys = ['auth', 'parm', 'tran', 'addr'] - def configure(self, snmpEngine, authData, transportTarget): + + def configure(self, snmpEngine, authData, transportTarget, *options): cache = self._getCache(snmpEngine) if isinstance(authData, CommunityData): if authData.communityIndex not in cache['auth']: @@ -59,9 +63,9 @@ class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator): else: raise error.PySnmpError('Unsupported authentication object') - paramsKey = authData.securityName, \ - authData.securityLevel, \ - authData.mpModel + paramsKey = (authData.securityName, + authData.securityLevel, + authData.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] cache['parm'][paramsKey] = paramsName, useCount + 1 @@ -145,9 +149,9 @@ class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator): else: raise error.PySnmpError('Unsupported authentication object') - paramsKey = authDataX.securityName, \ - authDataX.securityLevel, \ - authDataX.mpModel + paramsKey = (authDataX.securityName, + authDataX.securityLevel, + authDataX.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] useCount -= 1 @@ -186,11 +190,15 @@ class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator): return addrNames, paramsNames + class NotificationOriginatorLcdConfigurator(AbstractLcdConfigurator): cacheKeys = ['auth', 'name'] _cmdGenLcdCfg = CommandGeneratorLcdConfigurator() - def configure(self, snmpEngine, authData, transportTarget, notifyType): + + def configure(self, snmpEngine, authData, transportTarget, *options): cache = self._getCache(snmpEngine) + notifyType = options and options[0] or 'trap' + notifyName = None # Create matching transport tags if not given by user. Not good! if not transportTarget.tagList: @@ -220,7 +228,7 @@ class NotificationOriginatorLcdConfigurator(AbstractLcdConfigurator): ) cache['name'][notifyNameKey] = notifyName, paramsName, 1 authDataKey = authData.securityName, authData.securityModel - if authDataKey in cache['auth']: + if authDataKey in cache['auth']: authDataX, subTree, useCount = cache['auth'][authDataKey] cache['auth'][authDataKey] = authDataX, subTree, useCount + 1 else: diff --git a/pysnmp/hlapi/transport.py b/pysnmp/hlapi/transport.py index 3a062816..45807f2e 100644 --- a/pysnmp/hlapi/transport.py +++ b/pysnmp/hlapi/transport.py @@ -10,15 +10,18 @@ from pysnmp import error __all__ = [] + class AbstractTransportTarget: transportDomain = None protoTransport = AbstractTransport + def __init__(self, transportAddr, timeout=1, retries=5, tagList=null): self.transportAddr = self._resolveAddr(transportAddr) self.timeout = timeout self.retries = retries self.tagList = tagList self.iface = None + self.transport = None def __repr__(self): return '%s(%r, timeout=%r, retries=%r, tagList=%r)' % ( @@ -39,7 +42,8 @@ class AbstractTransportTarget: def verifyDispatcherCompatibility(self, snmpEngine): if not self.protoTransport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): - raise error.PySnmpError('Transport %r is not compatible with dispatcher %r' % (self.protoTransport, snmpEngine.transportDispatcher)) + raise error.PySnmpError('Transport %r is not compatible with dispatcher %r' % ( + self.protoTransport, snmpEngine.transportDispatcher)) def _resolveAddr(self, transportAddr): raise NotImplementedError() diff --git a/pysnmp/hlapi/varbinds.py b/pysnmp/hlapi/varbinds.py index 9b52e4cc..b5617113 100644 --- a/pysnmp/hlapi/varbinds.py +++ b/pysnmp/hlapi/varbinds.py @@ -9,8 +9,10 @@ from pysnmp.smi.rfc1902 import * __all__ = ['CommandGeneratorVarBinds', 'NotificationOriginatorVarBinds'] + class AbstractVarBinds: - def getMibViewController(self, snmpEngine): + @staticmethod + def getMibViewController(snmpEngine): mibViewController = snmpEngine.getUserContext('mibViewController') if not mibViewController: mibViewController = view.MibViewController( @@ -19,6 +21,7 @@ class AbstractVarBinds: snmpEngine.setUserContext(mibViewController=mibViewController) return mibViewController + class CommandGeneratorVarBinds(AbstractVarBinds): def makeVarBinds(self, snmpEngine, varBinds): mibViewController = self.getMibViewController(snmpEngine) @@ -44,6 +47,7 @@ class CommandGeneratorVarBinds(AbstractVarBinds): return varBinds + class NotificationOriginatorVarBinds(AbstractVarBinds): def makeVarBinds(self, snmpEngine, varBinds): mibViewController = self.getMibViewController(snmpEngine) @@ -65,4 +69,3 @@ class NotificationOriginatorVarBinds(AbstractVarBinds): mibViewController = self.getMibViewController(snmpEngine) varBinds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds] return varBinds - diff --git a/pysnmp/proto/acmod/rfc3415.py b/pysnmp/proto/acmod/rfc3415.py index 917dc5d7..3c6be611 100644 --- a/pysnmp/proto/acmod/rfc3415.py +++ b/pysnmp/proto/acmod/rfc3415.py @@ -10,10 +10,12 @@ from pysnmp import debug __powOfTwoSeq = [128, 64, 32, 16, 8, 4, 2, 1] + # 3.2 class Vacm: """View-based Access Control Model""" accessModelID = 3 + def isAccessAllowed(self, snmpEngine, securityModel, @@ -24,7 +26,9 @@ class Vacm: variableName): mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - debug.logger & debug.flagACL and debug.logger('isAccessAllowed: securityModel %s, securityName %s, securityLevel %s, viewType %s, contextName %s for variableName %s' % (securityModel, securityName, securityLevel, viewType, contextName, variableName)) + debug.logger & debug.flagACL and debug.logger( + 'isAccessAllowed: securityModel %s, securityName %s, securityLevel %s, viewType %s, contextName %s for variableName %s' % ( + securityModel, securityName, securityLevel, viewType, contextName, variableName)) # 3.2.1 vacmContextEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') @@ -37,7 +41,8 @@ class Vacm: raise error.StatusInformation(errorIndication=errind.noSuchContext) # 3.2.2 - vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry') + vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', + 'vacmSecurityToGroupEntry') tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( securityModel, securityName ) @@ -77,7 +82,8 @@ class Vacm: # XXX split onto object & instance ? # 3.2.5a - vacmViewTreeFamilyEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry') + vacmViewTreeFamilyEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', + 'vacmViewTreeFamilyEntry') tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName) # Walk over entries @@ -101,18 +107,18 @@ class Vacm: if vacmViewTreeFamilyMask.syntax: mask = [] for c in vacmViewTreeFamilyMask.syntax.asNumbers(): - mask = mask + [b&c for b in __powOfTwoSeq] - m = len(mask)-1 - idx = l-1 + mask = mask + [b & c for b in __powOfTwoSeq] + m = len(mask) - 1 + idx = l - 1 while idx: if idx > m or mask[idx] and \ - vacmViewTreeFamilySubtree.syntax[idx] != variableName[idx]: + vacmViewTreeFamilySubtree.syntax[idx] != variableName[idx]: break - idx = idx - 1 + idx -= 1 if idx: - continue # no match - else: # no mask + continue # no match + else: # no mask if vacmViewTreeFamilySubtree.syntax != variableName[:l]: - continue # no match + continue # no match # 3.2.5c return error.StatusInformation(errorIndication=errind.accessAllowed) diff --git a/pysnmp/proto/api/__init__.py b/pysnmp/proto/api/__init__.py index 47782bf2..c904896b 100644 --- a/pysnmp/proto/api/__init__.py +++ b/pysnmp/proto/api/__init__.py @@ -1,3 +1,9 @@ +# +# This file is part of pysnmp software. +# +# Copyright (c) 2005-2016, Ilya Etingof +# License: http://pysnmp.sf.net/license.html +# from pysnmp.proto.api import v1, v2c, verdec # Protocol versions diff --git a/pysnmp/proto/api/v1.py b/pysnmp/proto/api/v1.py index b6a8dabf..9bab214e 100644 --- a/pysnmp/proto/api/v1.py +++ b/pysnmp/proto/api/v1.py @@ -31,25 +31,32 @@ SetRequestPDU = rfc1157.SetRequestPDU TrapPDU = rfc1157.TrapPDU Message = rfc1157.Message + class VarBindAPI: - def setOIDVal(self, varBind, oidVal): + @staticmethod + def setOIDVal(varBind, oidVal): (oid, val) = oidVal varBind.setComponentByPosition(0, oid) if val is None: val = null - varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(), val, 1, verifyConstraints=False) + varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(), val, 1, + verifyConstraints=False) return varBind - def getOIDVal(self, varBind): + @staticmethod + def getOIDVal(varBind): return varBind[0], varBind[1].getComponent(1) + apiVarBind = VarBindAPI() getNextRequestID = nextid.Integer(0xffffff) + class PDUAPI: - _errorStatus = rfc1157._errorStatus.clone(0) + _errorStatus = rfc1157.errorStatus.clone(0) _errorIndex = Integer(0) + def setDefaults(self, pdu): pdu.setComponentByPosition( 0, getNextRequestID(), verifyConstraints=False @@ -62,19 +69,24 @@ class PDUAPI: ) pdu.setComponentByPosition(3) - def getRequestID(self, pdu): + @staticmethod + def getRequestID(pdu): return pdu.getComponentByPosition(0) - def setRequestID(self, pdu, value): + @staticmethod + def setRequestID(pdu, value): pdu.setComponentByPosition(0, value) - def getErrorStatus(self, pdu): + @staticmethod + def getErrorStatus(pdu): return pdu.getComponentByPosition(1) - def setErrorStatus(self, pdu, value): + @staticmethod + def setErrorStatus(pdu, value): pdu.setComponentByPosition(1, value) - def getErrorIndex(self, pdu, muteErrors=False): + @staticmethod + def getErrorIndex(pdu, muteErrors=False): errorIndex = pdu.getComponentByPosition(2) if errorIndex > len(pdu[3]): if muteErrors: @@ -84,7 +96,8 @@ class PDUAPI: ) return errorIndex - def setErrorIndex(self, pdu, value): + @staticmethod + def setErrorIndex(pdu, value): pdu.setComponentByPosition(2, value) def setEndOfMibError(self, pdu, errorIndex): @@ -94,19 +107,23 @@ class PDUAPI: def setNoSuchInstanceError(self, pdu, errorIndex): self.setEndOfMibError(pdu, errorIndex) - def getVarBindList(self, pdu): + @staticmethod + def getVarBindList(pdu): return pdu.getComponentByPosition(3) - def setVarBindList(self, pdu, varBindList): - varBindList = pdu.setComponentByPosition(3, varBindList) + @staticmethod + def setVarBindList(pdu, varBindList): + pdu.setComponentByPosition(3, varBindList) - def getVarBinds(self, pdu): + @staticmethod + def getVarBinds(pdu): varBinds = [] for varBind in pdu.getComponentByPosition(3): varBinds.append(apiVarBind.getOIDVal(varBind)) return varBinds - def setVarBinds(self, pdu, varBinds): + @staticmethod + def setVarBinds(pdu, varBinds): varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) varBindList.clear() idx = 0 @@ -135,22 +152,25 @@ class PDUAPI: else: return [apiPDU.getVarBinds(rspPDU)] + apiPDU = PDUAPI() + class TrapPDUAPI: _networkAddress = None _entOid = ObjectIdentifier((1, 3, 6, 1, 4, 1, 20408)) - _genericTrap = rfc1157._genericTrap.clone('coldStart') + _genericTrap = rfc1157.genericTrap.clone('coldStart') _zeroInt = univ.Integer(0) _zeroTime = TimeTicks(0) + def setDefaults(self, pdu): if self._networkAddress is None: try: import socket agentAddress = IpAddress(socket.gethostbyname(socket.gethostname())) - except: + except Exception: agentAddress = IpAddress('0.0.0.0') - self._networkAddress = NetworkAddress().setComponentByPosition(0, agentAddress) + self._networkAddress = NetworkAddress().setComponentByPosition(0, agentAddress) pdu.setComponentByPosition(0, self._entOid, verifyConstraints=False) pdu.setComponentByPosition(1, self._networkAddress, verifyConstraints=False) pdu.setComponentByPosition(2, self._genericTrap, verifyConstraints=False) @@ -158,49 +178,63 @@ class TrapPDUAPI: pdu.setComponentByPosition(4, self._zeroTime, verifyConstraints=False) pdu.setComponentByPosition(5) - def getEnterprise(self, pdu): + @staticmethod + def getEnterprise(pdu): return pdu.getComponentByPosition(0) - def setEnterprise(self, pdu, value): + @staticmethod + def setEnterprise(pdu, value): pdu.setComponentByPosition(0, value) - def getAgentAddr(self, pdu): + @staticmethod + def getAgentAddr(pdu): return pdu.getComponentByPosition(1).getComponentByPosition(0) - def setAgentAddr(self, pdu, value): + @staticmethod + def setAgentAddr(pdu, value): pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(0, value) - def getGenericTrap(self, pdu): + @staticmethod + def getGenericTrap(pdu): return pdu.getComponentByPosition(2) - def setGenericTrap(self, pdu, value): + @staticmethod + def setGenericTrap(pdu, value): pdu.setComponentByPosition(2, value) - def getSpecificTrap(self, pdu): + @staticmethod + def getSpecificTrap(pdu): return pdu.getComponentByPosition(3) - def setSpecificTrap(self, pdu, value): + @staticmethod + def setSpecificTrap(pdu, value): pdu.setComponentByPosition(3, value) - def getTimeStamp(self, pdu): + @staticmethod + def getTimeStamp(pdu): return pdu.getComponentByPosition(4) - def setTimeStamp(self, pdu, value): + @staticmethod + def setTimeStamp(pdu, value): pdu.setComponentByPosition(4, value) - def getVarBindList(self, pdu): + @staticmethod + def getVarBindList(pdu): return pdu.getComponentByPosition(5) - def setVarBindList(self, pdu, varBindList): - varBindList = pdu.setComponentByPosition(5, varBindList) + @staticmethod + def setVarBindList(pdu, varBindList): + pdu.setComponentByPosition(5, varBindList) - def getVarBinds(self, pdu): + @staticmethod + def getVarBinds(pdu): varBinds = [] for varBind in pdu.getComponentByPosition(5): varBinds.append(apiVarBind.getOIDVal(varBind)) return varBinds - def setVarBinds(self, pdu, varBinds): + @staticmethod + def setVarBinds(pdu, varBinds): varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5) varBindList.clear() idx = 0 @@ -211,36 +245,46 @@ class TrapPDUAPI: varBindList.setComponentByPosition(idx) apiVarBind.setOIDVal( varBindList.getComponentByPosition(idx), varBind - ) - idx = idx + 1 + ) + idx += 1 + apiTrapPDU = TrapPDUAPI() + class MessageAPI: - _version = rfc1157._version.clone(0) + _version = rfc1157.version.clone(0) _community = univ.OctetString('public') + def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False) return msg - def getVersion(self, msg): + @staticmethod + def getVersion(msg): return msg.getComponentByPosition(0) - def setVersion(self, msg, value): + @staticmethod + def setVersion(msg, value): msg.setComponentByPosition(0, value) - def getCommunity(self, msg): + @staticmethod + def getCommunity(msg): return msg.getComponentByPosition(1) - def setCommunity(self, msg, value): + @staticmethod + def setCommunity(msg, value): msg.setComponentByPosition(1, value) - def getPDU(self, msg): + @staticmethod + def getPDU(msg): return msg.getComponentByPosition(2).getComponent() - def setPDU(self, msg, value): - msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(value.getTagSet(), value, 1, verifyConstraints=False) + @staticmethod + def setPDU(msg, value): + msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(value.getTagSet(), value, 1, + verifyConstraints=False) def getResponse(self, reqMsg): rspMsg = Message() @@ -250,4 +294,5 @@ class MessageAPI: self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) return rspMsg + apiMessage = MessageAPI() diff --git a/pysnmp/proto/api/v2c.py b/pysnmp/proto/api/v2c.py index 96dcfc67..fa8f6799 100644 --- a/pysnmp/proto/api/v2c.py +++ b/pysnmp/proto/api/v2c.py @@ -46,8 +46,9 @@ getNextRequestID = v1.getNextRequestID apiVarBind = v1.apiVarBind + class PDUAPI(v1.PDUAPI): - _errorStatus = rfc1905._errorStatus.clone(0) + _errorStatus = rfc1905.errorStatus.clone(0) _errorIndex = univ.Integer(0).subtype(subtypeSpec=constraint.ValueRangeConstraint(0, rfc1905.max_bindings)) def getResponse(self, reqPDU): @@ -61,21 +62,24 @@ class PDUAPI(v1.PDUAPI): def setEndOfMibError(self, pdu, errorIndex): varBindList = self.getVarBindList(pdu) - varBindList[errorIndex-1].setComponentByPosition( + varBindList[errorIndex - 1].setComponentByPosition( 1, rfc1905.endOfMibView, verifyConstraints=False ) def setNoSuchInstanceError(self, pdu, errorIndex): varBindList = self.getVarBindList(pdu) - varBindList[errorIndex-1].setComponentByPosition( + varBindList[errorIndex - 1].setComponentByPosition( 1, rfc1905.noSuchInstance, verifyConstraints=False ) + apiPDU = PDUAPI() + class BulkPDUAPI(PDUAPI): - _nonRepeaters = rfc1905._nonRepeaters.clone(0) - _maxRepetitions = rfc1905._maxRepetitions.clone(10) + _nonRepeaters = rfc1905.nonRepeaters.clone(0) + _maxRepetitions = rfc1905.maxRepetitions.clone(10) + def setDefaults(self, pdu): PDUAPI.setDefaults(self, pdu) pdu.setComponentByPosition( @@ -89,34 +93,37 @@ class BulkPDUAPI(PDUAPI): ) pdu.setComponentByPosition(3) - def getNonRepeaters(self, pdu): + @staticmethod + def getNonRepeaters(pdu): return pdu.getComponentByPosition(1) - def setNonRepeaters(self, pdu, value): + @staticmethod + def setNonRepeaters(pdu, value): pdu.setComponentByPosition(1, value) - def getMaxRepetitions(self, pdu): + @staticmethod + def getMaxRepetitions(pdu): return pdu.getComponentByPosition(2) - def setMaxRepetitions(self, pdu, value): + @staticmethod + def setMaxRepetitions(pdu, value): pdu.setComponentByPosition(2, value) def getVarBindTable(self, reqPDU, rspPDU): nonRepeaters = self.getNonRepeaters(reqPDU) - maxRepetitions = self.getMaxRepetitions(reqPDU) reqVarBinds = self.getVarBinds(reqPDU) N = min(int(nonRepeaters), len(reqVarBinds)) - R = max(len(reqVarBinds)-N, 0) + R = max(len(reqVarBinds) - N, 0) rspVarBinds = self.getVarBinds(rspPDU) varBindTable = [] if R: - for i in range(0, len(rspVarBinds)-N, R): - varBindRow = rspVarBinds[:N] + rspVarBinds[N+i:N+R+i] + for i in range(0, len(rspVarBinds) - N, R): + varBindRow = rspVarBinds[:N] + rspVarBinds[N + i:N + R + i] # ignore stray OIDs / non-rectangular table if len(varBindRow) == N + R: varBindTable.append(varBindRow) @@ -125,8 +132,10 @@ class BulkPDUAPI(PDUAPI): return varBindTable + apiBulkPDU = BulkPDUAPI() + class TrapPDUAPI(v1.PDUAPI): sysUpTime = (1, 3, 6, 1, 2, 1, 1, 3, 0) snmpTrapAddress = (1, 3, 6, 1, 6, 3, 18, 1, 3, 0) @@ -135,6 +144,7 @@ class TrapPDUAPI(v1.PDUAPI): snmpTrapEnterprise = (1, 3, 6, 1, 6, 3, 1, 1, 4, 3, 0) _zeroTime = TimeTicks(0) _genTrap = ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)) + def setDefaults(self, pdu): v1.PDUAPI.setDefaults(self, pdu) varBinds = [(self.sysUpTime, self._zeroTime), @@ -142,10 +152,13 @@ class TrapPDUAPI(v1.PDUAPI): (self.snmpTrapOID, self._genTrap)] self.setVarBinds(pdu, varBinds) + apiTrapPDU = TrapPDUAPI() + class MessageAPI(v1.MessageAPI): - _version = rfc1901._version.clone(1) + _version = rfc1901.version.clone(1) + def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False) @@ -159,4 +172,5 @@ class MessageAPI(v1.MessageAPI): self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) return rspMsg + apiMessage = MessageAPI() diff --git a/pysnmp/proto/api/verdec.py b/pysnmp/proto/api/verdec.py index 627d857f..15aa363a 100644 --- a/pysnmp/proto/api/verdec.py +++ b/pysnmp/proto/api/verdec.py @@ -9,6 +9,7 @@ from pyasn1.codec.ber import decoder, eoo from pyasn1.error import PyAsn1Error from pysnmp.proto.error import ProtocolError + def decodeMessageVersion(wholeMsg): try: seq, wholeMsg = decoder.decode( diff --git a/pysnmp/proto/mpmod/base.py b/pysnmp/proto/mpmod/base.py index c24fccaf..b9d5820a 100644 --- a/pysnmp/proto/mpmod/base.py +++ b/pysnmp/proto/mpmod/base.py @@ -7,8 +7,10 @@ from pysnmp.proto.mpmod import cache from pysnmp.proto import error + class AbstractMessageProcessingModel: snmpMsgSpec = NotImplementedError + def __init__(self): self._snmpMsgSpec = self.snmpMsgSpec() # local copy self._cache = cache.Cache() @@ -35,7 +37,7 @@ class AbstractMessageProcessingModel: try: self._cache.popBySendPduHandle(sendPduHandle) except error.ProtocolError: - pass # XXX maybe these should all follow some scheme? + pass # XXX maybe these should all follow some scheme? def receiveTimerTick(self, snmpEngine, timeNow): self._cache.expireCaches() diff --git a/pysnmp/proto/mpmod/cache.py b/pysnmp/proto/mpmod/cache.py index 94dc19ef..43027d5c 100644 --- a/pysnmp/proto/mpmod/cache.py +++ b/pysnmp/proto/mpmod/cache.py @@ -7,9 +7,11 @@ from pysnmp.proto import error from pysnmp import nextid + class Cache: __stateReference = nextid.Integer(0xffffff) __msgID = nextid.Integer(0xffffff) + def __init__(self): self.__msgIdIndex = {} self.__stateReferenceIndex = {} @@ -26,7 +28,7 @@ class Cache: def pushByStateRef(self, stateReference, **msgInfo): if stateReference in self.__stateReferenceIndex: raise error.ProtocolError('Cache dup for stateReference=%s at %s' % (stateReference, self)) - expireAt = self.__expirationTimer+600 + expireAt = self.__expirationTimer + 600 self.__stateReferenceIndex[stateReference] = msgInfo, expireAt # Schedule to expire @@ -56,7 +58,7 @@ class Cache: raise error.ProtocolError( 'Cache dup for msgId=%s at %s' % (msgId, self) ) - expireAt = self.__expirationTimer+600 + expireAt = self.__expirationTimer + 600 self.__msgIdIndex[msgId] = msgInfo, expireAt self.__sendPduHandleIdx[msgInfo['sendPduHandle']] = msgId diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py index 48ec7eb0..fb4341cf 100644 --- a/pysnmp/proto/mpmod/rfc2576.py +++ b/pysnmp/proto/mpmod/rfc2576.py @@ -14,20 +14,24 @@ from pysnmp.proto import rfc3411, errind, error from pysnmp.proto.api import v1, v2c from pysnmp import debug + # Since I have not found a detailed reference to v1MP/v2cMP # inner workings, the following has been patterned from v3MP. Most # references here goes to RFC3412. class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): - messageProcessingModelID = univ.Integer(0) # SNMPv1 + 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): - snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineId = snmpEngineId.syntax # rfc3412: 7.1.1b @@ -36,7 +40,8 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): pdu.setComponentByPosition(1) msgID = self._cache.newMsgID() reqID = pdu.getComponentByPosition(0) - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: PDU request-id %s replaced with unique ID %s' % (reqID, msgID)) + debug.logger & debug.flagMP and debug.logger( + 'prepareOutgoingMessage: PDU request-id %s replaced with unique ID %s' % (reqID, msgID)) # rfc3412: 7.1.4 # Since there's no SNMP engine identification in v1/2c, @@ -48,7 +53,8 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): if not contextName: contextName = null - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) + debug.logger & debug.flagMP and debug.logger( + 'prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) # rfc3412: 7.1.6 scopedPDU = (contextEngineId, contextName, pdu) @@ -73,22 +79,25 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc3412: 7.1.9.a & rfc2576: 5.2.1 --> no-op - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineMaxMessageSize') # fix unique request-id right prior PDU serialization if pdu.tagSet in rfc3411.confirmedClassPDUs: + # noinspection PyUnboundLocalVariable pdu.setComponentByPosition(0, msgID) # rfc3412: 7.1.9.b (securityParameters, wholeMsg) = smHandler.generateRequestMsg( - snmpEngine, self.messageProcessingModelID, globalData, - snmpEngineMaxMessageSize.syntax, securityModel, - snmpEngineId, securityName, securityLevel, scopedPDU - ) + 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: + # noinspection PyUnboundLocalVariable pdu.setComponentByPosition(0, reqID) # rfc3412: 7.1.9.c @@ -131,7 +140,9 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): contextEngineId, contextName, pduVersion, pdu, maxSizeResponseScopedPDU, stateReference, statusInformation): - snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + + snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineId = snmpEngineId.syntax # rfc3412: 7.1.2.b @@ -151,7 +162,9 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): transportDomain = cachedParams['transportDomain'] transportAddress = cachedParams['transportAddress'] - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % (msgID, transportDomain, transportAddress, stateReference)) + debug.logger & debug.flagMP and debug.logger( + 'prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % ( + msgID, transportDomain, transportAddress, stateReference)) # rfc3412: 7.1.3 if statusInformation: @@ -173,7 +186,8 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # rfc3412: 7.1.6 scopedPDU = (contextEngineId, contextName, pdu) - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) + debug.logger & debug.flagMP and debug.logger( + 'prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) msg = self._snmpMsgSpec msg.setComponentByPosition(0, messageProcessingModel) @@ -231,13 +245,14 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): def prepareDataElements(self, snmpEngine, transportDomain, transportAddress, wholeMsg): + mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + # 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, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax += 1 raise error.StatusInformation(errorIndication=errind.parseError) @@ -247,14 +262,13 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): raise error.StatusInformation(errorIndication=errind.parseError) # rfc3412: 7.2.3 - msgVersion = messageProcessingModel = msg.getComponentByPosition(0) + msgVersion = msg.getComponentByPosition(0) # rfc2576: 5.2.1 - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') communityName = msg.getComponentByPosition(1) # transportDomain identifies local enpoint - securityParameters = (communityName, - (transportDomain, transportAddress)) + securityParameters = (communityName, (transportDomain, transportAddress)) messageProcessingModel = int(msg.getComponentByPosition(0)) securityModel = messageProcessingModel + 1 securityLevel = 1 @@ -270,14 +284,15 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): ) # 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)) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: SM returned securityEngineId %r securityName %r' % (securityEngineId, securityName)) # rfc3412: 7.2.6a --> noop @@ -305,7 +320,9 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): # recover original PDU request-id to return to app pdu.setComponentByPosition(0, cachedReqParams['reqID']) - debug.logger & debug.flagMP and debug.logger('prepareDataElements: unique PDU request-id %s replaced with original ID %s' % (msgID, cachedReqParams['reqID'])) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: unique PDU request-id %s replaced with original ID %s' % ( + msgID, cachedReqParams['reqID'])) # 7.2.10b sendPduHandle = cachedReqParams['sendPduHandle'] @@ -321,11 +338,12 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): if pduType in rfc3411.responseClassPDUs: # rfc3412: 7.2.12a -> noop # rfc3412: 7.2.12b + # noinspection PyUnboundLocalVariable 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) @@ -364,10 +382,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): reqID = pdu.getComponentByPosition(0) msgID = self._cache.newMsgID() pdu.setComponentByPosition(0, msgID) - debug.logger & debug.flagMP and debug.logger('prepareDataElements: received PDU request-id %s replaced with unique ID %s' % (reqID, msgID)) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: received PDU request-id %s replaced with unique ID %s' % (reqID, msgID)) # rfc3412: 7.2.13a - snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if securityEngineId != snmpEngineId.syntax: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( @@ -405,7 +424,8 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): snmpEngine, 'rfc2576.prepareDataElements:confirmed' ) - debug.logger & debug.flagMP and debug.logger('prepareDataElements: cached by new stateReference %s' % stateReference) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: cached by new stateReference %s' % stateReference) # rfc3412: 7.2.13c return (messageProcessingModel, securityModel, securityName, @@ -448,6 +468,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation(errorIndication=errind.unsupportedPDUtype) + class SnmpV2cMessageProcessingModel(SnmpV1MessageProcessingModel): - messageProcessingModelID = univ.Integer(1) # SNMPv2c + messageProcessingModelID = univ.Integer(1) # SNMPv2c snmpMsgSpec = v2c.Message diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py index 103719bf..90f3dd9b 100644 --- a/pysnmp/proto/mpmod/rfc3412.py +++ b/pysnmp/proto/mpmod/rfc3412.py @@ -15,6 +15,7 @@ from pysnmp import debug # API to rfc1905 protocol objects pMod = api.protoModules[api.protoVersion2c] + # SNMPv3 message format class ScopedPDU(univ.Sequence): @@ -24,28 +25,36 @@ class ScopedPDU(univ.Sequence): namedtype.NamedType('data', rfc1905.PDUs()) ) + class ScopedPduData(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('plaintext', ScopedPDU()), namedtype.NamedType('encryptedPDU', univ.OctetString()), ) + class HeaderData(univ.Sequence): componentType = namedtype.NamedTypes( - namedtype.NamedType('msgID', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), - namedtype.NamedType('msgMaxSize', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647))), + namedtype.NamedType('msgID', + univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), + namedtype.NamedType('msgMaxSize', + univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647))), namedtype.NamedType('msgFlags', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 1))), - namedtype.NamedType('msgSecurityModel', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))) + namedtype.NamedType('msgSecurityModel', + univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))) ) + class SNMPv3Message(univ.Sequence): componentType = namedtype.NamedTypes( - namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), + 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', (1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0): 'notInTimeWindow', @@ -54,8 +63,9 @@ _snmpErrors = {(1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0): 'unsupportedSecLevel', (1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0): 'wrongDigest', (1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0): 'decryptionError'} + class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): - messageProcessingModelID = univ.Integer(3) # SNMPv3 + messageProcessingModelID = univ.Integer(3) # SNMPv3 snmpMsgSpec = SNMPv3Message _emptyStr = univ.OctetString('') _msgFlags = {0: univ.OctetString('\x00'), @@ -64,6 +74,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): 4: univ.OctetString('\x04'), 5: univ.OctetString('\x05'), 7: univ.OctetString('\x07')} + def __init__(self): AbstractMessageProcessingModel.__init__(self) self.__scopedPDU = ScopedPDU() @@ -74,9 +85,9 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): def getPeerEngineInfo(self, transportDomain, transportAddress): k = transportDomain, transportAddress if k in self.__engineIdCache: - return self.__engineIdCache[k]['securityEngineId'], \ - self.__engineIdCache[k]['contextEngineId'], \ - self.__engineIdCache[k]['contextName'] + return (self.__engineIdCache[k]['securityEngineId'], + self.__engineIdCache[k]['contextEngineId'], + self.__engineIdCache[k]['contextName']) else: return None, None, None @@ -86,7 +97,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, expectResponse, sendPduHandle): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # 7.1.1b @@ -100,7 +112,9 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): else: peerSnmpEngineData = None - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % (peerSnmpEngineData, transportDomain, transportAddress)) + debug.logger & debug.flagMP and debug.logger( + 'prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % ( + peerSnmpEngineData, transportDomain, transportAddress)) # 7.1.4 if contextEngineId is None: @@ -117,7 +131,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if not contextName: contextName = self._emptyStr - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) + debug.logger & debug.flagMP and debug.logger( + 'prepareOutgoingMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) # 7.1.6 scopedPDU = self.__scopedPDU @@ -140,7 +155,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.1.7b headerData.setComponentByPosition(0, msgID, verifyConstraints=False) - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') # 7.1.7c # XXX need to coerce MIB value as it has incompatible constraints set @@ -153,16 +169,16 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if securityLevel == 1: pass elif securityLevel == 2: - msgFlags = msgFlags | 0x01 + msgFlags |= 0x01 elif securityLevel == 3: - msgFlags = msgFlags | 0x03 + msgFlags |= 0x03 else: raise error.ProtocolError( 'Unknown securityLevel %s' % securityLevel ) if pdu.tagSet in rfc3411.confirmedClassPDUs: - msgFlags = msgFlags | 0x04 + msgFlags |= 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False @@ -212,15 +228,17 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): else: securityEngineId = peerSnmpEngineData['securityEngineId'] - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % (securityModel, securityEngineId, securityName, securityLevel)) + 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 - ) + snmpEngine, self.messageProcessingModelID, msg, + snmpEngineMaxMessageSize.syntax, securityModel, + securityEngineId, securityName, securityLevel, scopedPDU + ) # Message size constraint verification if len(wholeMsg) > snmpEngineMaxMessageSize.syntax: @@ -262,7 +280,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): contextEngineId, contextName, pduVersion, pdu, maxSizeResponseScopedPDU, stateReference, statusInformation): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # 7.1.2.b @@ -279,21 +298,21 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): transportDomain = cachedParams['transportDomain'] transportAddress = cachedParams['transportAddress'] - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % (stateReference)) + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % stateReference) # 7.1.3 if statusInformation is not None and 'oid' in statusInformation: # 7.1.3a - if pdu is not None: + if pdu is None: + pduType = None + else: requestID = pdu.getComponentByPosition(0) pduType = pdu.tagSet - else: - pduType = None # 7.1.3b if pdu is None and not reportableFlag or \ - pduType is not None and \ - pduType not in rfc3411.confirmedClassPDUs: + pduType is not None and \ + pduType not in rfc3411.confirmedClassPDUs: raise error.StatusInformation( errorIndication=errind.loopTerminated ) @@ -306,6 +325,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if pdu is None: pMod.apiPDU.setRequestID(reportPDU, 0) else: + # noinspection PyUnboundLocalVariable pMod.apiPDU.setRequestID(reportPDU, requestID) # 7.1.3d.1 @@ -329,7 +349,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.1.3e pdu = reportPDU - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation) + debug.logger & debug.flagMP and debug.logger( + 'prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation) # 7.1.4 if not contextEngineId: contextEngineId = snmpEngineID # XXX impl-dep manner @@ -338,7 +359,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if not contextName: contextName = self._emptyStr - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) + debug.logger & debug.flagMP and debug.logger( + 'prepareResponseMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) # 7.1.6 scopedPDU = self.__scopedPDU @@ -361,7 +383,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.1.7b headerData.setComponentByPosition(0, msgID, verifyConstraints=False) - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') # 7.1.7c # XXX need to coerce MIB value as it has incompatible constraints set @@ -374,14 +397,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if securityLevel == 1: pass elif securityLevel == 2: - msgFlags = msgFlags | 0x01 + msgFlags |= 0x01 elif securityLevel == 3: - msgFlags = msgFlags | 0x03 + msgFlags |= 0x03 else: raise error.ProtocolError('Unknown securityLevel %s' % securityLevel) if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed? - msgFlags = msgFlags | 0x04 + msgFlags |= 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False @@ -399,17 +422,19 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): else: 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)) + 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 - ) + snmpEngine, self.messageProcessingModelID, msg, + snmpEngineMaxMessageSize.syntax, securityModel, + snmpEngineID, securityName, securityLevel, scopedPDU, + securityStateReference + ) except error.StatusInformation: # 7.1.8.b raise @@ -449,7 +474,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): 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, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', + 'snmpInASNParseErrs') snmpInASNParseErrs.syntax += 1 raise error.StatusInformation(errorIndication=errind.parseError) @@ -467,11 +493,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): securityModel = headerData.getComponentByPosition(3) securityParameters = msg.getComponentByPosition(2) - debug.logger & debug.flagMP and debug.logger('prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (msgVersion, msgID, securityModel)) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % ( + msgVersion, msgID, securityModel)) # 7.2.4 if securityModel not in snmpEngine.securityModels: - snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownSecurityModels') + snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + '__SNMP-MPD-MIB', 'snmpUnknownSecurityModels') snmpUnknownSecurityModels.syntax += 1 raise error.StatusInformation(errorIndication=errind.unsupportedSecurityModel) @@ -483,7 +512,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): elif (msgFlags & 0x03) == 0x03: securityLevel = 3 else: - snmpInvalidMsgs = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpInvalidMsgs') + snmpInvalidMsgs = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', + 'snmpInvalidMsgs') snmpInvalidMsgs.syntax += 1 raise error.StatusInformation(errorIndication=errind.invalidMsg) @@ -498,15 +528,16 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): (securityEngineId, securityName, scopedPDU, maxSizeResponseScopedPDU, securityStateReference) = smHandler.processIncomingMsg( - snmpEngine, messageProcessingModel, maxMessageSize, - securityParameters, securityModel, securityLevel, - wholeMsg, msg - ) + 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) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: SM failed, statusInformation %s' % statusInformation) if 'errorIndication' in statusInformation: # 7.2.6a if 'oid' in statusInformation: @@ -579,14 +610,17 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): self.__engineIdCacheExpQueue[expireAt] = [] self.__engineIdCacheExpQueue[expireAt].append(k) - debug.logger & debug.flagMP and debug.logger('prepareDataElements: cache securityEngineId %r for %r %r' % (securityEngineId, transportDomain, transportAddress)) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: cache securityEngineId %r for %r %r' % ( + securityEngineId, transportDomain, transportAddress)) - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', + 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # 7.2.7 XXX PDU would be parsed here? contextEngineId, contextName, pdu = scopedPDU - pdu = pdu.getComponent() # PDUs + pdu = pdu.getComponent() # PDUs # 7.2.8 pduVersion = api.protoVersion2c @@ -596,7 +630,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.2.10 if pduType in rfc3411.responseClassPDUs or \ - pduType in rfc3411.internalClassPDUs: + pduType in rfc3411.internalClassPDUs: # 7.2.10a try: cachedReqParams = self._cache.popByMsgId(msgID) @@ -610,7 +644,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): else: sendPduHandle = None - debug.logger & debug.flagMP and debug.logger('prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID)) + debug.logger & debug.flagMP and debug.logger( + 'prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID)) # 7.2.11 if pduType in rfc3411.internalClassPDUs: @@ -623,6 +658,10 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): oid=varBinds[0][0], val=varBinds[0][1], sendPduHandle=sendPduHandle ) + else: + statusInformation = error.StatusInformation( + sendPduHandle=sendPduHandle + ) # 7.2.11b (incomplete implementation) @@ -646,7 +685,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): smHandler.releaseStateInformation(securityStateReference) # 7.2.11d - stateReference = None + # no-op # 7.2.11e XXX may need to pass Reports up to app in some cases... raise statusInformation @@ -658,11 +697,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): # 7.2.12a -> noop # 7.2.12b + # noinspection PyUnboundLocalVariable 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 diff --git a/pysnmp/proto/proxy/rfc2576.py b/pysnmp/proto/proxy/rfc2576.py index 7d2f379d..771d6912 100644 --- a/pysnmp/proto/proxy/rfc2576.py +++ b/pysnmp/proto/proxy/rfc2576.py @@ -22,7 +22,7 @@ __v1ToV2ValueMap = { v1.Opaque.tagSet: v2c.Opaque() } -__v2ToV1ValueMap = { # XXX do not re-create same-type items? +__v2ToV1ValueMap = { # XXX do not re-create same-type items? v2c.Integer32.tagSet: v1.Integer(), v2c.OctetString.tagSet: v1.OctetString(), v2c.Null.tagSet: v1.Null(), @@ -50,7 +50,7 @@ __v2ToV1PduMap = { v2c.SetRequestPDU.tagSet: v1.SetRequestPDU(), v2c.ResponsePDU.tagSet: v1.GetResponsePDU(), v2c.SNMPv2TrapPDU.tagSet: v1.TrapPDU(), - v2c.GetBulkRequestPDU.tagSet: v1.GetNextRequestPDU() # 4.1.1 + v2c.GetBulkRequestPDU.tagSet: v1.GetNextRequestPDU() # 4.1.1 } # Trap map @@ -76,15 +76,15 @@ __v2ToV1TrapMap = { # 4.3 __v2ToV1ErrorMap = { - 0: 0, - 1: 1, - 5: 5, + 0: 0, + 1: 1, + 5: 5, 10: 3, - 9: 3, - 7: 3, - 8: 3, + 9: 3, + 7: 3, + 8: 3, 12: 3, - 6: 2, + 6: 2, 17: 2, 11: 2, 18: 2, @@ -96,6 +96,7 @@ __v2ToV1ErrorMap = { __zeroInt = v1.Integer(0) + def v1ToV2(v1Pdu, origV2Pdu=None): pduType = v1Pdu.tagSet v2Pdu = __v1ToV2PduMap[pduType].clone() @@ -112,8 +113,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None): # 3.1.2 genericTrap = v1.apiTrapPDU.getGenericTrap(v1Pdu) if genericTrap == 6: - snmpTrapOIDParam = v1.apiTrapPDU.getEnterprise(v1Pdu) + (0,) + \ - (int(v1.apiTrapPDU.getSpecificTrap(v1Pdu)),) + snmpTrapOIDParam = v1.apiTrapPDU.getEnterprise(v1Pdu) + (0, int(v1.apiTrapPDU.getSpecificTrap(v1Pdu))) # 3.1.3 else: @@ -146,15 +146,11 @@ def v1ToV2(v1Pdu, origV2Pdu=None): # 4.1.2.2.1&2 errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu)) errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu, muteErrors=True)) - if errorStatus == 2: # noSuchName + if errorStatus == 2: # noSuchName if origV2Pdu.tagSet == v2c.GetNextRequestPDU.tagSet: - v2VarBinds = [ - (o, rfc1905.endOfMibView) for o, v in v2VarBinds - ] + v2VarBinds = [(o, rfc1905.endOfMibView) for o, v in v2VarBinds] else: - v2VarBinds = [ - (o, rfc1905.noSuchObject) for o, v in v2VarBinds - ] + v2VarBinds = [(o, rfc1905.noSuchObject) for o, v in v2VarBinds] v2c.apiPDU.setErrorStatus(v2Pdu, 0) v2c.apiPDU.setErrorIndex(v2Pdu, 0) else: @@ -162,7 +158,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None): v2c.apiPDU.setErrorStatus(v2Pdu, errorStatus) v2c.apiPDU.setErrorIndex(v2Pdu, errorIndex) - # 4.1.2.1 --> no-op + # 4.1.2.1 --> no-op elif pduType in rfc3411.confirmedClassPDUs: v2c.apiPDU.setErrorStatus(v2Pdu, 0) @@ -177,6 +173,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None): return v2Pdu + def v2ToV1(v2Pdu, origV1Pdu=None): debug.logger & debug.flagPrx and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint()) @@ -238,9 +235,9 @@ def v2ToV1(v2Pdu, origV1Pdu=None): __v2VarBinds = [] for oid, val in v2VarBinds[2:]: if oid in __v2ToV1TrapMap or \ - oid in (v2c.apiTrapPDU.sysUpTime, - v2c.apiTrapPDU.snmpTrapAddress, - v2c.apiTrapPDU.snmpTrapEnterprise): + oid in (v2c.apiTrapPDU.sysUpTime, + v2c.apiTrapPDU.snmpTrapAddress, + v2c.apiTrapPDU.snmpTrapEnterprise): continue __v2VarBinds.append((oid, val)) v2VarBinds = __v2VarBinds @@ -252,14 +249,14 @@ def v2ToV1(v2Pdu, origV1Pdu=None): v1.apiPDU.setErrorIndex(v1Pdu, __zeroInt) if pduType in rfc3411.responseClassPDUs: - idx = len(v2VarBinds)-1 + idx = len(v2VarBinds) - 1 while idx >= 0: # 4.1.2.1 oid, val = v2VarBinds[idx] if v2c.Counter64.tagSet == val.tagSet: if origV1Pdu.tagSet == v1.GetRequestPDU.tagSet: v1.apiPDU.setErrorStatus(v1Pdu, 2) - v1.apiPDU.setErrorIndex(v1Pdu, idx+1) + v1.apiPDU.setErrorIndex(v1Pdu, idx + 1) break elif origV1Pdu.tagSet == v1.GetNextRequestPDU.tagSet: raise error.StatusInformation(idx=idx, pdu=v2Pdu) @@ -271,7 +268,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None): v2c.NoSuchInstance.tagSet, v2c.EndOfMibView.tagSet): v1.apiPDU.setErrorStatus(v1Pdu, 2) - v1.apiPDU.setErrorIndex(v1Pdu, idx+1) + v1.apiPDU.setErrorIndex(v1Pdu, idx + 1) idx -= 1 @@ -280,7 +277,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None): if v2ErrorStatus: v1.apiPDU.setErrorStatus( v1Pdu, __v2ToV1ErrorMap.get(v2ErrorStatus, 5) - ) + ) v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu, muteErrors=True)) elif pduType in rfc3411.confirmedClassPDUs: @@ -289,7 +286,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None): # Translate Var-Binds if pduType in rfc3411.responseClassPDUs and \ - v1.apiPDU.getErrorStatus(v1Pdu): + v1.apiPDU.getErrorStatus(v1Pdu): v1VarBinds = v1.apiPDU.getVarBinds(origV1Pdu) else: for oid, v2Val in v2VarBinds: diff --git a/pysnmp/proto/rfc1157.py b/pysnmp/proto/rfc1157.py index 5bf3d429..97b4215a 100644 --- a/pysnmp/proto/rfc1157.py +++ b/pysnmp/proto/rfc1157.py @@ -18,12 +18,12 @@ class VarBind(univ.Sequence): class VarBindList(univ.SequenceOf): componentType = VarBind() -_errorStatus = univ.Integer(namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5))) +errorStatus = univ.Integer(namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5))) class _RequestBase(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', univ.Integer()), - namedtype.NamedType('error-status', _errorStatus), + namedtype.NamedType('error-status', errorStatus), namedtype.NamedType('error-index', univ.Integer()), namedtype.NamedType('variable-bindings', VarBindList()) ) @@ -45,7 +45,7 @@ class SetRequestPDU(_RequestBase): tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3) ) -_genericTrap = univ.Integer().clone(namedValues=namedval.NamedValues(('coldStart', 0), ('warmStart', 1), ('linkDown', 2), ('linkUp', 3), ('authenticationFailure', 4), ('egpNeighborLoss', 5), ('enterpriseSpecific', 6))) +genericTrap = univ.Integer().clone(namedValues=namedval.NamedValues(('coldStart', 0), ('warmStart', 1), ('linkDown', 2), ('linkUp', 3), ('authenticationFailure', 4), ('egpNeighborLoss', 5), ('enterpriseSpecific', 6))) class TrapPDU(univ.Sequence): tagSet = univ.Sequence.tagSet.tagImplicitly( @@ -54,7 +54,7 @@ class TrapPDU(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('enterprise', univ.ObjectIdentifier()), namedtype.NamedType('agent-addr', rfc1155.NetworkAddress()), - namedtype.NamedType('generic-trap', _genericTrap), + namedtype.NamedType('generic-trap', genericTrap), namedtype.NamedType('specific-trap', univ.Integer()), namedtype.NamedType('time-stamp', rfc1155.TimeTicks()), namedtype.NamedType('variable-bindings', VarBindList()) @@ -69,11 +69,11 @@ class PDUs(univ.Choice): namedtype.NamedType('trap', TrapPDU()) ) -_version = univ.Integer(namedValues=namedval.NamedValues(('version-1', 0))) +version = univ.Integer(namedValues=namedval.NamedValues(('version-1', 0))) class Message(univ.Sequence): componentType = namedtype.NamedTypes( - namedtype.NamedType('version', _version), + namedtype.NamedType('version', version), namedtype.NamedType('community', univ.OctetString()), namedtype.NamedType('data', PDUs()) ) diff --git a/pysnmp/proto/rfc1901.py b/pysnmp/proto/rfc1901.py index 996fb629..ca72301b 100644 --- a/pysnmp/proto/rfc1901.py +++ b/pysnmp/proto/rfc1901.py @@ -7,11 +7,11 @@ from pyasn1.type import univ, namedtype, namedval from pysnmp.proto import rfc1905 -_version = univ.Integer(namedValues=namedval.NamedValues(('version-2c', 1))) +version = univ.Integer(namedValues=namedval.NamedValues(('version-2c', 1))) class Message(univ.Sequence): componentType = namedtype.NamedTypes( - namedtype.NamedType('version', _version), + namedtype.NamedType('version', version), namedtype.NamedType('community', univ.OctetString()), namedtype.NamedType('data', rfc1905.PDUs()) ) diff --git a/pysnmp/proto/rfc1905.py b/pysnmp/proto/rfc1905.py index b8189a3f..0b7136a8 100644 --- a/pysnmp/proto/rfc1905.py +++ b/pysnmp/proto/rfc1905.py @@ -72,26 +72,26 @@ class VarBindList(univ.SequenceOf): 0, max_bindings ) -_errorStatus = univ.Integer(namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5), ('noAccess', 6), ('wrongType', 7), ('wrongLength', 8), ('wrongEncoding', 9), ('wrongValue', 10), ('noCreation', 11), ('inconsistentValue', 12), ('resourceUnavailable', 13), ('commitFailed', 14), ('undoFailed', 15), ('authorizationError', 16), ('notWritable', 17), ('inconsistentName', 18))) +errorStatus = univ.Integer(namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5), ('noAccess', 6), ('wrongType', 7), ('wrongLength', 8), ('wrongEncoding', 9), ('wrongValue', 10), ('noCreation', 11), ('inconsistentValue', 12), ('resourceUnavailable', 13), ('commitFailed', 14), ('undoFailed', 15), ('authorizationError', 16), ('notWritable', 17), ('inconsistentName', 18))) # Base class for a non-bulk PDU class PDU(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', rfc1902.Integer32()), - namedtype.NamedType('error-status', _errorStatus), + namedtype.NamedType('error-status', errorStatus), namedtype.NamedType('error-index', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings))), namedtype.NamedType('variable-bindings', VarBindList()) ) -_nonRepeaters = univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings)) -_maxRepetitions = univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings)) +nonRepeaters = univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings)) +maxRepetitions = univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings)) # Base class for bulk PDU class BulkPDU(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', rfc1902.Integer32()), - namedtype.NamedType('non-repeaters', _nonRepeaters), - namedtype.NamedType('max-repetitions', _maxRepetitions), + namedtype.NamedType('non-repeaters', nonRepeaters), + namedtype.NamedType('max-repetitions', maxRepetitions), namedtype.NamedType('variable-bindings', VarBindList()) ) diff --git a/pysnmp/proto/secmod/eso/priv/aes192.py b/pysnmp/proto/secmod/eso/priv/aes192.py index 1fc08d4b..0de69551 100644 --- a/pysnmp/proto/secmod/eso/priv/aes192.py +++ b/pysnmp/proto/secmod/eso/priv/aes192.py @@ -6,6 +6,7 @@ # from pysnmp.proto.secmod.eso.priv import aesbase + class Aes192(aesbase.AbstractAes): """AES 192/256 bit encryption (Internet draft) diff --git a/pysnmp/proto/secmod/eso/priv/aes256.py b/pysnmp/proto/secmod/eso/priv/aes256.py index 4d5cbc71..c6ec1ab9 100644 --- a/pysnmp/proto/secmod/eso/priv/aes256.py +++ b/pysnmp/proto/secmod/eso/priv/aes256.py @@ -6,6 +6,7 @@ # from pysnmp.proto.secmod.eso.priv import aesbase + class Aes256(aesbase.AbstractAes): """AES 192/256 bit encryption (Internet draft) diff --git a/pysnmp/proto/secmod/eso/priv/aesbase.py b/pysnmp/proto/secmod/eso/priv/aesbase.py index 921b0197..f67bdfe0 100644 --- a/pysnmp/proto/secmod/eso/priv/aesbase.py +++ b/pysnmp/proto/secmod/eso/priv/aesbase.py @@ -9,13 +9,17 @@ from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import error from math import ceil + try: from hashlib import md5, sha1 except ImportError: - import md5, sha + import md5 + import sha + md5 = md5.new sha1 = sha.new + class AbstractAes(aes.Aes): serviceID = () keySize = 0 @@ -24,14 +28,15 @@ class AbstractAes(aes.Aes): def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) - while ceil(self.keySize//len(localPrivKey)): + while ceil(self.keySize // len(localPrivKey)): + # noinspection PyDeprecation,PyCallingNonCallable localPrivKey = localPrivKey + md5(localPrivKey).digest() elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) - while ceil(self.keySize//len(localPrivKey)): + while ceil(self.keySize // len(localPrivKey)): localPrivKey = localPrivKey + sha1(localPrivKey).digest() else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) + ) return localPrivKey[:self.keySize] diff --git a/pysnmp/proto/secmod/eso/priv/des3.py b/pysnmp/proto/secmod/eso/priv/des3.py index 8b4b19d3..e91f8fed 100644 --- a/pysnmp/proto/secmod/eso/priv/des3.py +++ b/pysnmp/proto/secmod/eso/priv/des3.py @@ -16,7 +16,9 @@ from math import ceil try: from hashlib import md5, sha1 except ImportError: - import md5, sha + import md5 + import sha + md5 = md5.new sha1 = sha.new @@ -27,6 +29,7 @@ except ImportError: random.seed() + # 5.1.1 class Des3(base.AbstractEncryptionService): @@ -34,7 +37,7 @@ class Des3(base.AbstractEncryptionService): http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt """ - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol keySize = 32 _localInt = random.randrange(0, 0xffffffff) @@ -46,22 +49,23 @@ class Des3(base.AbstractEncryptionService): else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) + ) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) - while ceil(self.keySize//len(localPrivKey)): + while ceil(self.keySize // len(localPrivKey)): + # noinspection PyDeprecation,PyCallingNonCallable localPrivKey = localPrivKey + md5(localPrivKey).digest() elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) - while ceil(self.keySize//len(localPrivKey)): + while ceil(self.keySize // len(localPrivKey)): localPrivKey = localPrivKey + sha1(localPrivKey).digest() else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) - ) - return localPrivKey[:self.keySize] # key+IV + ) + return localPrivKey[:self.keySize] # key+IV # 5.1.1.1 def __getEncryptionKey(self, privKey, snmpEngineBoots): @@ -72,42 +76,43 @@ class Des3(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 - ] + 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 + self._localInt += 1 # salt not yet hashed XXX - return des3Key.asOctets(), \ - univ.OctetString(salt).asOctets(), \ - univ.OctetString(map(lambda x, y: x^y, salt, preIV.asNumbers())).asOctets() + return (des3Key.asOctets(), + univ.OctetString(salt).asOctets(), + univ.OctetString(map(lambda x, y: x ^ y, salt, preIV.asNumbers())).asOctets()) - def __getDecryptionKey(self, privKey, salt): - return privKey[:24].asOctets(), \ - univ.OctetString(map(lambda x, y: x^y, salt.asNumbers(), privKey[24:32].asNumbers())).asOctets() + @staticmethod + def __getDecryptionKey(privKey, salt): + return (privKey[:24].asOctets(), + univ.OctetString(map(lambda x, y: x ^ y, salt.asNumbers(), privKey[24:32].asNumbers())).asOctets()) # 5.1.1.2 def encryptData(self, encryptKey, privParameters, dataToEncrypt): if DES3 is None: raise error.StatusInformation( errorIndication=errind.encryptionError - ) + ) snmpEngineBoots, snmpEngineTime, salt = privParameters des3Key, salt, iv = self.__getEncryptionKey( encryptKey, snmpEngineBoots - ) + ) des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) @@ -118,8 +123,9 @@ class Des3(base.AbstractEncryptionService): ciphertext = null while plaintext: cipherblock = des3Obj.encrypt( - univ.OctetString(map(lambda x, y: x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(plaintext[:8]).asNumbers())).asOctets() - ) + univ.OctetString(map(lambda x, y: x ^ y, univ.OctetString(cipherblock).asNumbers(), + univ.OctetString(plaintext[:8]).asNumbers())).asOctets() + ) ciphertext = ciphertext + cipherblock plaintext = plaintext[8:] @@ -130,20 +136,20 @@ class Des3(base.AbstractEncryptionService): if DES3 is None: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) snmpEngineBoots, snmpEngineTime, salt = privParameters if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) des3Key, iv = self.__getDecryptionKey(decryptKey, salt) if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError - ) + ) des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) @@ -151,7 +157,9 @@ class Des3(base.AbstractEncryptionService): ciphertext = encryptedData.asOctets() cipherblock = iv while ciphertext: - plaintext = plaintext + univ.OctetString(map(lambda x, y: x ^ y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(des3Obj.decrypt(ciphertext[:8])).asNumbers())).asOctets() + plaintext = plaintext + univ.OctetString(map(lambda x, y: x ^ y, univ.OctetString(cipherblock).asNumbers(), + univ.OctetString( + des3Obj.decrypt(ciphertext[:8])).asNumbers())).asOctets() cipherblock = ciphertext[:8] ciphertext = ciphertext[8:] diff --git a/pysnmp/proto/secmod/rfc3414/auth/base.py b/pysnmp/proto/secmod/rfc3414/auth/base.py index 4f57559d..9f842fe5 100644 --- a/pysnmp/proto/secmod/rfc3414/auth/base.py +++ b/pysnmp/proto/secmod/rfc3414/auth/base.py @@ -6,6 +6,7 @@ # from pysnmp.proto import errind, error + class AbstractAuthenticationService: serviceID = None -- cgit v1.2.1