summaryrefslogtreecommitdiff
path: root/pysnmp
diff options
context:
space:
mode:
authorIlya Etingof <etingof@gmail.com>2019-02-10 16:38:35 +0100
committerGitHub <noreply@github.com>2019-02-10 16:38:35 +0100
commit588b9b902d191d8010cb6b247fcb07887d59542c (patch)
tree419b01d2598e91331db784ac3a6675324aba8c24 /pysnmp
parent9664858b145140a4fbb2a22b633c1ab41c2555bd (diff)
downloadpysnmp-git-588b9b902d191d8010cb6b247fcb07887d59542c.tar.gz
Uppercase global constants (#238)
This is a massive patch essentially upper-casing global/class attributes that mean to be constants. Some previously exposed constants have been preserved for compatibility reasons (notably, in `hlapi`), though the rest might break user code relying on pysnmp 4.
Diffstat (limited to 'pysnmp')
-rw-r--r--pysnmp/carrier/asyncio/base.py2
-rw-r--r--pysnmp/carrier/asyncio/dgram/base.py23
-rw-r--r--pysnmp/carrier/asyncio/dgram/udp.py4
-rw-r--r--pysnmp/carrier/asyncio/dgram/udp6.py4
-rw-r--r--pysnmp/carrier/asyncore/base.py28
-rw-r--r--pysnmp/carrier/asyncore/dgram/base.py56
-rw-r--r--pysnmp/carrier/asyncore/dgram/udp.py6
-rw-r--r--pysnmp/carrier/asyncore/dgram/udp6.py6
-rw-r--r--pysnmp/carrier/asyncore/dgram/unix.py6
-rw-r--r--pysnmp/carrier/asyncore/dispatch.py6
-rw-r--r--pysnmp/carrier/base.py6
-rw-r--r--pysnmp/carrier/sockfix.py2
-rw-r--r--pysnmp/carrier/sockmsg.py5
-rw-r--r--pysnmp/carrier/twisted/base.py2
-rw-r--r--pysnmp/carrier/twisted/dgram/base.py8
-rw-r--r--pysnmp/carrier/twisted/dgram/udp.py4
-rw-r--r--pysnmp/carrier/twisted/dgram/unix.py7
-rw-r--r--pysnmp/carrier/twisted/dispatch.py4
-rw-r--r--pysnmp/debug.py66
-rw-r--r--pysnmp/entity/config.py100
-rw-r--r--pysnmp/entity/engine.py24
-rw-r--r--pysnmp/entity/rfc3413/cmdgen.py20
-rw-r--r--pysnmp/entity/rfc3413/cmdrsp.py18
-rw-r--r--pysnmp/entity/rfc3413/config.py10
-rw-r--r--pysnmp/entity/rfc3413/context.py10
-rw-r--r--pysnmp/entity/rfc3413/ntforg.py40
-rw-r--r--pysnmp/entity/rfc3413/ntfrcv.py12
-rw-r--r--pysnmp/error.py1
-rw-r--r--pysnmp/hlapi/transport.py12
-rw-r--r--pysnmp/hlapi/v1arch/asyncore/cmdgen.py8
-rw-r--r--pysnmp/hlapi/v1arch/asyncore/dispatch.py2
-rw-r--r--pysnmp/hlapi/v1arch/asyncore/ntforg.py8
-rw-r--r--pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py10
-rw-r--r--pysnmp/hlapi/v1arch/asyncore/transport.py8
-rw-r--r--pysnmp/hlapi/v1arch/dispatch.py11
-rw-r--r--pysnmp/hlapi/v3arch/asyncio/cmdgen.py41
-rw-r--r--pysnmp/hlapi/v3arch/asyncio/ntforg.py12
-rw-r--r--pysnmp/hlapi/v3arch/asyncio/transport.py8
-rw-r--r--pysnmp/hlapi/v3arch/asyncore/cmdgen.py28
-rw-r--r--pysnmp/hlapi/v3arch/asyncore/ntforg.py10
-rw-r--r--pysnmp/hlapi/v3arch/asyncore/sync/compat/cmdgen.py1
-rw-r--r--pysnmp/hlapi/v3arch/asyncore/transport.py8
-rw-r--r--pysnmp/hlapi/v3arch/auth.py147
-rw-r--r--pysnmp/hlapi/v3arch/lcd.py16
-rw-r--r--pysnmp/hlapi/v3arch/twisted/cmdgen.py36
-rw-r--r--pysnmp/hlapi/v3arch/twisted/ntforg.py10
-rw-r--r--pysnmp/hlapi/v3arch/twisted/transport.py2
-rw-r--r--pysnmp/proto/acmod/rfc3415.py4
-rw-r--r--pysnmp/proto/acmod/void.py4
-rw-r--r--pysnmp/proto/api/__init__.py6
-rw-r--r--pysnmp/proto/api/verdec.py5
-rw-r--r--pysnmp/proto/errind.py40
-rw-r--r--pysnmp/proto/error.py2
-rw-r--r--pysnmp/proto/mpmod/base.py4
-rw-r--r--pysnmp/proto/mpmod/rfc2576.py48
-rw-r--r--pysnmp/proto/mpmod/rfc3412.py83
-rw-r--r--pysnmp/proto/proxy/rfc2576.py74
-rw-r--r--pysnmp/proto/rfc1155.py1
-rw-r--r--pysnmp/proto/rfc3411.py68
-rw-r--r--pysnmp/proto/rfc3412.py42
-rw-r--r--pysnmp/proto/secmod/base.py2
-rw-r--r--pysnmp/proto/secmod/eso/priv/aes192.py8
-rw-r--r--pysnmp/proto/secmod/eso/priv/aes256.py8
-rw-r--r--pysnmp/proto/secmod/eso/priv/aesbase.py33
-rw-r--r--pysnmp/proto/secmod/eso/priv/des3.py43
-rw-r--r--pysnmp/proto/secmod/rfc2576.py54
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/base.py2
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py29
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/hmacsha.py28
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/noauth.py2
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/base.py4
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/des.py42
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/nopriv.py2
-rw-r--r--pysnmp/proto/secmod/rfc3414/service.py199
-rw-r--r--pysnmp/proto/secmod/rfc3826/priv/aes.py53
-rw-r--r--pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py51
-rw-r--r--pysnmp/smi/builder.py51
-rw-r--r--pysnmp/smi/compiler.py16
-rw-r--r--pysnmp/smi/instrum.py14
-rw-r--r--pysnmp/smi/mibs/SNMPv2-SMI.py92
-rw-r--r--pysnmp/smi/mibs/SNMPv2-TC.py2
-rw-r--r--pysnmp/smi/rfc1902.py112
-rw-r--r--pysnmp/smi/view.py6
83 files changed, 1104 insertions, 988 deletions
diff --git a/pysnmp/carrier/asyncio/base.py b/pysnmp/carrier/asyncio/base.py
index ce1b644f..4ee21ead 100644
--- a/pysnmp/carrier/asyncio/base.py
+++ b/pysnmp/carrier/asyncio/base.py
@@ -35,5 +35,5 @@ from pysnmp.carrier.base import AbstractTransport
class AbstractAsyncioTransport(AbstractTransport):
- protoTransportDispatcher = AsyncioDispatcher
+ PROTO_TRANSPORT_DISPATCHER = 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 a845fa1e..7cc0b589 100644
--- a/pysnmp/carrier/asyncio/dgram/base.py
+++ b/pysnmp/carrier/asyncio/dgram/base.py
@@ -47,8 +47,9 @@ IS_PYTHON_344_PLUS = platform.python_version_tuple() >= ('3', '4', '4')
class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport):
"""Base Asyncio datagram Transport, to be used with AsyncioDispatcher"""
- sockFamily = None
- addressType = lambda x: x
+ SOCK_FAMILY = None
+ ADDRESS_TYPE = lambda x: x
+
transport = None
def __init__(self, sock=None, sockMap=None, loop=None):
@@ -66,25 +67,25 @@ class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport):
def connection_made(self, transport):
self.transport = transport
- debug.logger & debug.flagIO and debug.logger('connection_made: invoked')
+ debug.logger & debug.FLAG_IO and debug.logger('connection_made: invoked')
while self._writeQ:
outgoingMessage, transportAddress = self._writeQ.pop(0)
- debug.logger & debug.flagIO and debug.logger('connection_made: transportAddress %r outgoingMessage %s' %
- (transportAddress, debug.hexdump(outgoingMessage)))
+ debug.logger & debug.FLAG_IO and debug.logger('connection_made: transportAddress %r outgoingMessage %s' %
+ (transportAddress, debug.hexdump(outgoingMessage)))
try:
self.transport.sendto(outgoingMessage, self.normalizeAddress(transportAddress))
except Exception:
raise error.CarrierError(';'.join(traceback.format_exception(*sys.exc_info())))
def connection_lost(self, exc):
- debug.logger & debug.flagIO and debug.logger('connection_lost: invoked')
+ debug.logger & debug.FLAG_IO and debug.logger('connection_lost: invoked')
# AbstractAsyncioTransport API
def openClientMode(self, iface=None):
try:
c = self.loop.create_datagram_endpoint(
- lambda: self, local_addr=iface, family=self.sockFamily
+ lambda: self, local_addr=iface, family=self.SOCK_FAMILY
)
# Avoid deprecation warning for asyncio.async()
if IS_PYTHON_344_PLUS:
@@ -99,7 +100,7 @@ class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport):
def openServerMode(self, iface):
try:
c = self.loop.create_datagram_endpoint(
- lambda: self, local_addr=iface, family=self.sockFamily
+ lambda: self, local_addr=iface, family=self.SOCK_FAMILY
)
# Avoid deprecation warning for asyncio.async()
if IS_PYTHON_344_PLUS:
@@ -118,7 +119,7 @@ class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport):
AbstractAsyncioTransport.closeTransport(self)
def sendMessage(self, outgoingMessage, transportAddress):
- debug.logger & debug.flagIO and debug.logger('sendMessage: %s transportAddress %r outgoingMessage %s' % (
+ debug.logger & debug.FLAG_IO and debug.logger('sendMessage: %s transportAddress %r outgoingMessage %s' % (
(self.transport is None and "queuing" or "sending"),
transportAddress, debug.hexdump(outgoingMessage)
))
@@ -131,6 +132,6 @@ class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport):
raise error.CarrierError(';'.join(traceback.format_exception(*sys.exc_info())))
def normalizeAddress(self, transportAddress):
- if not isinstance(transportAddress, self.addressType):
- transportAddress = self.addressType(transportAddress)
+ if not isinstance(transportAddress, self.ADDRESS_TYPE):
+ transportAddress = self.ADDRESS_TYPE(transportAddress)
return transportAddress
diff --git a/pysnmp/carrier/asyncio/dgram/udp.py b/pysnmp/carrier/asyncio/dgram/udp.py
index 41ada723..b13d4202 100644
--- a/pysnmp/carrier/asyncio/dgram/udp.py
+++ b/pysnmp/carrier/asyncio/dgram/udp.py
@@ -42,8 +42,8 @@ class UdpTransportAddress(tuple, AbstractTransportAddress):
class UdpAsyncioTransport(DgramAsyncioProtocol):
- sockFamily = socket.AF_INET
- addressType = UdpTransportAddress
+ SOCK_FAMILY = socket.AF_INET
+ ADDRESS_TYPE = UdpTransportAddress
UdpTransport = UdpAsyncioTransport
diff --git a/pysnmp/carrier/asyncio/dgram/udp6.py b/pysnmp/carrier/asyncio/dgram/udp6.py
index bc03b447..f3708852 100644
--- a/pysnmp/carrier/asyncio/dgram/udp6.py
+++ b/pysnmp/carrier/asyncio/dgram/udp6.py
@@ -17,8 +17,8 @@ class Udp6TransportAddress(tuple, AbstractTransportAddress):
class Udp6AsyncioTransport(DgramAsyncioProtocol):
- sockFamily = socket.has_ipv6 and socket.AF_INET6 or None
- addressType = Udp6TransportAddress
+ SOCK_FAMILY = socket.has_ipv6 and socket.AF_INET6 or None
+ ADDRESS_TYPE = Udp6TransportAddress
def normalizeAddress(self, transportAddress):
if '%' in transportAddress[0]: # strip zone ID
diff --git a/pysnmp/carrier/asyncore/base.py b/pysnmp/carrier/asyncore/base.py
index e4824f32..035dcbab 100644
--- a/pysnmp/carrier/asyncore/base.py
+++ b/pysnmp/carrier/asyncore/base.py
@@ -14,37 +14,37 @@ from pysnmp import debug
class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport):
- protoTransportDispatcher = AsyncoreDispatcher
- sockFamily = sockType = None
- retryCount = 0
- retryInterval = 0
- bufferSize = 131070
+ PROTO_TRANSPORT_DISPATCHER = AsyncoreDispatcher
+ SOCK_FAMILY = SOCK_TYPE = None
+ RETRY_COUNT = 0
+ RETRY_INTERVAL = 0
+ BUFFER_SIZE = 131070
# noinspection PyUnusedLocal
def __init__(self, sock=None, sockMap=None):
asyncore.dispatcher.__init__(self)
if sock is None:
- if self.sockFamily is None:
+ if self.SOCK_FAMILY is None:
raise error.CarrierError(
'Address family %s not supported' % self.__class__.__name__
)
- if self.sockType is None:
+ if self.SOCK_TYPE is None:
raise error.CarrierError(
'Socket type %s not supported' % self.__class__.__name__
)
try:
- sock = socket.socket(self.sockFamily, self.sockType)
+ sock = socket.socket(self.SOCK_FAMILY, self.SOCK_TYPE)
except socket.error as exc:
raise error.CarrierError('socket() failed: %s' % exc)
try:
for b in socket.SO_RCVBUF, socket.SO_SNDBUF:
bsize = sock.getsockopt(socket.SOL_SOCKET, b)
- if bsize < self.bufferSize:
- 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))
+ if bsize < self.BUFFER_SIZE:
+ sock.setsockopt(socket.SOL_SOCKET, b, self.BUFFER_SIZE)
+ debug.logger & debug.FLAG_IO and debug.logger('%s: socket %d buffer size increased from %d to %d for buffer %d' % (self.__class__.__name__, sock.fileno(), bsize, self.BUFFER_SIZE, b))
except Exception as exc:
- debug.logger & debug.flagIO and debug.logger('%s: socket buffer size option mangling failure for buffer: %s' % (self.__class__.__name__, exc))
+ debug.logger & debug.FLAG_IO and debug.logger('%s: socket buffer size option mangling failure for buffer: %s' % (self.__class__.__name__, exc))
# The socket map is managed by the AsyncoreDispatcher on
# which this transport is registered. Here we just prepare
@@ -82,8 +82,10 @@ class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport):
self.close()
# asyncore API
+
def handle_close(self):
raise error.CarrierError('Transport unexpectedly closed')
def handle_error(self):
- raise
+ exc = sys.exc_info()[1]
+ raise exc
diff --git a/pysnmp/carrier/asyncore/dgram/base.py b/pysnmp/carrier/asyncore/dgram/base.py
index e9ffc9b0..f103e781 100644
--- a/pysnmp/carrier/asyncore/dgram/base.py
+++ b/pysnmp/carrier/asyncore/dgram/base.py
@@ -12,23 +12,23 @@ from pysnmp.carrier import sockfix, sockmsg, error
from pysnmp import debug
# Ignore these socket errors
-sockErrors = {errno.ESHUTDOWN: True,
- errno.ENOTCONN: True,
- errno.ECONNRESET: False,
- errno.ECONNREFUSED: False,
- errno.EAGAIN: False,
- errno.EWOULDBLOCK: False}
+SOCK_ERRORS = {errno.ESHUTDOWN: True,
+ errno.ENOTCONN: True,
+ errno.ECONNRESET: False,
+ errno.ECONNREFUSED: False,
+ errno.EAGAIN: False,
+ errno.EWOULDBLOCK: False}
if hasattr(errno, 'EBADFD'):
# bad FD may happen upon FD closure on n-1 select() event
- sockErrors[errno.EBADFD] = True
+ SOCK_ERRORS[errno.EBADFD] = True
class DgramSocketTransport(AbstractSocketTransport):
- sockType = socket.SOCK_DGRAM
- retryCount = 3
- retryInterval = 1
- addressType = lambda x: x
+ SOCK_TYPE = socket.SOCK_DGRAM
+ RETRY_COUNT = 3
+ RETRY_INTERVAL = 1
+ ADDRESS_TYPE = lambda x: x
def __init__(self, sock=None, sockMap=None):
self.__outQueue = []
@@ -36,7 +36,7 @@ class DgramSocketTransport(AbstractSocketTransport):
def __recvfrom(s, sz):
d, a = s.recvfrom(sz)
- return d, self.addressType(a)
+ return d, self.ADDRESS_TYPE(a)
self._recvfrom = __recvfrom
AbstractSocketTransport.__init__(self, sock, sockMap)
@@ -64,7 +64,7 @@ class DgramSocketTransport(AbstractSocketTransport):
)
except socket.error as exc:
raise error.CarrierError('setsockopt() for SO_BROADCAST failed: %s' % exc)
- debug.logger & debug.flagIO and debug.logger('enableBroadcast: %s option SO_BROADCAST on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
+ debug.logger & debug.FLAG_IO and debug.logger('enableBroadcast: %s option SO_BROADCAST on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
return self
def enablePktInfo(self, flag=1):
@@ -82,10 +82,10 @@ class DgramSocketTransport(AbstractSocketTransport):
except socket.error as exc:
raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", exc))
- self._sendto = sockmsg.getSendTo(self.addressType)
- self._recvfrom = sockmsg.getRecvFrom(self.addressType)
+ self._sendto = sockmsg.getSendTo(self.ADDRESS_TYPE)
+ self._recvfrom = sockmsg.getRecvFrom(self.ADDRESS_TYPE)
- debug.logger & debug.flagIO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno()))
+ debug.logger & debug.FLAG_IO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno()))
return self
def enableTransparent(self, flag=1):
@@ -105,18 +105,18 @@ class DgramSocketTransport(AbstractSocketTransport):
except OSError:
raise error.CarrierError('IP_TRANSPARENT socket option requires superuser priveleges')
- debug.logger & debug.flagIO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
+ debug.logger & debug.FLAG_IO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
return self
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)))
+ debug.logger & debug.FLAG_IO and debug.logger('sendMessage: outgoingMessage queued (%d octets) %s' % (len(outgoingMessage), debug.hexdump(outgoingMessage)))
def normalizeAddress(self, transportAddress):
- if not isinstance(transportAddress, self.addressType):
- transportAddress = self.addressType(transportAddress)
+ if not isinstance(transportAddress, self.ADDRESS_TYPE):
+ transportAddress = self.ADDRESS_TYPE(transportAddress)
if not transportAddress.getLocalAddress():
transportAddress.setLocalAddress(self.getLocalAddress())
@@ -140,17 +140,17 @@ class DgramSocketTransport(AbstractSocketTransport):
def handle_write(self):
outgoingMessage, transportAddress = self.__outQueue.pop(0)
- debug.logger & debug.flagIO and debug.logger('handle_write: transportAddress %r -> %r outgoingMessage (%d octets) %s' % (transportAddress.getLocalAddress(), transportAddress, len(outgoingMessage), debug.hexdump(outgoingMessage)))
+ debug.logger & debug.FLAG_IO and debug.logger('handle_write: transportAddress %r -> %r outgoingMessage (%d octets) %s' % (transportAddress.getLocalAddress(), transportAddress, len(outgoingMessage), debug.hexdump(outgoingMessage)))
if not transportAddress:
- debug.logger & debug.flagIO and debug.logger('handle_write: missing dst address, loosing outgoing msg')
+ debug.logger & debug.FLAG_IO and debug.logger('handle_write: missing dst address, loosing outgoing msg')
return
try:
self._sendto(
self.socket, outgoingMessage, transportAddress
)
except socket.error as exc:
- if exc.args[0] in sockErrors:
- debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % exc)
+ if exc.args[0] in SOCK_ERRORS:
+ debug.logger & debug.FLAG_IO and debug.logger('handle_write: ignoring socket error %s' % exc)
else:
raise error.CarrierError('sendto() failed for %s: %s' % (transportAddress, exc))
@@ -161,7 +161,7 @@ class DgramSocketTransport(AbstractSocketTransport):
try:
incomingMessage, transportAddress = self._recvfrom(self.socket, 65535)
transportAddress = self.normalizeAddress(transportAddress)
- debug.logger & debug.flagIO and debug.logger(
+ debug.logger & debug.FLAG_IO 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()
@@ -170,9 +170,9 @@ class DgramSocketTransport(AbstractSocketTransport):
self._cbFun(self, transportAddress, incomingMessage)
return
except socket.error as exc:
- if exc.args[0] in sockErrors:
- debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % exc)
- sockErrors[exc.args[0]] and self.handle_close()
+ if exc.args[0] in SOCK_ERRORS:
+ debug.logger & debug.FLAG_IO and debug.logger('handle_read: known socket error %s' % exc)
+ SOCK_ERRORS[exc.args[0]] and self.handle_close()
return
else:
raise error.CarrierError('recvfrom() failed: %s' % exc)
diff --git a/pysnmp/carrier/asyncore/dgram/udp.py b/pysnmp/carrier/asyncore/dgram/udp.py
index 08ae5ceb..60bc32a9 100644
--- a/pysnmp/carrier/asyncore/dgram/udp.py
+++ b/pysnmp/carrier/asyncore/dgram/udp.py
@@ -8,7 +8,7 @@ from socket import AF_INET
from pysnmp.carrier.base import AbstractTransportAddress
from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport
-domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1)
+DOMAIN_NAME = SNMP_UDP_DOMAIN = (1, 3, 6, 1, 6, 1, 1)
class UdpTransportAddress(tuple, AbstractTransportAddress):
@@ -16,8 +16,8 @@ class UdpTransportAddress(tuple, AbstractTransportAddress):
class UdpSocketTransport(DgramSocketTransport):
- sockFamily = AF_INET
- addressType = UdpTransportAddress
+ SOCK_FAMILY = AF_INET
+ ADDRESS_TYPE = UdpTransportAddress
UdpTransport = UdpSocketTransport
diff --git a/pysnmp/carrier/asyncore/dgram/udp6.py b/pysnmp/carrier/asyncore/dgram/udp6.py
index 900ef3c7..ee99674d 100644
--- a/pysnmp/carrier/asyncore/dgram/udp6.py
+++ b/pysnmp/carrier/asyncore/dgram/udp6.py
@@ -9,7 +9,7 @@ from pysnmp.carrier.base import AbstractTransportAddress
from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport
import socket
-domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2)
+DOMAIN_NAME = SNMP_UDP6_DOMAIN = (1, 3, 6, 1, 2, 1, 100, 1, 2)
class Udp6TransportAddress(tuple, AbstractTransportAddress):
@@ -17,8 +17,8 @@ class Udp6TransportAddress(tuple, AbstractTransportAddress):
class Udp6SocketTransport(DgramSocketTransport):
- sockFamily = socket.has_ipv6 and socket.AF_INET6 or None
- addressType = Udp6TransportAddress
+ SOCK_FAMILY = socket.has_ipv6 and socket.AF_INET6 or None
+ ADDRESS_TYPE = Udp6TransportAddress
def normalizeAddress(self, transportAddress):
if '%' in transportAddress[0]: # strip zone ID
diff --git a/pysnmp/carrier/asyncore/dgram/unix.py b/pysnmp/carrier/asyncore/dgram/unix.py
index 15f68b2b..486c84f8 100644
--- a/pysnmp/carrier/asyncore/dgram/unix.py
+++ b/pysnmp/carrier/asyncore/dgram/unix.py
@@ -14,7 +14,7 @@ except ImportError:
from pysnmp.carrier.base import AbstractTransportAddress
from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport
-domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13)
+DOMAIN_NAME = SNMP_LOCAL_DOMAIN = (1, 3, 6, 1, 2, 1, 100, 1, 13)
random.seed()
@@ -24,8 +24,8 @@ class UnixTransportAddress(str, AbstractTransportAddress):
class UnixSocketTransport(DgramSocketTransport):
- sockFamily = AF_UNIX
- addressType = UnixTransportAddress
+ SOCK_FAMILY = AF_UNIX
+ ADDRESS_TYPE = UnixTransportAddress
_iface = ''
def openClientMode(self, iface=None):
diff --git a/pysnmp/carrier/asyncore/dispatch.py b/pysnmp/carrier/asyncore/dispatch.py
index 221c596c..3517bdff 100644
--- a/pysnmp/carrier/asyncore/dispatch.py
+++ b/pysnmp/carrier/asyncore/dispatch.py
@@ -35,8 +35,7 @@ class AsyncoreDispatcher(AbstractTransportDispatcher):
def transportsAreWorking(self):
for transport in self.__sockMap.values():
if transport.writable():
- return 1
- return 0
+ return True
def runDispatcher(self, timeout=0.0):
while self.jobsArePending() or self.transportsAreWorking():
@@ -45,6 +44,7 @@ class AsyncoreDispatcher(AbstractTransportDispatcher):
use_poll=True, map=self.__sockMap, count=1)
except KeyboardInterrupt:
raise
- except:
+
+ except Exception:
raise PySnmpError('poll error: %s' % ';'.join(format_exception(*exc_info())))
self.handleTimerTick(time())
diff --git a/pysnmp/carrier/base.py b/pysnmp/carrier/base.py
index 017a1520..12dfc86b 100644
--- a/pysnmp/carrier/base.py
+++ b/pysnmp/carrier/base.py
@@ -211,13 +211,13 @@ class AbstractTransportAddress(object):
class AbstractTransport(object):
- protoTransportDispatcher = None
- addressType = AbstractTransportAddress
+ PROTO_TRANSPORT_DISPATCHER = None
+ ADDRESS_TYPE = AbstractTransportAddress
_cbFun = None
@classmethod
def isCompatibleWithDispatcher(cls, transportDispatcher):
- return isinstance(transportDispatcher, cls.protoTransportDispatcher)
+ return isinstance(transportDispatcher, cls.PROTO_TRANSPORT_DISPATCHER)
def registerCbFun(self, cbFun):
if self._cbFun:
diff --git a/pysnmp/carrier/sockfix.py b/pysnmp/carrier/sockfix.py
index fab6d1aa..edfc1631 100644
--- a/pysnmp/carrier/sockfix.py
+++ b/pysnmp/carrier/sockfix.py
@@ -22,7 +22,7 @@ for symbol, value in SYMBOLS.items():
if not hasattr(socket, symbol):
setattr(socket, symbol, value)
- debug.logger & debug.flagIO and debug.logger(
+ debug.logger & debug.FLAG_IO and debug.logger(
'WARNING: the socket module on this platform misses option %s. '
'Assuming its value is %d.' % (symbol, value)
)
diff --git a/pysnmp/carrier/sockmsg.py b/pysnmp/carrier/sockmsg.py
index 4ff55a91..deab4b6d 100644
--- a/pysnmp/carrier/sockmsg.py
+++ b/pysnmp/carrier/sockmsg.py
@@ -27,6 +27,7 @@ if sys.version_info[:2] < (3, 3):
def getSendTo(addressType):
raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version')
+
else:
import ctypes
import ipaddress
@@ -91,7 +92,7 @@ else:
_to = (str(addr), s.getsockname()[1])
break
- debug.logger & debug.flagIO and debug.logger(
+ debug.logger & debug.FLAG_IO and debug.logger(
'recvfrom: received %d octets from %s to %s; '
'iov blob %r' % (len(data), _from, _to, ancdata))
@@ -120,7 +121,7 @@ else:
_f.ipi6_addr = in6_addr.from_buffer_copy(addr.packed)
ancdata = [(socket.SOL_IPV6, socket.IPV6_PKTINFO, memoryview(_f).tobytes())]
- debug.logger & debug.flagIO and debug.logger(
+ debug.logger & debug.FLAG_IO and debug.logger(
'sendto: sending %d octets to %s; address %r; '
'iov blob %r' % (len(_data), _to, addr, ancdata))
diff --git a/pysnmp/carrier/twisted/base.py b/pysnmp/carrier/twisted/base.py
index d8b75bc7..91883d7d 100644
--- a/pysnmp/carrier/twisted/base.py
+++ b/pysnmp/carrier/twisted/base.py
@@ -17,7 +17,7 @@ from pysnmp.carrier.base import AbstractTransport
class AbstractTwistedTransport(AbstractTransport):
- protoTransportDispatcher = TwistedDispatcher
+ PROTO_TRANSPORT_DISPATCHER = TwistedDispatcher
def __init__(self, sock=None, sockMap=None):
self._writeQ = []
diff --git a/pysnmp/carrier/twisted/dgram/base.py b/pysnmp/carrier/twisted/dgram/base.py
index 4386b702..42eb7c04 100644
--- a/pysnmp/carrier/twisted/dgram/base.py
+++ b/pysnmp/carrier/twisted/dgram/base.py
@@ -26,20 +26,20 @@ class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport):
reactor.callLater(0, self._cbFun, self, transportAddress, datagram)
def startProtocol(self):
- debug.logger & debug.flagIO and debug.logger('startProtocol: invoked')
+ debug.logger & debug.FLAG_IO and debug.logger('startProtocol: invoked')
while self._writeQ:
outgoingMessage, transportAddress = self._writeQ.pop(0)
- debug.logger & debug.flagIO and debug.logger('startProtocol: transportAddress %r outgoingMessage %s' % (transportAddress, debug.hexdump(outgoingMessage)))
+ debug.logger & debug.FLAG_IO and debug.logger('startProtocol: transportAddress %r outgoingMessage %s' % (transportAddress, debug.hexdump(outgoingMessage)))
try:
self.transport.write(outgoingMessage, transportAddress)
except Exception as exc:
raise error.CarrierError('Twisted exception: %s' % exc)
def stopProtocol(self):
- debug.logger & debug.flagIO and debug.logger('stopProtocol: invoked')
+ debug.logger & debug.FLAG_IO and debug.logger('stopProtocol: invoked')
def sendMessage(self, outgoingMessage, transportAddress):
- debug.logger & debug.flagIO and debug.logger('startProtocol: %s transportAddress %r outgoingMessage %s' % ((self.transport is None and "queuing" or "sending"), transportAddress, debug.hexdump(outgoingMessage)))
+ debug.logger & debug.FLAG_IO and debug.logger('startProtocol: %s transportAddress %r outgoingMessage %s' % ((self.transport is None and "queuing" or "sending"), transportAddress, debug.hexdump(outgoingMessage)))
if self.transport is None:
self._writeQ.append((outgoingMessage, transportAddress))
else:
diff --git a/pysnmp/carrier/twisted/dgram/udp.py b/pysnmp/carrier/twisted/dgram/udp.py
index bdb93cdd..eb47bb24 100644
--- a/pysnmp/carrier/twisted/dgram/udp.py
+++ b/pysnmp/carrier/twisted/dgram/udp.py
@@ -10,7 +10,7 @@ from pysnmp.carrier.base import AbstractTransportAddress
from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport
from pysnmp.carrier import error
-domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1)
+DOMAIN_NAME = SNMP_UDP_DOMAIN = (1, 3, 6, 1, 6, 1, 1)
class UdpTransportAddress(tuple, AbstractTransportAddress):
@@ -18,7 +18,7 @@ class UdpTransportAddress(tuple, AbstractTransportAddress):
class UdpTwistedTransport(DgramTwistedTransport):
- addressType = UdpTransportAddress
+ ADDRESS_TYPE = UdpTransportAddress
_lport = None
# AbstractTwistedTransport API
diff --git a/pysnmp/carrier/twisted/dgram/unix.py b/pysnmp/carrier/twisted/dgram/unix.py
index fe9c459b..24fdc5c7 100644
--- a/pysnmp/carrier/twisted/dgram/unix.py
+++ b/pysnmp/carrier/twisted/dgram/unix.py
@@ -10,13 +10,15 @@ from pysnmp.carrier.base import AbstractTransportAddress
from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport
from pysnmp.carrier import error
-domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13)
+DOMAIN_NAME = SNMP_LOCAL_DOMAIN = (1, 3, 6, 1, 2, 1, 100, 1, 13)
+
class UnixTransportAddress(str, AbstractTransportAddress):
pass
+
class UnixTwistedTransport(DgramTwistedTransport):
- addressType = UnixTransportAddress
+ ADDRESS_TYPE = UnixTransportAddress
_lport = None
# AbstractTwistedTransport API
@@ -43,4 +45,5 @@ class UnixTwistedTransport(DgramTwistedTransport):
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 def16f6f..cacc20b4 100644
--- a/pysnmp/carrier/twisted/dispatch.py
+++ b/pysnmp/carrier/twisted/dispatch.py
@@ -34,9 +34,11 @@ class TwistedDispatcher(AbstractTransportDispatcher):
if not reactor.running:
try:
reactor.run()
+
except KeyboardInterrupt:
raise
- except:
+
+ except Exception:
raise PySnmpError('reactor error: %s' % ';'.join(traceback.format_exception(*sys.exc_info())))
# jobstarted/jobfinished might be okay as-is
diff --git a/pysnmp/debug.py b/pysnmp/debug.py
index 715a3876..8217569d 100644
--- a/pysnmp/debug.py
+++ b/pysnmp/debug.py
@@ -9,30 +9,32 @@ from pyasn1.compat.octets import octs2ints
from pysnmp import error
from pysnmp import __version__
-flagNone = 0x0000
-flagIO = 0x0001
-flagDsp = 0x0002
-flagMP = 0x0004
-flagSM = 0x0008
-flagBld = 0x0010
-flagMIB = 0x0020
-flagIns = 0x0040
-flagACL = 0x0080
-flagPrx = 0x0100
-flagApp = 0x0200
-flagAll = 0xffff
-
-flagMap = {'io': flagIO,
- 'dsp': flagDsp,
- 'msgproc': flagMP,
- 'secmod': flagSM,
- 'mibbuild': flagBld,
- 'mibview': flagMIB,
- 'mibinstrum': flagIns,
- 'acl': flagACL,
- 'proxy': flagPrx,
- 'app': flagApp,
- 'all': flagAll}
+FLAG_NONE = 0x0000
+FLAG_IO = 0x0001
+FLAG_DSP = 0x0002
+FLAG_MP = 0x0004
+FLAG_SM = 0x0008
+FLAG_BLD = 0x0010
+FLAG_MIB = 0x0020
+FLAG_INS = 0x0040
+FLAG_ACL = 0x0080
+FLAG_PRX = 0x0100
+FLAG_APP = 0x0200
+FLAG_ALL = 0xffff
+
+FLAG_MAP = {
+ 'io': FLAG_IO,
+ 'dsp': FLAG_DSP,
+ 'msgproc': FLAG_MP,
+ 'secmod': FLAG_SM,
+ 'mibbuild': FLAG_BLD,
+ 'mibview': FLAG_MIB,
+ 'mibinstrum': FLAG_INS,
+ 'acl': FLAG_ACL,
+ 'proxy': FLAG_PRX,
+ 'app': FLAG_APP,
+ 'all': FLAG_ALL
+}
class Printer(object):
@@ -58,6 +60,7 @@ class Printer(object):
if hasattr(logging, 'NullHandler'):
NullHandler = logging.NullHandler
+
else:
# Python 2.6 and older
class NullHandler(logging.Handler):
@@ -66,14 +69,14 @@ else:
class Debug(object):
- defaultPrinter = None
+ DEFAULT_PRINTER = None
def __init__(self, *flags, **options):
- self._flags = flagNone
+ self._flags = FLAG_NONE
if options.get('printer') is not None:
self._printer = options.get('printer')
- elif self.defaultPrinter is not None:
- self._printer = self.defaultPrinter
+ elif self.DEFAULT_PRINTER is not None:
+ self._printer = self.DEFAULT_PRINTER
else:
if 'loggerName' in options:
# route our logs to parent logger
@@ -90,9 +93,9 @@ class Debug(object):
f = f[1:]
try:
if inverse:
- self._flags &= ~flagMap[f]
+ self._flags &= ~FLAG_MAP[f]
else:
- self._flags |= flagMap[f]
+ self._flags |= FLAG_MAP[f]
except KeyError:
raise error.PySnmpError('bad debug flag %s' % f)
@@ -123,4 +126,5 @@ def setLogger(l):
def hexdump(octets):
return ' '.join(
- ['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x) for n, x in zip(range(len(octets)), octs2ints(octets))])
+ ['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x)
+ for n, x in zip(range(len(octets)), octs2ints(octets))])
diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py
index 2ea0ea59..e89a102a 100644
--- a/pysnmp/entity/config.py
+++ b/pysnmp/entity/config.py
@@ -17,48 +17,52 @@ from pysnmp import error
# A shortcut to popular constants
# Transports
-snmpUDPDomain = udp.snmpUDPDomain
-snmpUDP6Domain = udp6.snmpUDP6Domain
+SNMP_UDP_DOMAIN = udp.SNMP_UDP_DOMAIN
+SNMP_UDP6_DOMAIN = udp6.SNMP_UDP6_DOMAIN
# Auth protocol
-usmHMACMD5AuthProtocol = hmacmd5.HmacMd5.serviceID
-usmHMACSHAAuthProtocol = hmacsha.HmacSha.serviceID
-usmHMAC128SHA224AuthProtocol = hmacsha2.HmacSha2.sha224ServiceID
-usmHMAC192SHA256AuthProtocol = hmacsha2.HmacSha2.sha256ServiceID
-usmHMAC256SHA384AuthProtocol = hmacsha2.HmacSha2.sha384ServiceID
-usmHMAC384SHA512AuthProtocol = hmacsha2.HmacSha2.sha512ServiceID
-
-usmNoAuthProtocol = noauth.NoAuth.serviceID
+USM_AUTH_HMAC96_MD5 = hmacmd5.HmacMd5.SERVICE_ID
+USM_AUTH_HMAC96_SHA = hmacsha.HmacSha.SERVICE_ID
+USM_AUTH_HMAC128_SHA224 = hmacsha2.HmacSha2.SHA224_SERVICE_ID
+USM_AUTH_HMAC192_SHA256 = hmacsha2.HmacSha2.SHA256_SERVICE_ID
+USM_AUTH_HMAC256_SHA384 = hmacsha2.HmacSha2.SHA384_SERVICE_ID
+USM_AUTH_HMAC384_SHA512 = hmacsha2.HmacSha2.SHA512_SERVICE_ID
+
+USM_AUTH_NONE = noauth.NoAuth.SERVICE_ID
"""No authentication service"""
# Privacy protocol
-usmDESPrivProtocol = des.Des.serviceID
-usm3DESEDEPrivProtocol = des3.Des3.serviceID
-usmAesCfb128Protocol = aes.Aes.serviceID
-usmAesBlumenthalCfb192Protocol = aes192.AesBlumenthal192.serviceID # semi-standard but not widely used
-usmAesBlumenthalCfb256Protocol = aes256.AesBlumenthal256.serviceID # semi-standard but not widely used
-usmAesCfb192Protocol = aes192.Aes192.serviceID # non-standard but used by many vendors
-usmAesCfb256Protocol = aes256.Aes256.serviceID # non-standard but used by many vendors
-usmNoPrivProtocol = nopriv.NoPriv.serviceID
-
-# Auth services
-authServices = {hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(),
- hmacsha.HmacSha.serviceID: hmacsha.HmacSha(),
- hmacsha2.HmacSha2.sha224ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha224ServiceID),
- hmacsha2.HmacSha2.sha256ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha256ServiceID),
- hmacsha2.HmacSha2.sha384ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha384ServiceID),
- hmacsha2.HmacSha2.sha512ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha512ServiceID),
- noauth.NoAuth.serviceID: noauth.NoAuth()}
-
-# Privacy services
-privServices = {des.Des.serviceID: des.Des(),
- des3.Des3.serviceID: des3.Des3(),
- aes.Aes.serviceID: aes.Aes(),
- aes192.AesBlumenthal192.serviceID: aes192.AesBlumenthal192(),
- aes256.AesBlumenthal256.serviceID: aes256.AesBlumenthal256(),
- aes192.Aes192.serviceID: aes192.Aes192(), # non-standard
- aes256.Aes256.serviceID: aes256.Aes256(), # non-standard
- nopriv.NoPriv.serviceID: nopriv.NoPriv()}
+USM_PRIV_CBC56_DES = des.Des.SERVICE_ID
+USM_PRIV_CBC168_3DES = des3.Des3.SERVICE_ID
+USM_PRIV_CFB128_AES = aes.Aes.SERVICE_ID
+USM_PRIV_CFB192_AES = aes192.Aes192.SERVICE_ID # non-standard but used by many vendors
+USM_PRIV_CFB256_AES = aes256.Aes256.SERVICE_ID # non-standard but used by many vendors
+USM_PRIV_CFB192_AES_BLUMENTHAL = aes192.AesBlumenthal192.SERVICE_ID # semi-standard but not widely used
+USM_PRIV_CFB256_AES_BLUMENTHAL = aes256.AesBlumenthal256.SERVICE_ID # semi-standard but not widely used
+
+USM_PRIV_NONE = nopriv.NoPriv.SERVICE_ID
+
+AUTH_SERVICES = {
+ hmacmd5.HmacMd5.SERVICE_ID: hmacmd5.HmacMd5(),
+ hmacsha.HmacSha.SERVICE_ID: hmacsha.HmacSha(),
+ hmacsha2.HmacSha2.SHA224_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA224_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA256_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA256_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA384_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA384_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA512_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA512_SERVICE_ID),
+ noauth.NoAuth.SERVICE_ID: noauth.NoAuth()
+}
+
+PRIV_SERVICES = {
+ des.Des.SERVICE_ID: des.Des(),
+ des3.Des3.SERVICE_ID: des3.Des3(),
+ aes.Aes.SERVICE_ID: aes.Aes(),
+ aes192.AesBlumenthal192.SERVICE_ID: aes192.AesBlumenthal192(),
+ aes256.AesBlumenthal256.SERVICE_ID: aes256.AesBlumenthal256(),
+ aes192.Aes192.SERVICE_ID: aes192.Aes192(), # non-standard
+ aes256.Aes256.SERVICE_ID: aes256.Aes256(), # non-standard
+ nopriv.NoPriv.SERVICE_ID: nopriv.NoPriv()
+}
+
# This module uses Management Instrumentation subsystem in purely
# synchronous manner. The assumption is that the Management
@@ -133,8 +137,8 @@ def __cookV3UserInfo(snmpEngine, securityName, securityEngineId):
def addV3User(snmpEngine, userName,
- authProtocol=usmNoAuthProtocol, authKey=None,
- privProtocol=usmNoPrivProtocol, privKey=None,
+ authProtocol=USM_AUTH_NONE, authKey=None,
+ privProtocol=USM_PRIV_NONE, privKey=None,
securityEngineId=None,
securityName=None):
mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder
@@ -166,21 +170,21 @@ def addV3User(snmpEngine, userName,
)
# Localize keys
- if authProtocol in authServices:
- hashedAuthPassphrase = authServices[authProtocol].hashPassphrase(
+ if authProtocol in AUTH_SERVICES:
+ hashedAuthPassphrase = AUTH_SERVICES[authProtocol].hashPassphrase(
authKey and authKey or null
)
- localAuthKey = authServices[authProtocol].localizeKey(
+ localAuthKey = AUTH_SERVICES[authProtocol].localizeKey(
hashedAuthPassphrase, snmpEngineID
)
else:
raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,))
- if privProtocol in privServices:
- hashedPrivPassphrase = privServices[privProtocol].hashPassphrase(
+ if privProtocol in PRIV_SERVICES:
+ hashedPrivPassphrase = PRIV_SERVICES[privProtocol].hashPassphrase(
authProtocol, privKey and privKey or null
)
- localPrivKey = privServices[privProtocol].localizeKey(
+ localPrivKey = PRIV_SERVICES[privProtocol].localizeKey(
authProtocol, hashedPrivPassphrase, snmpEngineID
)
else:
@@ -318,13 +322,13 @@ def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress,
(snmpTargetAddrEntry, snmpSourceAddrEntry,
tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName)
- if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain:
+ if transportDomain[:len(SNMP_UDP_DOMAIN)] == SNMP_UDP_DOMAIN:
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:
+ elif transportDomain[:len(SNMP_UDP6_DOMAIN)] == SNMP_UDP6_DOMAIN:
TransportAddressIPv6, = mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6')
transportAddress = TransportAddressIPv6(transportAddress)
if sourceAddress is None:
@@ -365,7 +369,7 @@ def addTransport(snmpEngine, transportDomain, transport):
'Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher))
else:
snmpEngine.registerTransportDispatcher(
- transport.protoTransportDispatcher()
+ transport.PROTO_TRANSPORT_DISPATCHER()
)
# here we note that we have created transportDispatcher automatically
snmpEngine.setUserContext(automaticTransportDispatcher=0)
diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py
index 11abec6e..8c4e363a 100644
--- a/pysnmp/entity/engine.py
+++ b/pysnmp/entity/engine.py
@@ -64,21 +64,21 @@ class SnmpEngine(object):
else:
self.msgAndPduDsp = msgAndPduDsp
self.messageProcessingSubsystems = {
- SnmpV1MessageProcessingModel.messageProcessingModelID:
+ SnmpV1MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID:
SnmpV1MessageProcessingModel(),
- SnmpV2cMessageProcessingModel.messageProcessingModelID:
+ SnmpV2cMessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID:
SnmpV2cMessageProcessingModel(),
- SnmpV3MessageProcessingModel.messageProcessingModelID:
+ SnmpV3MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID:
SnmpV3MessageProcessingModel()
}
self.securityModels = {
- SnmpV1SecurityModel.securityModelID: SnmpV1SecurityModel(),
- SnmpV2cSecurityModel.securityModelID: SnmpV2cSecurityModel(),
- SnmpUSMSecurityModel.securityModelID: SnmpUSMSecurityModel()
+ SnmpV1SecurityModel.SECURITY_MODEL_ID: SnmpV1SecurityModel(),
+ SnmpV2cSecurityModel.SECURITY_MODEL_ID: SnmpV2cSecurityModel(),
+ SnmpUSMSecurityModel.SECURITY_MODEL_ID: SnmpUSMSecurityModel()
}
self.accessControlModel = {
- void.Vacm.accessModelID: void.Vacm(),
- rfc3415.Vacm.accessModelID: rfc3415.Vacm()
+ void.Vacm.ACCESS_MODEL_ID: void.Vacm(),
+ rfc3415.Vacm.ACCESS_MODEL_ID: rfc3415.Vacm()
}
self.transportDispatcher = None
@@ -102,7 +102,7 @@ class SnmpEngine(object):
origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID)
self.snmpEngineID = origSnmpEngineID.syntax
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint())
# Attempt to make some of snmp Engine settings persistent.
@@ -110,7 +110,7 @@ class SnmpEngine(object):
persistentPath = os.path.join(tempfile.gettempdir(), '__pysnmp', self.snmpEngineID.prettyPrint())
- debug.logger & debug.flagApp and debug.logger('SnmpEngine: using persistent directory: %s' % persistentPath)
+ debug.logger & debug.FLAG_APP and debug.logger('SnmpEngine: using persistent directory: %s' % persistentPath)
if not os.path.exists(persistentPath):
try:
@@ -135,10 +135,10 @@ class SnmpEngine(object):
os.close(fd)
shutil.move(fn, f)
except Exception as exc:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'SnmpEngine: could not stored SNMP Engine Boots: %s' % exc)
else:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint())
def __repr__(self):
diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py
index 59503d52..9ca9b50b 100644
--- a/pysnmp/entity/rfc3413/cmdgen.py
+++ b/pysnmp/entity/rfc3413/cmdgen.py
@@ -46,7 +46,7 @@ class CommandGenerator(object):
# 3.1.3
if statusInformation:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation))
errorIndication = statusInformation['errorIndication']
@@ -59,7 +59,7 @@ class CommandGenerator(object):
origRetries += 1
if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get('discoveryRetries', 4):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries))
cbFun(snmpEngine, origSendRequestHandle, errorIndication, None, cbCtx)
return
@@ -94,7 +94,7 @@ class CommandGenerator(object):
except StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % (
sendPduHandle, statusInformation))
cbFun(snmpEngine, origSendRequestHandle,
@@ -108,7 +108,7 @@ class CommandGenerator(object):
origContextEngineId and origContextEngineId != contextEngineId or
origContextName and origContextName != contextName or
origPduVersion != pduVersion):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle)
cbFun(snmpEngine, origSendRequestHandle,
@@ -121,7 +121,7 @@ class CommandGenerator(object):
# 3.1.2
if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle)
cbFun(snmpEngine, origSendRequestHandle,
'badResponse', None, cbCtx)
@@ -176,7 +176,7 @@ class CommandGenerator(object):
retryCount, 0, 0
)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % (
sendPduHandle, timeout, timeoutInTicks, retryCount))
@@ -273,7 +273,7 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun):
v2c.apiPDU.getErrorStatus(PDU),
v2c.apiPDU.getErrorIndex(PDU, muteErrors=True),
varBindTable, cbCtx):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle)
return # app says enough
@@ -292,7 +292,7 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun):
except StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation))
cbFun(snmpEngine, sendRequestHandle,
statusInformation['errorIndication'],
@@ -356,7 +356,7 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun):
v2c.apiBulkPDU.getErrorStatus(PDU),
v2c.apiBulkPDU.getErrorIndex(PDU, muteErrors=True),
varBindTable, cbCtx):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle)
return # app says enough
@@ -375,7 +375,7 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun):
except StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % (
sendRequestHandle, statusInformation))
cbFun(snmpEngine, sendRequestHandle,
diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py
index 461ba235..52951a4b 100644
--- a/pysnmp/entity/rfc3413/cmdrsp.py
+++ b/pysnmp/entity/rfc3413/cmdrsp.py
@@ -15,7 +15,7 @@ from pysnmp import debug
# 3.2
class CommandResponderBase(object):
- acmID = 3 # default MIB access control method to use
+ ACM_ID = 3 # default MIB access control method to use
SUPPORTED_PDU_TYPES = ()
SMI_ERROR_MAP = {
pysnmp.smi.error.TooBigError: 'tooBig',
@@ -75,7 +75,7 @@ class CommandResponderBase(object):
v2c.apiPDU.setErrorIndex(PDU, errorIndex)
v2c.apiPDU.setVarBinds(PDU, varBinds)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % (
stateReference, errorStatus, errorIndex, varBinds)
)
@@ -117,7 +117,7 @@ class CommandResponderBase(object):
)
except error.StatusInformation as exc:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendPdu: stateReference %s, statusInformation %s' % (stateReference, exc))
snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB',
'snmpSilentDrops')
@@ -140,8 +140,8 @@ class CommandResponderBase(object):
origPdu = None
# 3.2.1
- if (PDU.tagSet not in rfc3411.readClassPDUs and
- PDU.tagSet not in rfc3411.writeClassPDUs):
+ if (PDU.tagSet not in rfc3411.READ_CLASS_PDUS and
+ PDU.tagSet not in rfc3411.WRITE_CLASS_PDUS):
raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
# 3.2.2 --> no-op
@@ -160,7 +160,7 @@ class CommandResponderBase(object):
# 3.2.5
varBinds = v2c.apiPDU.getVarBinds(PDU)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))
self.initiateMgmtOperation(snmpEngine, stateReference, contextName, PDU)
@@ -194,7 +194,7 @@ class CommandResponderBase(object):
context['pduType'])
try:
- snmpEngine.accessControlModel[cls.acmID].isAccessAllowed(
+ snmpEngine.accessControlModel[cls.ACM_ID].isAccessAllowed(
snmpEngine, securityModel, securityName,
securityLevel, viewType, contextName, name
)
@@ -202,7 +202,7 @@ class CommandResponderBase(object):
# Map ACM errors onto SMI ones
except error.StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'__verifyAccess: name %s, statusInformation %s' % (name, statusInformation))
errorIndication = statusInformation['errorIndication']
# 3.2.5...
@@ -469,7 +469,7 @@ class BulkCommandResponder(NextCommandResponder):
if R:
M = min(M, self.maxVarBinds // R)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'initiateMgmtOperation: N %d, M %d, R %d' % (N, M, R))
mgmtFun = self._getMgmtFun(contextName)
diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py
index 144aa486..7689824b 100644
--- a/pysnmp/entity/rfc3413/config.py
+++ b/pysnmp/entity/rfc3413/config.py
@@ -63,20 +63,20 @@ def getTargetAddr(snmpEngine, snmpTargetAddrName):
transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain)
- if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain:
+ if snmpTargetAddrTDomain[:len(config.SNMP_UDP_DOMAIN)] == config.SNMP_UDP_DOMAIN:
SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM',
'SnmpUDPAddress')
- snmpTargetAddrTAddress = transport.addressType(
+ snmpTargetAddrTAddress = transport.ADDRESS_TYPE(
SnmpUDPAddress(snmpTargetAddrTAddress)
).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress))
- elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain:
+ elif snmpTargetAddrTDomain[:len(config.SNMP_UDP6_DOMAIN)] == config.SNMP_UDP6_DOMAIN:
TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6')
- snmpTargetAddrTAddress = transport.addressType(
+ snmpTargetAddrTAddress = transport.ADDRESS_TYPE(
TransportAddressIPv6(snmpTargetAddrTAddress)
).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress))
elif snmpTargetAddrTDomain[:len(config.snmpLocalDomain)] == config.snmpLocalDomain:
- snmpTargetAddrTAddress = transport.addressType(
+ snmpTargetAddrTAddress = transport.ADDRESS_TYPE(
snmpTargetAddrTAddress
)
diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py
index 3975e670..7d3c3262 100644
--- a/pysnmp/entity/rfc3413/context.py
+++ b/pysnmp/entity/rfc3413/context.py
@@ -19,7 +19,7 @@ class SnmpContext(object):
self.contextEngineId = snmpEngineId.syntax
else:
self.contextEngineId = snmpEngineId.syntax.clone(contextEngineId)
- debug.logger & debug.flagIns and debug.logger('SnmpContext: contextEngineId \"%r\"' % (self.contextEngineId,))
+ debug.logger & debug.FLAG_INS and debug.logger('SnmpContext: contextEngineId \"%r\"' % (self.contextEngineId,))
self.contextNames = {
null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name
}
@@ -30,7 +30,7 @@ class SnmpContext(object):
raise error.PySnmpError(
'Duplicate contextName %s' % contextName
)
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum))
if mibInstrum is None:
self.contextNames[contextName] = self.contextNames[null]
@@ -40,18 +40,18 @@ class SnmpContext(object):
def unregisterContextName(self, contextName):
contextName = univ.OctetString(contextName).asOctets()
if contextName in self.contextNames:
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'unregisterContextName: unregistered contextName %r' % contextName)
del self.contextNames[contextName]
def getMibInstrum(self, contextName=null):
contextName = univ.OctetString(contextName).asOctets()
if contextName not in self.contextNames:
- debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName %r not registered' % contextName)
+ debug.logger & debug.FLAG_INS and debug.logger('getMibInstrum: contextName %r not registered' % contextName)
raise error.PySnmpError(
'Missing contextName %s' % contextName
)
else:
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName]))
return self.contextNames[contextName]
diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py
index 263dbb79..0c686635 100644
--- a/pysnmp/entity/rfc3413/ntforg.py
+++ b/pysnmp/entity/rfc3413/ntforg.py
@@ -19,7 +19,7 @@ getNextHandle = nextid.Integer(0x7fffffff)
class NotificationOriginator(object):
- acmID = 3 # default MIB access control method to use
+ ACM_ID = 3 # default MIB access control method to use
def __init__(self, **options):
self.__pendingReqs = {}
@@ -46,7 +46,7 @@ class NotificationOriginator(object):
snmpEngine.transportDispatcher.jobFinished(id(self))
if statusInformation:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % (
sendRequestHandle, sendPduHandle, statusInformation))
@@ -60,7 +60,7 @@ class NotificationOriginator(object):
origRetries += 1
if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get('discoveryRetries', 4):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % (
sendRequestHandle, sendPduHandle, origRetries))
cbFun(snmpEngine, sendRequestHandle, errorIndication, None, cbCtx)
@@ -89,7 +89,7 @@ class NotificationOriginator(object):
)
except error.StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % (
sendRequestHandle, statusInformation))
cbFun(snmpEngine, sendRequestHandle,
@@ -98,7 +98,7 @@ class NotificationOriginator(object):
snmpEngine.transportDispatcher.jobStarted(id(self))
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % (
sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount))
@@ -136,7 +136,7 @@ class NotificationOriginator(object):
pduVersion = 1
# 3.3.5
- if reqPDU.tagSet in rfc3411.confirmedClassPDUs:
+ if reqPDU.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# Convert timeout in seconds into timeout in timer ticks
timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution()
@@ -151,7 +151,7 @@ class NotificationOriginator(object):
self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx)
)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout))
# 3.3.6b
@@ -171,7 +171,7 @@ class NotificationOriginator(object):
sendRequestHandle = None
- debug.logger & debug.flagApp and debug.logger('sendPdu: message sent')
+ debug.logger & debug.FLAG_APP and debug.logger('sendPdu: message sent')
return sendRequestHandle
@@ -181,12 +181,12 @@ class NotificationOriginator(object):
self.__pendingNotifications[notificationHandle].remove(sendRequestHandle)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP 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(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % (
notificationHandle, sendRequestHandle))
del self.__pendingNotifications[notificationHandle]
@@ -202,7 +202,7 @@ class NotificationOriginator(object):
#
def sendVarBinds(self, snmpEngine, notificationTarget, contextEngineId,
contextName, varBinds=(), cbFun=None, cbCtx=None):
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % (
notificationTarget, contextEngineId or '<default>', contextName, varBinds))
@@ -216,7 +216,7 @@ class NotificationOriginator(object):
notificationHandle = getNextHandle()
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % (
notificationHandle, notifyTag, notifyType))
@@ -245,7 +245,7 @@ class NotificationOriginator(object):
sendRequestHandle = -1
- debug.logger & debug.flagApp and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,))
+ debug.logger & debug.FLAG_APP and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,))
for targetAddrName in config.getTargetNames(snmpEngine, notifyTag):
(transportDomain, transportAddress, timeout,
@@ -261,7 +261,7 @@ class NotificationOriginator(object):
# (filterSubtree, filterMask,
# filterType) = config.getNotifyFilter(filterProfileName)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP 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))
@@ -270,16 +270,16 @@ class NotificationOriginator(object):
if varName in (sysUpTime.name, snmpTrapOID.name):
continue
try:
- snmpEngine.accessControlModel[self.acmID].isAccessAllowed(
+ snmpEngine.accessControlModel[self.ACM_ID].isAccessAllowed(
snmpEngine, securityModel, securityName,
securityLevel, 'notify', contextName, varName
)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName))
except error.StatusInformation:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % (
varName, securityName))
return
@@ -305,7 +305,7 @@ class NotificationOriginator(object):
except error.StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % (
sendRequestHandle, statusInformation))
if notificationHandle not in self.__pendingNotifications or \
@@ -318,7 +318,7 @@ class NotificationOriginator(object):
cbCtx)
return notificationHandle
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % (
notificationHandle, sendRequestHandle, timeout))
@@ -327,7 +327,7 @@ class NotificationOriginator(object):
self.__pendingNotifications[notificationHandle] = set()
self.__pendingNotifications[notificationHandle].add(sendRequestHandle)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % (
notificationHandle, sendRequestHandle))
diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py
index 9e3fcc24..c286ec54 100644
--- a/pysnmp/entity/rfc3413/ntfrcv.py
+++ b/pysnmp/entity/rfc3413/ntfrcv.py
@@ -53,11 +53,11 @@ class NotificationReceiver(object):
errorIndex = 0
varBinds = v2c.apiPDU.getVarBinds(PDU)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))
# 3.4
- if PDU.tagSet in rfc3411.confirmedClassPDUs:
+ if PDU.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# 3.4.1 --> no-op
rspPDU = v2c.apiPDU.getResponse(PDU)
@@ -67,7 +67,7 @@ class NotificationReceiver(object):
v2c.apiPDU.setErrorIndex(rspPDU, errorIndex)
v2c.apiPDU.setVarBinds(rspPDU, varBinds)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint()))
# Agent-side API complies with SMIv2
@@ -85,18 +85,18 @@ class NotificationReceiver(object):
stateReference, statusInformation)
except error.StatusInformation as exc:
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processPdu: stateReference %s, statusInformation %s' % (stateReference, exc))
snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB',
'snmpSilentDrops')
snmpSilentDrops.syntax += 1
- elif PDU.tagSet in rfc3411.unconfirmedClassPDUs:
+ elif PDU.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS:
pass
else:
raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
- debug.logger & debug.flagApp and debug.logger(
+ debug.logger & debug.FLAG_APP and debug.logger(
'processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (
stateReference, self.__cbFun, self.__cbCtx, varBinds))
diff --git a/pysnmp/error.py b/pysnmp/error.py
index f8004638..e53c6af4 100644
--- a/pysnmp/error.py
+++ b/pysnmp/error.py
@@ -9,6 +9,7 @@ import sys
class PySnmpError(Exception):
+
def __init__(self, *args):
msg = args and str(args[0]) or ''
diff --git a/pysnmp/hlapi/transport.py b/pysnmp/hlapi/transport.py
index 351f01f1..61c01dd1 100644
--- a/pysnmp/hlapi/transport.py
+++ b/pysnmp/hlapi/transport.py
@@ -12,8 +12,8 @@ __all__ = []
class AbstractTransportTarget(object):
- transportDomain = None
- protoTransport = AbstractTransport
+ TRANSPORT_DOMAIN = None
+ PROTO_TRANSPORT = AbstractTransport
def __init__(self, transportAddr, timeout=1, retries=5, tagList=null):
self.transportAddr = self._resolveAddr(transportAddr)
@@ -30,7 +30,7 @@ class AbstractTransportTarget(object):
)
def getTransportInfo(self):
- return self.transportDomain, self.transportAddr
+ return self.TRANSPORT_DOMAIN, self.transportAddr
def setLocalAddress(self, iface):
"""Set source address.
@@ -50,13 +50,13 @@ class AbstractTransportTarget(object):
return self
def openClientMode(self):
- self.transport = self.protoTransport().openClientMode(self.iface)
+ self.transport = self.PROTO_TRANSPORT().openClientMode(self.iface)
return self.transport
def verifyDispatcherCompatibility(self, snmpEngine):
- if not self.protoTransport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher):
+ if not self.PROTO_TRANSPORT.isCompatibleWithDispatcher(snmpEngine.transportDispatcher):
raise error.PySnmpError('Transport %r is not compatible with dispatcher %r' % (
- self.protoTransport, snmpEngine.transportDispatcher))
+ self.PROTO_TRANSPORT, snmpEngine.transportDispatcher))
def _resolveAddr(self, transportAddr):
raise NotImplementedError()
diff --git a/pysnmp/hlapi/v1arch/asyncore/cmdgen.py b/pysnmp/hlapi/v1arch/asyncore/cmdgen.py
index 3d52bc43..a0eb1293 100644
--- a/pysnmp/hlapi/v1arch/asyncore/cmdgen.py
+++ b/pysnmp/hlapi/v1arch/asyncore/cmdgen.py
@@ -151,7 +151,7 @@ def getCmd(snmpDispatcher, authData, transportTarget, *varBinds, **options):
if lookupMib:
varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
- pMod = api.protoModules[authData.mpModel]
+ pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetRequestPDU()
pMod.apiPDU.setDefaults(reqPdu)
@@ -295,7 +295,7 @@ def setCmd(snmpDispatcher, authData, transportTarget,
if lookupMib:
varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
- pMod = api.protoModules[authData.mpModel]
+ pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.SetRequestPDU()
pMod.apiPDU.setDefaults(reqPdu)
@@ -440,7 +440,7 @@ def nextCmd(snmpDispatcher, authData, transportTarget,
if lookupMib:
varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
- pMod = api.protoModules[authData.mpModel]
+ pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetNextRequestPDU()
pMod.apiPDU.setDefaults(reqPdu)
@@ -616,7 +616,7 @@ def bulkCmd(snmpDispatcher, authData, transportTarget,
if lookupMib:
varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
- pMod = api.protoModules[authData.mpModel]
+ pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqPdu = pMod.GetBulkRequestPDU()
pMod.apiBulkPDU.setDefaults(reqPdu)
diff --git a/pysnmp/hlapi/v1arch/asyncore/dispatch.py b/pysnmp/hlapi/v1arch/asyncore/dispatch.py
index 16a187dd..76f98401 100644
--- a/pysnmp/hlapi/v1arch/asyncore/dispatch.py
+++ b/pysnmp/hlapi/v1arch/asyncore/dispatch.py
@@ -26,4 +26,4 @@ class SnmpDispatcher(AbstractSnmpDispatcher):
application. In a multithreaded environment, each thread that
works with SNMP must have its own `SnmpDispatcher` instance.
"""
- protoDispatcher = AsyncoreDispatcher
+ PROTO_DISPATCHER = AsyncoreDispatcher
diff --git a/pysnmp/hlapi/v1arch/asyncore/ntforg.py b/pysnmp/hlapi/v1arch/asyncore/ntforg.py
index d46ade57..80caeac5 100644
--- a/pysnmp/hlapi/v1arch/asyncore/ntforg.py
+++ b/pysnmp/hlapi/v1arch/asyncore/ntforg.py
@@ -14,7 +14,7 @@ from pysnmp import error
__all__ = ['sendNotification']
-vbProcessor = NotificationOriginatorVarBinds()
+VB_PROCESSOR = NotificationOriginatorVarBinds()
def sendNotification(snmpDispatcher, authData, transportTarget,
@@ -132,7 +132,7 @@ def sendNotification(snmpDispatcher, authData, transportTarget,
varBinds = pMod.apiTrapPDU.getVarBinds(rspPdu)
if lookupMib:
- varBinds = vbProcessor.unmakeVarBinds(snmpDispatcher.cache, varBinds)
+ varBinds = VB_PROCESSOR.unmakeVarBinds(snmpDispatcher.cache, varBinds)
nextStateHandle = pMod.getNextRequestID()
@@ -153,7 +153,7 @@ def sendNotification(snmpDispatcher, authData, transportTarget,
lookupMib, cbFun, cbCtx = [options.get(x) for x in ('lookupMib', 'cbFun', 'cbCtx')]
if lookupMib:
- varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
+ varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
# # make sure required PDU payload is in place
# completeVarBinds = []
@@ -171,7 +171,7 @@ def sendNotification(snmpDispatcher, authData, transportTarget,
# varBinds.insert(0, (ObjectIdentifier(pMod.apiTrapPDU.sysUpTime), pMod.Integer(0)))
# input PDU is always v2c
- pMod = api.protoModules[api.protoVersion2c]
+ pMod = api.PROTOCOL_MODULES[api.SNMP_VERSION_2C]
if notifyType == 'trap':
reqPdu = pMod.TrapPDU()
diff --git a/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py b/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py
index f0c19f59..bb7b9ad5 100644
--- a/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py
+++ b/pysnmp/hlapi/v1arch/asyncore/sync/cmdgen.py
@@ -20,7 +20,7 @@ if version_info[:2] < (2, 6):
def next(iter):
return iter.next()
-vbProcessor = CommandGeneratorVarBinds()
+VB_PROCESSOR = CommandGeneratorVarBinds()
def getCmd(snmpDispatcher, authData, transportTarget,
@@ -309,7 +309,7 @@ def nextCmd(snmpDispatcher, authData, transportTarget,
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
- initialVarBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
+ initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
totalRows = totalCalls = 0
@@ -360,7 +360,7 @@ def nextCmd(snmpDispatcher, authData, transportTarget,
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
- initialVarBinds = varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
+ initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
totalRows += 1
totalCalls += 1
@@ -489,7 +489,7 @@ def bulkCmd(snmpDispatcher, authData, transportTarget,
maxRows = options.pop('maxRows', 0)
maxCalls = options.pop('maxCalls', 0)
- initialVarBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, varBinds)
+ initialVarBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, varBinds)
nullVarBinds = [False] * len(initialVarBinds)
@@ -570,4 +570,4 @@ def bulkCmd(snmpDispatcher, authData, transportTarget,
nextVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow)
if nextVarBinds:
- initialVarBinds = varBinds = vbProcessor.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
+ initialVarBinds = varBinds = VB_PROCESSOR.makeVarBinds(snmpDispatcher.cache, nextVarBinds)
diff --git a/pysnmp/hlapi/v1arch/asyncore/transport.py b/pysnmp/hlapi/v1arch/asyncore/transport.py
index 78630e27..452550a4 100644
--- a/pysnmp/hlapi/v1arch/asyncore/transport.py
+++ b/pysnmp/hlapi/v1arch/asyncore/transport.py
@@ -43,8 +43,8 @@ class UdpTransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp.domainName
- protoTransport = udp.UdpSocketTransport
+ TRANSPORT_DOMAIN = udp.DOMAIN_NAME
+ PROTO_TRANSPORT = udp.UdpSocketTransport
def _resolveAddr(self, transportAddr):
try:
@@ -96,8 +96,8 @@ class Udp6TransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp6.domainName
- protoTransport = udp6.Udp6SocketTransport
+ TRANSPORT_DOMAIN = udp6.DOMAIN_NAME
+ PROTO_TRANSPORT = udp6.Udp6SocketTransport
def _resolveAddr(self, transportAddr):
try:
diff --git a/pysnmp/hlapi/v1arch/dispatch.py b/pysnmp/hlapi/v1arch/dispatch.py
index 48c67599..e52c999d 100644
--- a/pysnmp/hlapi/v1arch/dispatch.py
+++ b/pysnmp/hlapi/v1arch/dispatch.py
@@ -33,13 +33,14 @@ class AbstractSnmpDispatcher(object):
works with SNMP must have its own `SnmpDispatcher` instance.
"""
- protoDispatcher = None
+ PROTO_DISPATCHER = None
def __init__(self, transportDispatcher=None):
if transportDispatcher:
self.transportDispatcher = transportDispatcher
+
else:
- self.transportDispatcher = self.protoDispatcher()
+ self.transportDispatcher = self.PROTO_DISPATCHER()
self._automaticDispatcher = transportDispatcher is not self.transportDispatcher
self._configuredTransports = set()
@@ -77,7 +78,7 @@ class AbstractSnmpDispatcher(object):
)
self._configuredTransports.add(transportTarget.transportDomain)
- pMod = api.protoModules[authData.mpModel]
+ pMod = api.PROTOCOL_MODULES[authData.mpModel]
reqMsg = pMod.Message()
pMod.apiMessage.setDefaults(reqMsg)
@@ -114,9 +115,9 @@ class AbstractSnmpDispatcher(object):
except error.ProtocolError:
return null # n.b the whole buffer gets dropped
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % mpModel)
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: msgVersion %s, msg decoded' % mpModel)
- pMod = api.protoModules[mpModel]
+ pMod = api.PROTOCOL_MODULES[mpModel]
while wholeMsg:
rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message())
diff --git a/pysnmp/hlapi/v3arch/asyncio/cmdgen.py b/pysnmp/hlapi/v3arch/asyncio/cmdgen.py
index 278be5be..8d978573 100644
--- a/pysnmp/hlapi/v3arch/asyncio/cmdgen.py
+++ b/pysnmp/hlapi/v3arch/asyncio/cmdgen.py
@@ -42,13 +42,14 @@ from pysnmp.proto.api import v2c
try:
import asyncio
+
except ImportError:
import trollius as asyncio
__all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'isEndOfMib']
-vbProcessor = CommandGeneratorVarBinds()
-lcd = CommandGeneratorLcdConfigurator()
+VB_PROCESSOR = CommandGeneratorVarBinds()
+LCD = CommandGeneratorLcdConfigurator()
isEndOfMib = lambda varBinds: not v2c.apiPDU.getNextVarBinds(varBinds)
@@ -136,8 +137,8 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
if future.cancelled():
return
try:
- varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds,
- lookupMib)
+ varBindsUnmade = VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBinds,
+ lookupMib)
except Exception as e:
future.set_exception(e)
else:
@@ -145,7 +146,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
(errorIndication, errorStatus, errorIndex, varBindsUnmade)
)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
future = asyncio.Future()
@@ -153,7 +154,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
return future
@@ -242,8 +243,8 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
if future.cancelled():
return
try:
- varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds,
- lookupMib)
+ varBindsUnmade = VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBinds,
+ lookupMib)
except Exception as e:
future.set_exception(e)
else:
@@ -251,7 +252,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
(errorIndication, errorStatus, errorIndex, varBindsUnmade)
)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
future = asyncio.Future()
@@ -259,7 +260,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
return future
@@ -352,9 +353,9 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
if future.cancelled():
return
try:
- varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine.cache,
- varBindTableRow,
- lookupMib)
+ varBindsUnmade = [VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
+ varBindTableRow,
+ lookupMib)
for varBindTableRow in varBindTable]
except Exception as e:
future.set_exception(e)
@@ -363,7 +364,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
(errorIndication, errorStatus, errorIndex, varBindsUnmade)
)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
future = asyncio.Future()
@@ -371,7 +372,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
return future
@@ -493,9 +494,9 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
if future.cancelled():
return
try:
- varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine.cache,
- varBindTableRow,
- lookupMib)
+ varBindsUnmade = [VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
+ varBindTableRow,
+ lookupMib)
for varBindTableRow in varBindTable]
except Exception as e:
future.set_exception(e)
@@ -504,7 +505,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
(errorIndication, errorStatus, errorIndex, varBindsUnmade)
)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
future = asyncio.Future()
@@ -512,7 +513,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.BulkCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, nonRepeaters, maxRepetitions,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), future)
)
return future
diff --git a/pysnmp/hlapi/v3arch/asyncio/ntforg.py b/pysnmp/hlapi/v3arch/asyncio/ntforg.py
index 67601fe4..0b974538 100644
--- a/pysnmp/hlapi/v3arch/asyncio/ntforg.py
+++ b/pysnmp/hlapi/v3arch/asyncio/ntforg.py
@@ -23,8 +23,8 @@ except ImportError:
__all__ = ['sendNotification']
-vbProcessor = NotificationOriginatorVarBinds()
-lcd = NotificationOriginatorLcdConfigurator()
+VB_PROCESSOR = NotificationOriginatorVarBinds()
+LCD = NotificationOriginatorLcdConfigurator()
@asyncio.coroutine
@@ -142,8 +142,8 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
if future.cancelled():
return
try:
- varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds,
- lookupMib)
+ varBindsUnmade = VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBinds,
+ lookupMib)
except Exception as e:
future.set_exception(e)
else:
@@ -151,7 +151,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
(errorIndication, errorStatus, errorIndex, varBindsUnmade)
)
- notifyName = lcd.configure(
+ notifyName = LCD.configure(
snmpEngine, authData, transportTarget, notifyType,
contextData.contextName)
@@ -162,7 +162,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyName,
contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds),
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds),
__cbFun,
(options.get('lookupMib', True), future)
)
diff --git a/pysnmp/hlapi/v3arch/asyncio/transport.py b/pysnmp/hlapi/v3arch/asyncio/transport.py
index aeeeb51f..581ee549 100644
--- a/pysnmp/hlapi/v3arch/asyncio/transport.py
+++ b/pysnmp/hlapi/v3arch/asyncio/transport.py
@@ -48,8 +48,8 @@ class UdpTransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp.domainName
- protoTransport = udp.UdpAsyncioTransport
+ TRANSPORT_DOMAIN = udp.domainName
+ PROTO_TRANSPORT = udp.UdpAsyncioTransport
def _resolveAddr(self, transportAddr):
try:
@@ -109,8 +109,8 @@ class Udp6TransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp6.domainName
- protoTransport = udp6.Udp6AsyncioTransport
+ TRANSPORT_DOMAIN = udp6.domainName
+ PROTO_TRANSPORT = udp6.Udp6AsyncioTransport
def _resolveAddr(self, transportAddr):
try:
diff --git a/pysnmp/hlapi/v3arch/asyncore/cmdgen.py b/pysnmp/hlapi/v3arch/asyncore/cmdgen.py
index 475a2ea7..53b4cd1b 100644
--- a/pysnmp/hlapi/v3arch/asyncore/cmdgen.py
+++ b/pysnmp/hlapi/v3arch/asyncore/cmdgen.py
@@ -15,8 +15,8 @@ from pysnmp.proto.api import v2c
__all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'isEndOfMib']
-vbProcessor = CommandGeneratorVarBinds()
-lcd = CommandGeneratorLcdConfigurator()
+VB_PROCESSOR = CommandGeneratorVarBinds()
+LCD = CommandGeneratorLcdConfigurator()
isEndOfMib = lambda varBinds: not v2c.apiPDU.getNextVarBinds(varBinds)
@@ -117,17 +117,17 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
if cbFun:
return cbFun(snmpEngine, sendRequestHandle, errorIndication,
errorStatus, errorIndex,
- vbProcessor.unmakeVarBinds(
+ VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib
), cbCtx)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
return cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True),
options.get('cbFun'), options.get('cbCtx'))
)
@@ -229,16 +229,16 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
lookupMib, cbFun, cbCtx = cbCtx
return cbFun(snmpEngine, sendRequestHandle, errorIndication,
errorStatus, errorIndex,
- vbProcessor.unmakeVarBinds(
+ VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib
), cbCtx)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
return cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
- contextData.contextName, vbProcessor.makeVarBinds(snmpEngine.cache, varBinds),
+ contextData.contextName, VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds),
__cbFun, (options.get('lookupMib', True),
options.get('cbFun'), options.get('cbCtx'))
)
@@ -341,17 +341,17 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
lookupMib, cbFun, cbCtx = cbCtx
return cbFun(snmpEngine, sendRequestHandle, errorIndication,
errorStatus, errorIndex,
- [vbProcessor.unmakeVarBinds(snmpEngine.cache, varBindTableRow, lookupMib) for varBindTableRow in
+ [VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBindTableRow, lookupMib) for varBindTableRow in
varBindTable],
cbCtx)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
return cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName,
contextData.contextEngineId, contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds),
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds),
__cbFun, (options.get('lookupMib', True),
options.get('cbFun'), options.get('cbCtx'))
)
@@ -484,16 +484,16 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
lookupMib, cbFun, cbCtx = cbCtx
return cbFun(snmpEngine.cache, sendRequestHandle, errorIndication,
errorStatus, errorIndex,
- [vbProcessor.unmakeVarBinds(snmpEngine.cache, varBindTableRow, lookupMib) for varBindTableRow in
+ [VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBindTableRow, lookupMib) for varBindTableRow in
varBindTable], cbCtx)
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
return cmdgen.BulkCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, nonRepeaters, maxRepetitions,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True),
options.get('cbFun'), options.get('cbCtx'))
)
diff --git a/pysnmp/hlapi/v3arch/asyncore/ntforg.py b/pysnmp/hlapi/v3arch/asyncore/ntforg.py
index c6669d35..e69eccbf 100644
--- a/pysnmp/hlapi/v3arch/asyncore/ntforg.py
+++ b/pysnmp/hlapi/v3arch/asyncore/ntforg.py
@@ -14,8 +14,8 @@ from pysnmp.hlapi.v3arch.asyncore.transport import *
__all__ = ['sendNotification']
-vbProcessor = NotificationOriginatorVarBinds()
-lcd = NotificationOriginatorLcdConfigurator()
+VB_PROCESSOR = NotificationOriginatorVarBinds()
+LCD = NotificationOriginatorLcdConfigurator()
def sendNotification(snmpEngine, authData, transportTarget, contextData,
@@ -156,18 +156,18 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
return cbFun and cbFun(
snmpEngine, sendRequestHandle, errorIndication,
errorStatus, errorIndex,
- vbProcessor.unmakeVarBinds(
+ VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib
), cbCtx
)
- notifyName = lcd.configure(snmpEngine, authData, transportTarget,
+ notifyName = LCD.configure(snmpEngine, authData, transportTarget,
notifyType, contextData.contextName)
return ntforg.NotificationOriginator().sendVarBinds(
snmpEngine, notifyName,
contextData.contextEngineId, contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True),
options.get('cbFun'), options.get('cbCtx'))
)
diff --git a/pysnmp/hlapi/v3arch/asyncore/sync/compat/cmdgen.py b/pysnmp/hlapi/v3arch/asyncore/sync/compat/cmdgen.py
index f2230826..bb9703f4 100644
--- a/pysnmp/hlapi/v3arch/asyncore/sync/compat/cmdgen.py
+++ b/pysnmp/hlapi/v3arch/asyncore/sync/compat/cmdgen.py
@@ -19,6 +19,7 @@ __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'next']
def next(iter):
return iter.next()
+
def getCmd(snmpEngine, authData, transportTarget, contextData,
*varBinds, **options):
# noinspection PyShadowingNames
diff --git a/pysnmp/hlapi/v3arch/asyncore/transport.py b/pysnmp/hlapi/v3arch/asyncore/transport.py
index 77a37c65..61d32aaa 100644
--- a/pysnmp/hlapi/v3arch/asyncore/transport.py
+++ b/pysnmp/hlapi/v3arch/asyncore/transport.py
@@ -49,8 +49,8 @@ class UdpTransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp.domainName
- protoTransport = udp.UdpSocketTransport
+ TRANSPORT_DOMAIN = udp.DOMAIN_NAME
+ PROTO_TRANSPORT = udp.UdpSocketTransport
def _resolveAddr(self, transportAddr):
try:
@@ -107,8 +107,8 @@ class Udp6TransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp6.domainName
- protoTransport = udp6.Udp6SocketTransport
+ TRANSPORT_DOMAIN = udp6.DOMAIN_NAME
+ PROTO_TRANSPORT = udp6.Udp6SocketTransport
def _resolveAddr(self, transportAddr):
try:
diff --git a/pysnmp/hlapi/v3arch/auth.py b/pysnmp/hlapi/v3arch/auth.py
index 2c729b22..47152c88 100644
--- a/pysnmp/hlapi/v3arch/auth.py
+++ b/pysnmp/hlapi/v3arch/auth.py
@@ -8,15 +8,89 @@ from pysnmp.entity import config
from pysnmp import error
from pyasn1.compat.octets import null
-__all__ = ['CommunityData', 'UsmUserData',
- 'usm3DESEDEPrivProtocol', 'usmAesCfb128Protocol',
- 'usmAesCfb192Protocol', 'usmAesCfb256Protocol',
- 'usmAesBlumenthalCfb192Protocol', 'usmAesBlumenthalCfb256Protocol',
- 'usmDESPrivProtocol', 'usmHMACMD5AuthProtocol',
- 'usmHMACSHAAuthProtocol', 'usmHMAC128SHA224AuthProtocol',
- 'usmHMAC192SHA256AuthProtocol', 'usmHMAC256SHA384AuthProtocol',
- 'usmHMAC384SHA512AuthProtocol', 'usmNoAuthProtocol',
- 'usmNoPrivProtocol']
+__all__ = [
+ 'CommunityData', 'UsmUserData',
+ 'USM_AUTH_NONE', 'USM_AUTH_HMAC96_MD5',
+ 'USM_AUTH_HMAC96_SHA', 'USM_AUTH_HMAC128_SHA224',
+ 'USM_AUTH_HMAC192_SHA256', 'USM_AUTH_HMAC256_SHA384',
+ 'USM_AUTH_HMAC384_SHA512', 'USM_PRIV_NONE',
+ 'USM_PRIV_CBC56_DES', 'USM_PRIV_CBC168_3DES',
+ 'USM_PRIV_CFB128_AES', 'USM_PRIV_CFB192_AES',
+ 'USM_PRIV_CFB256_AES', 'USM_PRIV_CFB192_AES_BLUMENTHAL',
+ 'USM_PRIV_CFB256_AES_BLUMENTHAL',
+ # backward-compatible constants
+ 'usm3DESEDEPrivProtocol', 'usmAesCfb128Protocol',
+ 'usmAesCfb192Protocol', 'usmAesCfb256Protocol',
+ 'usmAesBlumenthalCfb192Protocol', 'usmAesBlumenthalCfb256Protocol',
+ 'usmDESPrivProtocol', 'usmHMACMD5AuthProtocol',
+ 'usmHMACSHAAuthProtocol', 'usmHMAC128SHA224AuthProtocol',
+ 'usmHMAC192SHA256AuthProtocol', 'usmHMAC256SHA384AuthProtocol',
+ 'usmHMAC384SHA512AuthProtocol', 'usmNoAuthProtocol',
+ 'usmNoPrivProtocol'
+]
+
+
+USM_AUTH_NONE = config.USM_AUTH_NONE
+"""No Authentication Protocol"""
+
+USM_AUTH_HMAC96_MD5 = config.USM_AUTH_HMAC96_MD5
+"""The HMAC-MD5-96 Digest Authentication Protocol (:RFC:`3414#section-6`)"""
+
+USM_AUTH_HMAC96_SHA = config.USM_AUTH_HMAC96_SHA
+"""The HMAC-SHA-96 Digest Authentication Protocol AKA SHA-1 (:RFC:`3414#section-7`)"""
+
+USM_AUTH_HMAC128_SHA224 = config.USM_AUTH_HMAC128_SHA224
+"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
+
+USM_AUTH_HMAC192_SHA256 = config.USM_AUTH_HMAC192_SHA256
+"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
+
+USM_AUTH_HMAC256_SHA384 = config.USM_AUTH_HMAC256_SHA384
+"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
+
+USM_AUTH_HMAC384_SHA512 = config.USM_AUTH_HMAC384_SHA512
+"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
+
+USM_PRIV_NONE = config.USM_PRIV_NONE
+"""No Privacy Protocol"""
+
+USM_PRIV_CBC56_DES = config.USM_PRIV_CBC56_DES
+"""The CBC56-DES Symmetric Encryption Protocol (:RFC:`3414#section-8`)"""
+
+USM_PRIV_CBC168_3DES = config.USM_PRIV_CBC168_3DES
+"""The 3DES-EDE Symmetric Encryption Protocol (`draft-reeder-snmpv3-usm-3desede-00 <https:://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00#section-5>`_)"""
+
+USM_PRIV_CFB128_AES = config.USM_PRIV_CFB128_AES
+"""The CFB128-AES-128 Symmetric Encryption Protocol (:RFC:`3826#section-3`)"""
+
+USM_PRIV_CFB192_AES = config.USM_PRIV_CFB192_AES
+"""The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_) with Reeder key localization"""
+
+USM_PRIV_CFB256_AES = config.USM_PRIV_CFB256_AES
+"""The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_) with Reeder key localization"""
+
+USM_PRIV_CFB192_AES_BLUMENTHAL = config.USM_PRIV_CFB192_AES_BLUMENTHAL
+"""The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_)"""
+
+USM_PRIV_CFB256_AES_BLUMENTHAL = config.USM_PRIV_CFB256_AES_BLUMENTHAL
+"""The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_)"""
+
+# Backward-compatible protocol IDs
+usmNoAuthProtocol = USM_AUTH_NONE
+usmHMACMD5AuthProtocol = USM_AUTH_HMAC96_MD5
+usmHMACSHAAuthProtocol = USM_AUTH_HMAC96_SHA
+usmHMAC128SHA224AuthProtocol = USM_AUTH_HMAC128_SHA224
+usmHMAC192SHA256AuthProtocol = USM_AUTH_HMAC192_SHA256
+usmHMAC256SHA384AuthProtocol = USM_AUTH_HMAC256_SHA384
+usmHMAC384SHA512AuthProtocol = USM_AUTH_HMAC384_SHA512
+usmNoPrivProtocol = USM_PRIV_NONE
+usmDESPrivProtocol = USM_PRIV_CBC56_DES
+usm3DESEDEPrivProtocol = USM_PRIV_CBC168_3DES
+usmAesCfb128Protocol = USM_PRIV_CFB128_AES
+usmAesCfb192Protocol = USM_PRIV_CFB192_AES
+usmAesCfb256Protocol = USM_PRIV_CFB256_AES
+usmAesBlumenthalCfb192Protocol = USM_PRIV_CFB192_AES_BLUMENTHAL
+usmAesBlumenthalCfb256Protocol = USM_PRIV_CFB256_AES_BLUMENTHAL
class CommunityData(object):
@@ -151,51 +225,6 @@ class CommunityData(object):
securityName is None and self.securityName or securityName
)
-usmNoAuthProtocol = config.usmNoAuthProtocol
-"""No Authentication Protocol"""
-
-usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol
-"""The HMAC-MD5-96 Digest Authentication Protocol (:RFC:`3414#section-6`)"""
-
-usmHMACSHAAuthProtocol = config.usmHMACSHAAuthProtocol
-"""The HMAC-SHA-96 Digest Authentication Protocol AKA SHA-1 (:RFC:`3414#section-7`)"""
-
-usmHMAC128SHA224AuthProtocol = config.usmHMAC128SHA224AuthProtocol
-"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
-
-usmHMAC192SHA256AuthProtocol = config.usmHMAC192SHA256AuthProtocol
-"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
-
-usmHMAC256SHA384AuthProtocol = config.usmHMAC256SHA384AuthProtocol
-"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
-
-usmHMAC384SHA512AuthProtocol = config.usmHMAC384SHA512AuthProtocol
-"""The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)"""
-
-usmNoPrivProtocol = config.usmNoPrivProtocol
-"""No Privacy Protocol"""
-
-usmDESPrivProtocol = config.usmDESPrivProtocol
-"""The CBC-DES Symmetric Encryption Protocol (:RFC:`3414#section-8`)"""
-
-usm3DESEDEPrivProtocol = config.usm3DESEDEPrivProtocol
-"""The 3DES-EDE Symmetric Encryption Protocol (`draft-reeder-snmpv3-usm-3desede-00 <https:://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00#section-5>`_)"""
-
-usmAesCfb128Protocol = config.usmAesCfb128Protocol
-"""The CFB128-AES-128 Symmetric Encryption Protocol (:RFC:`3826#section-3`)"""
-
-usmAesCfb192Protocol = config.usmAesCfb192Protocol
-"""The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_) with Reeder key localization"""
-
-usmAesCfb256Protocol = config.usmAesCfb256Protocol
-"""The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_) with Reeder key localization"""
-
-usmAesBlumenthalCfb192Protocol = config.usmAesBlumenthalCfb192Protocol
-"""The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_)"""
-
-usmAesBlumenthalCfb256Protocol = config.usmAesBlumenthalCfb256Protocol
-"""The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 <https:://tools.ietf.org/html/draft-blumenthal-aes-usm-04#section-3>`_)"""
-
class UsmUserData(object):
"""Creates SNMP v3 User Security Model (USM) configuration entry.
@@ -264,8 +293,8 @@ class UsmUserData(object):
"""
authKey = privKey = None
- authProtocol = config.usmNoAuthProtocol
- privProtocol = config.usmNoPrivProtocol
+ authProtocol = config.USM_AUTH_NONE
+ privProtocol = config.USM_PRIV_NONE
securityLevel = 'noAuthNoPriv'
securityModel = 3
mpModel = 3
@@ -285,7 +314,7 @@ class UsmUserData(object):
if authKey is not None:
self.authKey = authKey
if authProtocol is None:
- self.authProtocol = config.usmHMACMD5AuthProtocol
+ self.authProtocol = config.USM_AUTH_HMAC96_MD5
else:
self.authProtocol = authProtocol
if self.securityLevel != 'authPriv':
@@ -293,11 +322,11 @@ class UsmUserData(object):
if privKey is not None:
self.privKey = privKey
- if self.authProtocol == config.usmNoAuthProtocol:
+ if self.authProtocol == config.USM_AUTH_NONE:
raise error.PySnmpError('Privacy implies authenticity')
self.securityLevel = 'authPriv'
if privProtocol is None:
- self.privProtocol = config.usmDESPrivProtocol
+ self.privProtocol = config.USM_PRIV_CBC56_DES
else:
self.privProtocol = privProtocol
diff --git a/pysnmp/hlapi/v3arch/lcd.py b/pysnmp/hlapi/v3arch/lcd.py
index c56592e6..aefee634 100644
--- a/pysnmp/hlapi/v3arch/lcd.py
+++ b/pysnmp/hlapi/v3arch/lcd.py
@@ -79,22 +79,22 @@ class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator):
)
cache['parm'][paramsKey] = paramsName, 1
- if transportTarget.transportDomain in cache['tran']:
- transport, useCount = cache['tran'][transportTarget.transportDomain]
+ if transportTarget.TRANSPORT_DOMAIN in cache['tran']:
+ transport, useCount = cache['tran'][transportTarget.TRANSPORT_DOMAIN]
transportTarget.verifyDispatcherCompatibility(snmpEngine)
- cache['tran'][transportTarget.transportDomain] = transport, useCount + 1
- elif config.getTransport(snmpEngine, transportTarget.transportDomain):
+ cache['tran'][transportTarget.TRANSPORT_DOMAIN] = transport, useCount + 1
+ elif config.getTransport(snmpEngine, transportTarget.TRANSPORT_DOMAIN):
transportTarget.verifyDispatcherCompatibility(snmpEngine)
else:
transport = transportTarget.openClientMode()
config.addTransport(
snmpEngine,
- transportTarget.transportDomain,
+ transportTarget.TRANSPORT_DOMAIN,
transport
)
- cache['tran'][transportTarget.transportDomain] = transport, 1
+ cache['tran'][transportTarget.TRANSPORT_DOMAIN] = transport, 1
- transportKey = (paramsName, transportTarget.transportDomain,
+ transportKey = (paramsName, transportTarget.TRANSPORT_DOMAIN,
transportTarget.transportAddr,
transportTarget.timeout,
transportTarget.retries,
@@ -108,7 +108,7 @@ class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator):
addrName = 'a%s' % self.nextID()
config.addTargetAddr(
snmpEngine, addrName,
- transportTarget.transportDomain,
+ transportTarget.TRANSPORT_DOMAIN,
transportTarget.transportAddr,
paramsName,
transportTarget.timeout * 100,
diff --git a/pysnmp/hlapi/v3arch/twisted/cmdgen.py b/pysnmp/hlapi/v3arch/twisted/cmdgen.py
index cb82a93a..028af30a 100644
--- a/pysnmp/hlapi/v3arch/twisted/cmdgen.py
+++ b/pysnmp/hlapi/v3arch/twisted/cmdgen.py
@@ -18,8 +18,8 @@ from twisted.python.failure import Failure
__all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'isEndOfMib']
-vbProcessor = CommandGeneratorVarBinds()
-lcd = CommandGeneratorLcdConfigurator()
+VB_PROCESSOR = CommandGeneratorVarBinds()
+LCD = CommandGeneratorLcdConfigurator()
isEndOfMib = lambda varBinds: not v2c.apiPDU.getNextVarBinds(varBinds)
@@ -120,7 +120,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
deferred.errback(Failure(errorIndication))
else:
try:
- varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds, lookupMib)
+ varBindsUnmade = VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBinds, lookupMib)
except Exception as e:
deferred.errback(Failure(e))
@@ -128,7 +128,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
else:
deferred.callback((errorStatus, errorIndex, varBindsUnmade))
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
deferred = Deferred()
@@ -136,7 +136,7 @@ def getCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.GetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), deferred)
)
return deferred
@@ -237,7 +237,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
deferred.errback(Failure(errorIndication))
else:
try:
- varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine.cache, varBinds, lookupMib)
+ varBindsUnmade = VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache, varBinds, lookupMib)
except Exception as e:
deferred.errback(Failure(e))
@@ -245,7 +245,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
else:
deferred.callback((errorStatus, errorIndex, varBindsUnmade))
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
deferred = Deferred()
@@ -253,7 +253,7 @@ def setCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.SetCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), deferred)
)
return deferred
@@ -365,9 +365,9 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
deferred.errback(Failure(errorIndication))
else:
try:
- varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine.cache,
- varBindTableRow,
- lookupMib)
+ varBindsUnmade = [VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
+ varBindTableRow,
+ lookupMib)
for varBindTableRow in varBindTable]
except Exception as e:
@@ -376,7 +376,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
else:
deferred.callback((errorStatus, errorIndex, varBindsUnmade))
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
deferred = Deferred()
@@ -384,7 +384,7 @@ def nextCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.NextCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds), __cbFun,
(options.get('lookupMib', True), deferred)
)
return deferred
@@ -524,9 +524,9 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
deferred.errback(Failure(errorIndication))
else:
try:
- varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine.cache,
- varBindTableRow,
- lookupMib)
+ varBindsUnmade = [VB_PROCESSOR.unmakeVarBinds(snmpEngine.cache,
+ varBindTableRow,
+ lookupMib)
for varBindTableRow in varBindTable]
except Exception as e:
@@ -535,7 +535,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
else:
deferred.callback((errorStatus, errorIndex, varBindsUnmade))
- addrName, paramsName = lcd.configure(
+ addrName, paramsName = LCD.configure(
snmpEngine, authData, transportTarget, contextData.contextName)
deferred = Deferred()
@@ -543,7 +543,7 @@ def bulkCmd(snmpEngine, authData, transportTarget, contextData,
cmdgen.BulkCommandGenerator().sendVarBinds(
snmpEngine, addrName, contextData.contextEngineId,
contextData.contextName, nonRepeaters, maxRepetitions,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds),
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds),
__cbFun,
(options.get('lookupMib', True), deferred)
)
diff --git a/pysnmp/hlapi/v3arch/twisted/ntforg.py b/pysnmp/hlapi/v3arch/twisted/ntforg.py
index 73cb4172..1888d543 100644
--- a/pysnmp/hlapi/v3arch/twisted/ntforg.py
+++ b/pysnmp/hlapi/v3arch/twisted/ntforg.py
@@ -17,8 +17,8 @@ from twisted.python.failure import Failure
__all__ = ['sendNotification']
-vbProcessor = NotificationOriginatorVarBinds()
-lcd = NotificationOriginatorLcdConfigurator()
+VB_PROCESSOR = NotificationOriginatorVarBinds()
+LCD = NotificationOriginatorLcdConfigurator()
def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
@@ -156,7 +156,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
deferred.errback(Failure(errorIndication))
else:
try:
- varBindsUnmade = vbProcessor.unmakeVarBinds(
+ varBindsUnmade = VB_PROCESSOR.unmakeVarBinds(
snmpEngine.cache, varBinds, lookupMib
)
@@ -166,7 +166,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
else:
deferred.callback((errorStatus, errorIndex, varBindsUnmade))
- notifyName = lcd.configure(snmpEngine, authData, transportTarget,
+ notifyName = LCD.configure(snmpEngine, authData, transportTarget,
notifyType, contextData.contextName)
def __trapFun(deferred):
@@ -179,7 +179,7 @@ def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyName,
contextData.contextEngineId,
contextData.contextName,
- vbProcessor.makeVarBinds(snmpEngine.cache, varBinds),
+ VB_PROCESSOR.makeVarBinds(snmpEngine.cache, varBinds),
__cbFun,
(options.get('lookupMib', True), deferred)
)
diff --git a/pysnmp/hlapi/v3arch/twisted/transport.py b/pysnmp/hlapi/v3arch/twisted/transport.py
index 778060f8..dafc6387 100644
--- a/pysnmp/hlapi/v3arch/twisted/transport.py
+++ b/pysnmp/hlapi/v3arch/twisted/transport.py
@@ -47,7 +47,7 @@ class UdpTransportTarget(AbstractTransportTarget):
>>>
"""
- transportDomain = udp.domainName
+ transportDomain = udp.DOMAIN_NAME
protoTransport = udp.UdpTwistedTransport
def _resolveAddr(self, transportAddr):
try:
diff --git a/pysnmp/proto/acmod/rfc3415.py b/pysnmp/proto/acmod/rfc3415.py
index cf020d9f..0d093c4b 100644
--- a/pysnmp/proto/acmod/rfc3415.py
+++ b/pysnmp/proto/acmod/rfc3415.py
@@ -12,7 +12,7 @@ from pysnmp import debug
# 3.2
class Vacm(object):
"""View-based Access Control Model"""
- accessModelID = 3
+ ACCESS_MODEL_ID = 3
_powOfTwoSeq = (128, 64, 32, 16, 8, 4, 2, 1)
@@ -26,7 +26,7 @@ class Vacm(object):
variableName):
mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController
- debug.logger & debug.flagACL and debug.logger(
+ debug.logger & debug.FLAG_ACL and debug.logger(
'isAccessAllowed: securityModel %s, securityName %s, securityLevel %s, viewType %s, contextName %s for variableName %s' % (
securityModel, securityName, securityLevel, viewType, contextName, variableName))
diff --git a/pysnmp/proto/acmod/void.py b/pysnmp/proto/acmod/void.py
index ecc4c4b6..677103b9 100644
--- a/pysnmp/proto/acmod/void.py
+++ b/pysnmp/proto/acmod/void.py
@@ -12,7 +12,7 @@ from pysnmp import debug
# noinspection PyUnusedLocal
class Vacm(object):
"""Void Access Control Model"""
- accessModelID = 0
+ ACCESS_MODEL_ID = 0
def isAccessAllowed(self,
snmpEngine,
@@ -22,7 +22,7 @@ class Vacm(object):
viewType,
contextName,
variableName):
- debug.logger & debug.flagACL and debug.logger(
+ debug.logger & debug.FLAG_ACL and debug.logger(
'isAccessAllowed: viewType %s for variableName %s - OK' % (viewType, variableName)
)
diff --git a/pysnmp/proto/api/__init__.py b/pysnmp/proto/api/__init__.py
index d742ecc7..fd404e5c 100644
--- a/pysnmp/proto/api/__init__.py
+++ b/pysnmp/proto/api/__init__.py
@@ -7,8 +7,8 @@
from pysnmp.proto.api import v1, v2c, verdec
# Protocol versions
-protoVersion1 = 0
-protoVersion2c = 1
-protoModules = {protoVersion1: v1, protoVersion2c: v2c}
+SNMP_VERSION_1 = 0
+SNMP_VERSION_2C = 1
+PROTOCOL_MODULES = {SNMP_VERSION_1: v1, SNMP_VERSION_2C: v2c}
decodeMessageVersion = verdec.decodeMessageVersion
diff --git a/pysnmp/proto/api/verdec.py b/pysnmp/proto/api/verdec.py
index 7076e63c..9bbb73bd 100644
--- a/pysnmp/proto/api/verdec.py
+++ b/pysnmp/proto/api/verdec.py
@@ -23,5 +23,6 @@ def decodeMessageVersion(wholeMsg):
if eoo.endOfOctets.isSameTypeWith(ver):
raise ProtocolError('EOO at SNMP version component')
return ver
- except PyAsn1Error:
- raise ProtocolError('Invalid BER at SNMP version component')
+
+ except PyAsn1Error as exc:
+ raise ProtocolError('Invalid BER at SNMP version component: %s' % exc)
diff --git a/pysnmp/proto/errind.py b/pysnmp/proto/errind.py
index b300d324..0c0dcb80 100644
--- a/pysnmp/proto/errind.py
+++ b/pysnmp/proto/errind.py
@@ -41,90 +41,105 @@ class ErrorIndication(Exception):
class SerializationError(ErrorIndication):
pass
+
serializationError = SerializationError('SNMP message serialization error')
class DeserializationError(ErrorIndication):
pass
+
deserializationError = DeserializationError('SNMP message deserialization error')
class ParseError(DeserializationError):
pass
+
parseError = ParseError('SNMP message deserialization error')
class UnsupportedMsgProcessingModel(ErrorIndication):
pass
+
unsupportedMsgProcessingModel = UnsupportedMsgProcessingModel('Unknown SNMP message processing model ID encountered')
class UnknownPDUHandler(ErrorIndication):
pass
+
unknownPDUHandler = UnknownPDUHandler('Unhandled PDU type encountered')
class UnsupportedPDUtype(ErrorIndication):
pass
+
unsupportedPDUtype = UnsupportedPDUtype('Unsupported SNMP PDU type encountered')
class RequestTimedOut(ErrorIndication):
pass
+
requestTimedOut = RequestTimedOut('No SNMP response received before timeout')
class EmptyResponse(ErrorIndication):
pass
+
emptyResponse = EmptyResponse('Empty SNMP response message')
class NonReportable(ErrorIndication):
pass
+
nonReportable = NonReportable('Report PDU generation not attempted')
class DataMismatch(ErrorIndication):
pass
+
dataMismatch = DataMismatch('SNMP request/response parameters mismatched')
class EngineIDMismatch(ErrorIndication):
pass
+
engineIDMismatch = EngineIDMismatch('SNMP engine ID mismatch encountered')
class UnknownEngineID(ErrorIndication):
pass
+
unknownEngineID = UnknownEngineID('Unknown SNMP engine ID encountered')
class TooBig(ErrorIndication):
pass
+
tooBig = TooBig('SNMP message will be too big')
class LoopTerminated(ErrorIndication):
pass
+
loopTerminated = LoopTerminated('Infinite SNMP entities talk terminated')
class InvalidMsg(ErrorIndication):
pass
+
invalidMsg = InvalidMsg('Invalid SNMP message header parameters encountered')
@@ -133,96 +148,112 @@ invalidMsg = InvalidMsg('Invalid SNMP message header parameters encountered')
class UnknownCommunityName(ErrorIndication):
pass
+
unknownCommunityName = UnknownCommunityName('Unknown SNMP community name encountered')
class NoEncryption(ErrorIndication):
pass
+
noEncryption = NoEncryption('No encryption services configured')
class EncryptionError(ErrorIndication):
pass
+
encryptionError = EncryptionError('Ciphering services not available')
class DecryptionError(ErrorIndication):
pass
+
decryptionError = DecryptionError('Ciphering services not available or ciphertext is broken')
class NoAuthentication(ErrorIndication):
pass
+
noAuthentication = NoAuthentication('No authentication services configured')
class AuthenticationError(ErrorIndication):
pass
+
authenticationError = AuthenticationError('Ciphering services not available or bad parameters')
class AuthenticationFailure(ErrorIndication):
pass
+
authenticationFailure = AuthenticationFailure('Authenticator mismatched')
class UnsupportedAuthProtocol(ErrorIndication):
pass
+
unsupportedAuthProtocol = UnsupportedAuthProtocol('Authentication protocol is not supported')
class UnsupportedPrivProtocol(ErrorIndication):
pass
+
unsupportedPrivProtocol = UnsupportedPrivProtocol('Privacy protocol is not supported')
class UnknownSecurityName(ErrorIndication):
pass
+
unknownSecurityName = UnknownSecurityName('Unknown SNMP security name encountered')
class UnsupportedSecurityModel(ErrorIndication):
pass
+
unsupportedSecurityModel = UnsupportedSecurityModel('Unsupported SNMP security model')
class UnsupportedSecurityLevel(ErrorIndication):
pass
+
unsupportedSecurityLevel = UnsupportedSecurityLevel('Unsupported SNMP security level')
class NotInTimeWindow(ErrorIndication):
pass
+
notInTimeWindow = NotInTimeWindow('SNMP message timing parameters not in windows of trust')
class UnknownUserName(ErrorIndication):
pass
+
unknownUserName = UnknownUserName('Unknown USM user')
class WrongDigest(ErrorIndication):
pass
+
wrongDigest = WrongDigest('Wrong SNMP PDU digest')
class ReportPduReceived(ErrorIndication):
pass
+
reportPduReceived = ReportPduReceived('Remote SNMP engine reported error')
@@ -231,42 +262,50 @@ reportPduReceived = ReportPduReceived('Remote SNMP engine reported error')
class NoSuchView(ErrorIndication):
pass
+
noSuchView = NoSuchView('No such MIB view currently exists')
class NoAccessEntry(ErrorIndication):
pass
+
+
noAccessEntry = NoAccessEntry('Access to MIB node denined')
class NoGroupName(ErrorIndication):
pass
+
noGroupName = NoGroupName('No such VACM group configured')
class NoSuchContext(ErrorIndication):
pass
+
noSuchContext = NoSuchContext('SNMP context now found')
class NotInView(ErrorIndication):
pass
+
notInView = NotInView('Requested OID is out of MIB view')
class AccessAllowed(ErrorIndication):
pass
+
accessAllowed = AccessAllowed()
class OtherError(ErrorIndication):
pass
+
otherError = OtherError('Unspecified SNMP engine error occurred')
@@ -275,4 +314,5 @@ otherError = OtherError('Unspecified SNMP engine error occurred')
class OidNotIncreasing(ErrorIndication):
pass
+
oidNotIncreasing = OidNotIncreasing('OID not increasing')
diff --git a/pysnmp/proto/error.py b/pysnmp/proto/error.py
index 14e6b737..6d10b0c1 100644
--- a/pysnmp/proto/error.py
+++ b/pysnmp/proto/error.py
@@ -23,7 +23,7 @@ class StatusInformation(SnmpV3Error):
def __init__(self, **kwargs):
SnmpV3Error.__init__(self)
self.__errorIndication = kwargs
- debug.logger & (debug.flagDsp | debug.flagMP | debug.flagSM | debug.flagACL) and debug.logger(
+ debug.logger & (debug.FLAG_DSP | debug.FLAG_MP | debug.FLAG_SM | debug.FLAG_ACL) and debug.logger(
'StatusInformation: %s' % kwargs)
def __str__(self):
diff --git a/pysnmp/proto/mpmod/base.py b/pysnmp/proto/mpmod/base.py
index 620ccf89..0a9f9f6a 100644
--- a/pysnmp/proto/mpmod/base.py
+++ b/pysnmp/proto/mpmod/base.py
@@ -9,10 +9,10 @@ from pysnmp.proto import error
class AbstractMessageProcessingModel(object):
- snmpMsgSpec = NotImplementedError
+ SNMP_MSG_SPEC = NotImplementedError
def __init__(self):
- self._snmpMsgSpec = self.snmpMsgSpec() # local copy
+ self._snmpMsgSpec = self.SNMP_MSG_SPEC() # local copy
self._cache = cache.Cache()
def prepareOutgoingMessage(self, snmpEngine, transportDomain,
diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py
index 9c050430..3872ce9a 100644
--- a/pysnmp/proto/mpmod/rfc2576.py
+++ b/pysnmp/proto/mpmod/rfc2576.py
@@ -20,8 +20,8 @@ from pysnmp import debug
# references here goes to RFC3412.
class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
- messageProcessingModelID = univ.Integer(0) # SNMPv1
- snmpMsgSpec = v1.Message
+ MESSAGE_PROCESSING_MODEL_ID = univ.Integer(0) # SNMPv1
+ SNMP_MSG_SPEC = v1.Message
# rfc3412: 7.1
def prepareOutgoingMessage(self, snmpEngine, transportDomain,
@@ -35,11 +35,11 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
snmpEngineId = snmpEngineId.syntax
# rfc3412: 7.1.1b
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# serve unique PDU request-id
msgID = self._cache.newMsgID()
reqID = pdu.getComponentByPosition(0)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: PDU request-id %s replaced with unique ID %s' % (reqID, msgID))
# rfc3412: 7.1.4
@@ -52,14 +52,14 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
if not contextName:
contextName = null
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName))
# rfc3412: 7.1.6
scopedPDU = (contextEngineId, contextName, pdu)
msg = self._snmpMsgSpec
- msg.setComponentByPosition(0, self.messageProcessingModelID)
+ msg.setComponentByPosition(0, self.MESSAGE_PROCESSING_MODEL_ID)
msg.setComponentByPosition(2)
msg.getComponentByPosition(2).setComponentByType(
pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False
@@ -82,25 +82,25 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
'snmpEngineMaxMessageSize')
# fix unique request-id right prior PDU serialization
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# noinspection PyUnboundLocalVariable
pdu.setComponentByPosition(0, msgID)
# rfc3412: 7.1.9.b
(securityParameters,
wholeMsg) = smHandler.generateRequestMsg(
- snmpEngine, self.messageProcessingModelID, globalData,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, globalData,
snmpEngineMaxMessageSize.syntax, securityModel,
snmpEngineId, securityName, securityLevel, scopedPDU
)
# return original request-id right after PDU serialization
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# noinspection PyUnboundLocalVariable
pdu.setComponentByPosition(0, reqID)
# rfc3412: 7.1.9.c
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# XXX rfc bug? why stateReference should be created?
self._cache.pushByMsgId(int(msgID), sendPduHandle=sendPduHandle,
reqID=reqID, snmpEngineId=snmpEngineId,
@@ -161,7 +161,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
transportDomain = cachedParams['transportDomain']
transportAddress = cachedParams['transportAddress']
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % (
msgID, transportDomain, transportAddress, stateReference))
@@ -185,7 +185,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.6
scopedPDU = (contextEngineId, contextName, pdu)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName))
msg = self._snmpMsgSpec
@@ -213,7 +213,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.8.a
(securityParameters, wholeMsg) = smHandler.generateResponseMsg(
- snmpEngine, self.messageProcessingModelID, globalData,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, globalData,
maxMessageSize, securityModel, snmpEngineId, securityName,
securityLevel, scopedPDU, securityStateReference
)
@@ -249,7 +249,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.2
msg, restOfWholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
if eoo.endOfOctets.isSameTypeWith(msg):
raise error.StatusInformation(errorIndication=errind.parseError)
@@ -289,7 +289,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
securityModel, securityLevel, wholeMsg, msg
)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: SM returned securityEngineId %r securityName %r' % (securityEngineId, securityName))
except error.StatusInformation as exc:
@@ -322,7 +322,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.8, 7.2.9 -> no-op
# rfc3412: 7.2.10
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# get unique PDU request-id
msgID = pdu.getComponentByPosition(0)
@@ -336,7 +336,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# recover original PDU request-id to return to app
pdu.setComponentByPosition(0, cachedReqParams['reqID'])
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: unique PDU request-id %s replaced with original ID %s' % (
msgID, cachedReqParams['reqID']))
@@ -351,7 +351,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.2.11 -> no-op
# rfc3412: 7.2.12
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# rfc3412: 7.2.12a -> no-op
# rfc3412: 7.2.12b
# noinspection PyUnboundLocalVariable
@@ -393,12 +393,12 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# rfc3412: 7.2.13
- if pduType in rfc3411.confirmedClassPDUs:
+ if pduType in rfc3411.CONFIRMED_CLASS_PDUS:
# store original PDU request-id and replace it with a unique one
reqID = pdu.getComponentByPosition(0)
msgID = self._cache.newMsgID()
pdu.setComponentByPosition(0, msgID)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: received PDU request-id %s replaced with unique ID %s' % (reqID, msgID))
# rfc3412: 7.2.13a
@@ -440,7 +440,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
snmpEngine, 'rfc2576.prepareDataElements:confirmed'
)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: cached by new stateReference %s' % stateReference)
# rfc3412: 7.2.13c
@@ -451,7 +451,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# rfc3412: 7.2.14
- if pduType in rfc3411.unconfirmedClassPDUs:
+ if pduType in rfc3411.UNCONFIRMED_CLASS_PDUS:
# Pass new stateReference to let app browse request details
stateReference = self._cache.newStateReference()
@@ -486,5 +486,5 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
class SnmpV2cMessageProcessingModel(SnmpV1MessageProcessingModel):
- messageProcessingModelID = univ.Integer(1) # SNMPv2c
- snmpMsgSpec = v2c.Message
+ MESSAGE_PROCESSING_MODEL_ID = univ.Integer(1) # SNMPv2c
+ SNMP_MSG_SPEC = v2c.Message
diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py
index bda72cd9..fe736cac 100644
--- a/pysnmp/proto/mpmod/rfc3412.py
+++ b/pysnmp/proto/mpmod/rfc3412.py
@@ -13,7 +13,7 @@ from pyasn1.error import PyAsn1Error
from pysnmp import debug
# API to rfc1905 protocol objects
-pMod = api.protoModules[api.protoVersion2c]
+pMod = api.PROTOCOL_MODULES[api.SNMP_VERSION_2C]
# SNMPv3 message format
@@ -68,8 +68,9 @@ _snmpErrors = {(1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0): errind.unsupportedSecurityLev
class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
- messageProcessingModelID = univ.Integer(3) # SNMPv3
- snmpMsgSpec = SNMPv3Message
+ MESSAGE_PROCESSING_MODEL_ID = univ.Integer(3) # SNMPv3
+ SNMP_MSG_SPEC = SNMPv3Message
+
_emptyStr = univ.OctetString('')
_msgFlags = {0: univ.OctetString('\x00'),
1: univ.OctetString('\x01'),
@@ -107,7 +108,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.1b
msgID = self._cache.newMsgID()
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID)
+ debug.logger & debug.FLAG_MP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID)
k = (transportDomain, transportAddress)
if k in self.__engineIdCache:
@@ -115,7 +116,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
peerSnmpEngineData = None
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % (
peerSnmpEngineData, transportDomain, transportAddress))
@@ -134,7 +135,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
if not contextName:
contextName = self._emptyStr
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareOutgoingMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName))
# 7.1.6
@@ -151,7 +152,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.7a
msg.setComponentByPosition(
- 0, self.messageProcessingModelID, verifyConstraints=False, matchTags=False, matchConstraints=False
+ 0, self.MESSAGE_PROCESSING_MODEL_ID, verifyConstraints=False, matchTags=False, matchConstraints=False
)
headerData = msg.setComponentByPosition(1).getComponentByPosition(1)
@@ -180,7 +181,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
'Unknown securityLevel %s' % securityLevel
)
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
msgFlags |= 0x04
headerData.setComponentByPosition(
@@ -191,7 +192,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# XXX need to coerce MIB value as it has incompatible constraints set
headerData.setComponentByPosition(3, int(securityModel))
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),))
if securityModel in snmpEngine.securityModels:
smHandler = snmpEngine.securityModels[securityModel]
@@ -201,7 +202,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
)
# 7.1.9.a
- if pdu.tagSet in rfc3411.unconfirmedClassPDUs:
+ if pdu.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS:
securityEngineId = snmpEngineID
else:
if peerSnmpEngineData is None:
@@ -227,18 +228,18 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
scopedPDU.getComponentByPosition(2).setComponentByType(
emptyPdu.tagSet, emptyPdu, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: force engineID discovery')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareOutgoingMessage: force engineID discovery')
else:
securityEngineId = peerSnmpEngineData['securityEngineId']
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP 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,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, msg,
snmpEngineMaxMessageSize.syntax, securityModel,
securityEngineId, securityName, securityLevel, scopedPDU
)
@@ -248,7 +249,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
raise error.StatusInformation(errorIndication=errind.tooBig)
# 7.1.9.c
- if pdu.tagSet in rfc3411.confirmedClassPDUs:
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS:
# XXX rfc bug? why stateReference should be created?
self._cache.pushByMsgId(msgID, sendPduHandle=sendPduHandle,
msgID=msgID, snmpEngineID=snmpEngineID,
@@ -300,7 +301,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
transportDomain = cachedParams['transportDomain']
transportAddress = cachedParams['transportAddress']
- debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % stateReference)
+ debug.logger & debug.FLAG_MP and debug.logger('prepareResponseMessage: stateReference %s' % stateReference)
# 7.1.3
if statusInformation is not None and 'oid' in statusInformation:
@@ -314,7 +315,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.3b
if (pdu is None and not reportableFlag or
pduType is not None and
- pduType not in rfc3411.confirmedClassPDUs):
+ pduType not in rfc3411.CONFIRMED_CLASS_PDUS):
raise error.StatusInformation(
errorIndication=errind.loopTerminated
)
@@ -351,7 +352,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.3e
pdu = reportPDU
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation)
# 7.1.4
if not contextEngineId:
@@ -361,7 +362,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
if not contextName:
contextName = self._emptyStr
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName))
# 7.1.6
@@ -378,7 +379,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.7a
msg.setComponentByPosition(
- 0, self.messageProcessingModelID, verifyConstraints=False, matchTags=False, matchConstraints=False
+ 0, self.MESSAGE_PROCESSING_MODEL_ID, verifyConstraints=False, matchTags=False, matchConstraints=False
)
headerData = msg.setComponentByPosition(1).getComponentByPosition(1)
@@ -406,7 +407,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
raise error.ProtocolError('Unknown securityLevel %s' % securityLevel)
- if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed?
+ if pdu.tagSet in rfc3411.CONFIRMED_CLASS_PDUS: # XXX not needed?
msgFlags |= 0x04
headerData.setComponentByPosition(
@@ -418,14 +419,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
3, securityModel, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),))
if securityModel in snmpEngine.securityModels:
smHandler = snmpEngine.securityModels[securityModel]
else:
raise error.StatusInformation(errorIndication=errind.unsupportedSecurityModel)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareResponseMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % (
securityModel, snmpEngineID, securityName, securityLevel))
@@ -433,7 +434,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
try:
(securityParameters,
wholeMsg) = smHandler.generateResponseMsg(
- snmpEngine, self.messageProcessingModelID, msg,
+ snmpEngine, self.MESSAGE_PROCESSING_MODEL_ID, msg,
snmpEngineMaxMessageSize.syntax, securityModel,
snmpEngineID, securityName, securityLevel, scopedPDU,
securityStateReference
@@ -442,7 +443,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.1.8.b
raise
- debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: SM finished')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareResponseMessage: SM finished')
# Message size constraint verification
if len(wholeMsg) > min(snmpEngineMaxMessageSize.syntax, maxMessageSize):
@@ -474,7 +475,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
# 7.2.2
msg, restOfwholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),))
if eoo.endOfOctets.isSameTypeWith(msg):
raise error.StatusInformation(errorIndication=errind.parseError)
@@ -488,7 +489,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
securityModel = headerData.getComponentByPosition(3)
securityParameters = msg.getComponentByPosition(2)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (
msgVersion, msgID, securityModel))
@@ -528,12 +529,12 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
securityParameters, securityModel, securityLevel,
wholeMsg, msg
)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: SM succeeded')
except error.StatusInformation as exc:
statusInformation = exc
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: SM failed, statusInformation %s' % statusInformation)
snmpEngine.observer.storeExecutionContext(
@@ -590,7 +591,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
except error.StatusInformation:
pass
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: error reported')
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: error reported')
# 7.2.6b
if sys.version_info[0] <= 2:
@@ -615,7 +616,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
pdu = pdus.getComponent()
# Here we assume that authentic/default EngineIDs
# come only in the course of engine-to-engine communication.
- if pdu.tagSet in rfc3411.internalClassPDUs:
+ if pdu.tagSet in rfc3411.INTERNAL_CLASS_PDUS:
self.__engineIdCache[k] = {
'securityEngineId': securityEngineId,
'contextEngineId': contextEngineId,
@@ -627,7 +628,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
self.__engineIdCacheExpQueue[expireAt] = []
self.__engineIdCacheExpQueue[expireAt].append(k)
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: cache securityEngineId %r for %r %r' % (
securityEngineId, transportDomain, transportAddress))
@@ -642,14 +643,14 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
pdu = pdu.getComponent() # PDUs
# 7.2.8
- pduVersion = api.protoVersion2c
+ pduVersion = api.SNMP_VERSION_2C
# 7.2.9
pduType = pdu.tagSet
# 7.2.10
- if (pduType in rfc3411.responseClassPDUs or
- pduType in rfc3411.internalClassPDUs):
+ if (pduType in rfc3411.RESPONSE_CLASS_PDUS or
+ pduType in rfc3411.INTERNAL_CLASS_PDUS):
# 7.2.10a
try:
cachedReqParams = self._cache.popByMsgId(msgID)
@@ -663,11 +664,11 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
sendPduHandle = None
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID))
# 7.2.11
- if pduType in rfc3411.internalClassPDUs:
+ if pduType in rfc3411.INTERNAL_CLASS_PDUS:
# 7.2.11a
varBinds = pMod.apiPDU.getVarBinds(pdu)
if varBinds:
@@ -711,7 +712,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
statusInformation = None # no errors ahead
# 7.2.12
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# 7.2.12a -> no-op
# 7.2.12b
@@ -754,7 +755,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# 7.2.13
- if pduType in rfc3411.confirmedClassPDUs:
+ if pduType in rfc3411.CONFIRMED_CLASS_PDUS:
# 7.2.13a
if securityEngineId != snmpEngineID:
smHandler.releaseStateInformation(securityStateReference)
@@ -776,7 +777,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
transportAddress=transportAddress
)
- debug.logger & debug.flagMP and debug.logger('prepareDataElements: new stateReference %s' % stateReference)
+ debug.logger & debug.FLAG_MP and debug.logger('prepareDataElements: new stateReference %s' % stateReference)
snmpEngine.observer.storeExecutionContext(
snmpEngine, 'rfc3412.prepareDataElements:confirmed',
@@ -802,7 +803,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
stateReference)
# 7.2.14
- if pduType in rfc3411.unconfirmedClassPDUs:
+ if pduType in rfc3411.UNCONFIRMED_CLASS_PDUS:
# Pass new stateReference to let app browse request details
stateReference = self._cache.newStateReference()
@@ -840,7 +841,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
if self.__expirationTimer in self.__engineIdCacheExpQueue:
for engineKey in self.__engineIdCacheExpQueue[self.__expirationTimer]:
del self.__engineIdCache[engineKey]
- debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %r' % (engineKey,))
+ debug.logger & debug.FLAG_MP and debug.logger('__expireEnginesInfo: expiring %r' % (engineKey,))
del self.__engineIdCacheExpQueue[self.__expirationTimer]
self.__expirationTimer += 1
diff --git a/pysnmp/proto/proxy/rfc2576.py b/pysnmp/proto/proxy/rfc2576.py
index 6b1dfcbb..4391a54f 100644
--- a/pysnmp/proto/proxy/rfc2576.py
+++ b/pysnmp/proto/proxy/rfc2576.py
@@ -10,7 +10,7 @@ from pysnmp import debug
# 2.1.1
-__v1ToV2ValueMap = {
+V1_TO_V2_VALUE_MAP = {
v1.Integer.tagSet: v2c.Integer32(),
v1.OctetString.tagSet: v2c.OctetString(),
v1.Null.tagSet: v2c.Null(),
@@ -22,7 +22,7 @@ __v1ToV2ValueMap = {
v1.Opaque.tagSet: v2c.Opaque()
}
-__v2ToV1ValueMap = { # XXX do not re-create same-type items?
+V2_TO_V1_VALUE_MAP = { # XXX do not re-create same-type items?
v2c.Integer32.tagSet: v1.Integer(),
v2c.OctetString.tagSet: v1.OctetString(),
v2c.Null.tagSet: v1.Null(),
@@ -36,7 +36,7 @@ __v2ToV1ValueMap = { # XXX do not re-create same-type items?
# PDU map
-__v1ToV2PduMap = {
+V1_TO_V2_PDU_MAP = {
v1.GetRequestPDU.tagSet: v2c.GetRequestPDU(),
v1.GetNextRequestPDU.tagSet: v2c.GetNextRequestPDU(),
v1.SetRequestPDU.tagSet: v2c.SetRequestPDU(),
@@ -44,7 +44,7 @@ __v1ToV2PduMap = {
v1.TrapPDU.tagSet: v2c.SNMPv2TrapPDU()
}
-__v2ToV1PduMap = {
+V2_TO_V1_PDU_MAP = {
v2c.GetRequestPDU.tagSet: v1.GetRequestPDU(),
v2c.GetNextRequestPDU.tagSet: v1.GetNextRequestPDU(),
v2c.SetRequestPDU.tagSet: v1.SetRequestPDU(),
@@ -55,7 +55,7 @@ __v2ToV1PduMap = {
# Trap map
-__v1ToV2TrapMap = {
+V1_TO_V2_TRAP_MAP = {
0: (1, 3, 6, 1, 6, 3, 1, 1, 5, 1),
1: (1, 3, 6, 1, 6, 3, 1, 1, 5, 2),
2: (1, 3, 6, 1, 6, 3, 1, 1, 5, 3),
@@ -64,7 +64,7 @@ __v1ToV2TrapMap = {
5: (1, 3, 6, 1, 6, 3, 1, 1, 5, 6)
}
-__v2ToV1TrapMap = {
+V2_TO_V1_TRAP_MAP = {
(1, 3, 6, 1, 6, 3, 1, 1, 5, 1): 0,
(1, 3, 6, 1, 6, 3, 1, 1, 5, 2): 1,
(1, 3, 6, 1, 6, 3, 1, 1, 5, 3): 2,
@@ -75,7 +75,7 @@ __v2ToV1TrapMap = {
# 4.3
-__v2ToV1ErrorMap = {
+V2_TO_V1_ERROR_MAP = {
0: 0,
1: 1,
5: 5,
@@ -94,19 +94,17 @@ __v2ToV1ErrorMap = {
16: 2
}
-__zeroInt = v1.Integer(0)
-
def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
pduType = v1Pdu.tagSet
- v2Pdu = __v1ToV2PduMap[pduType].clone()
+ v2Pdu = V1_TO_V2_PDU_MAP[pduType].clone()
- debug.logger & debug.flagPrx and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint())
v2VarBinds = []
# 3.1
- if pduType in rfc3411.notificationClassPDUs:
+ if pduType in rfc3411.NOTIFICATION_CLASS_PDUS:
# 3.1.1
sysUpTime = v1.apiTrapPDU.getTimeStamp(v1Pdu)
@@ -117,7 +115,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
# 3.1.3
else:
- snmpTrapOIDParam = v2c.ObjectIdentifier(__v1ToV2TrapMap[genericTrap])
+ snmpTrapOIDParam = v2c.ObjectIdentifier(V1_TO_V2_TRAP_MAP[genericTrap])
# 3.1.4
v2VarBinds.append((v2c.apiTrapPDU.sysUpTime, sysUpTime))
@@ -139,10 +137,10 @@ def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
if v1Val.tagSet == v1.NetworkAddress.tagSet:
v1Val = v1Val.getComponent()
v2VarBinds.append(
- (oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val))
+ (oid, V1_TO_V2_VALUE_MAP[v1Val.tagSet].clone(v1Val))
)
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
# 4.1.2.2.1&2
errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu))
errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu, muteErrors=True))
@@ -158,41 +156,43 @@ def v1ToV2(v1Pdu, origV2Pdu=None, snmpTrapCommunity=''):
# 4.1.2.1 --> no-op
- elif pduType in rfc3411.confirmedClassPDUs:
+ elif pduType in rfc3411.CONFIRMED_CLASS_PDUS:
v2c.apiPDU.setErrorStatus(v2Pdu, 0)
v2c.apiPDU.setErrorIndex(v2Pdu, 0)
- if pduType not in rfc3411.notificationClassPDUs:
+ if pduType not in rfc3411.NOTIFICATION_CLASS_PDUS:
v2c.apiPDU.setRequestID(v2Pdu, int(v1.apiPDU.getRequestID(v1Pdu)))
v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds)
- debug.logger & debug.flagPrx and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint())
return v2Pdu
def v2ToV1(v2Pdu, origV1Pdu=None):
- debug.logger & debug.flagPrx and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint())
pduType = v2Pdu.tagSet
- if pduType in __v2ToV1PduMap:
- v1Pdu = __v2ToV1PduMap[pduType].clone()
+ if pduType in V2_TO_V1_PDU_MAP:
+ v1Pdu = V2_TO_V1_PDU_MAP[pduType].clone()
else:
raise error.ProtocolError('Unsupported PDU type')
v2VarBinds = v2c.apiPDU.getVarBinds(v2Pdu)
v1VarBinds = []
+ zeroInt = v1.Integer(0)
+
# 3.2
- if pduType in rfc3411.notificationClassPDUs:
+ if pduType in rfc3411.NOTIFICATION_CLASS_PDUS:
# 3.2.1
snmpTrapOID, snmpTrapOIDParam = v2VarBinds[1]
if snmpTrapOID != v2c.apiTrapPDU.snmpTrapOID:
raise error.ProtocolError('Second OID not snmpTrapOID')
snmpTrapOID, snmpTrapOIDParam = v2VarBinds[1]
- if snmpTrapOIDParam in __v2ToV1TrapMap:
+ if snmpTrapOIDParam in V2_TO_V1_TRAP_MAP:
for oid, val in v2VarBinds:
if oid == v2c.apiTrapPDU.snmpTrapEnterprise:
v1.apiTrapPDU.setEnterprise(v1Pdu, val)
@@ -216,14 +216,14 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v1.apiTrapPDU.setAgentAddr(v1Pdu, v1.IpAddress('0.0.0.0'))
# 3.2.3
- if snmpTrapOIDParam in __v2ToV1TrapMap:
- v1.apiTrapPDU.setGenericTrap(v1Pdu, __v2ToV1TrapMap[snmpTrapOIDParam])
+ if snmpTrapOIDParam in V2_TO_V1_TRAP_MAP:
+ v1.apiTrapPDU.setGenericTrap(v1Pdu, V2_TO_V1_TRAP_MAP[snmpTrapOIDParam])
else:
v1.apiTrapPDU.setGenericTrap(v1Pdu, 6)
# 3.2.4
- if snmpTrapOIDParam in __v2ToV1TrapMap:
- v1.apiTrapPDU.setSpecificTrap(v1Pdu, __zeroInt)
+ if snmpTrapOIDParam in V2_TO_V1_TRAP_MAP:
+ v1.apiTrapPDU.setSpecificTrap(v1Pdu, zeroInt)
else:
v1.apiTrapPDU.setSpecificTrap(v1Pdu, snmpTrapOIDParam[-1])
@@ -232,7 +232,7 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
__v2VarBinds = []
for oid, val in v2VarBinds[2:]:
- if oid in __v2ToV1TrapMap or \
+ if oid in V2_TO_V1_TRAP_MAP or \
oid in (v2c.apiTrapPDU.sysUpTime,
v2c.apiTrapPDU.snmpTrapAddress,
v2c.apiTrapPDU.snmpTrapEnterprise):
@@ -243,10 +243,10 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
# 3.2.6 --> done below
else:
- v1.apiPDU.setErrorStatus(v1Pdu, __zeroInt)
- v1.apiPDU.setErrorIndex(v1Pdu, __zeroInt)
+ v1.apiPDU.setErrorStatus(v1Pdu, zeroInt)
+ v1.apiPDU.setErrorIndex(v1Pdu, zeroInt)
- if pduType in rfc3411.responseClassPDUs:
+ if pduType in rfc3411.RESPONSE_CLASS_PDUS:
idx = len(v2VarBinds) - 1
while idx >= 0:
# 4.1.2.1
@@ -274,25 +274,25 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu)
if v2ErrorStatus:
v1.apiPDU.setErrorStatus(
- v1Pdu, __v2ToV1ErrorMap.get(v2ErrorStatus, 5)
+ v1Pdu, V2_TO_V1_ERROR_MAP.get(v2ErrorStatus, 5)
)
v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu, muteErrors=True))
- elif pduType in rfc3411.confirmedClassPDUs:
+ elif pduType in rfc3411.CONFIRMED_CLASS_PDUS:
v1.apiPDU.setErrorStatus(v1Pdu, 0)
v1.apiPDU.setErrorIndex(v1Pdu, 0)
# Translate Var-Binds
- if (pduType in rfc3411.responseClassPDUs and
+ if (pduType in rfc3411.RESPONSE_CLASS_PDUS and
v1.apiPDU.getErrorStatus(v1Pdu)):
v1VarBinds = v1.apiPDU.getVarBinds(origV1Pdu)
else:
for oid, v2Val in v2VarBinds:
v1VarBinds.append(
- (oid, __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val))
+ (oid, V2_TO_V1_VALUE_MAP[v2Val.tagSet].clone(v2Val))
)
- if pduType in rfc3411.notificationClassPDUs:
+ if pduType in rfc3411.NOTIFICATION_CLASS_PDUS:
v1.apiTrapPDU.setVarBinds(v1Pdu, v1VarBinds)
else:
v1.apiPDU.setVarBinds(v1Pdu, v1VarBinds)
@@ -301,6 +301,6 @@ def v2ToV1(v2Pdu, origV1Pdu=None):
v1Pdu, v2c.apiPDU.getRequestID(v2Pdu)
)
- debug.logger & debug.flagPrx and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint())
+ debug.logger & debug.FLAG_PRX and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint())
return v1Pdu
diff --git a/pysnmp/proto/rfc1155.py b/pysnmp/proto/rfc1155.py
index 8fb48e8c..b9a2eb25 100644
--- a/pysnmp/proto/rfc1155.py
+++ b/pysnmp/proto/rfc1155.py
@@ -105,7 +105,6 @@ class NetworkAddress(univ.Choice):
raise SmiError('unknown NetworkAddress type %r' % (kind,))
-
class Gauge(univ.Integer):
tagSet = univ.Integer.tagSet.tagImplicitly(
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02)
diff --git a/pysnmp/proto/rfc3411.py b/pysnmp/proto/rfc3411.py
index bd4d40d3..3c0fd645 100644
--- a/pysnmp/proto/rfc3411.py
+++ b/pysnmp/proto/rfc3411.py
@@ -6,50 +6,50 @@
#
from pysnmp.proto import rfc1157, rfc1905
-readClassPDUs = {
- rfc1157.GetRequestPDU.tagSet: 1,
- rfc1157.GetNextRequestPDU.tagSet: 1,
- rfc1905.GetRequestPDU.tagSet: 1,
- rfc1905.GetNextRequestPDU.tagSet: 1,
- rfc1905.GetBulkRequestPDU.tagSet: 1
+READ_CLASS_PDUS = {
+ rfc1157.GetRequestPDU.tagSet,
+ rfc1157.GetNextRequestPDU.tagSet,
+ rfc1905.GetRequestPDU.tagSet,
+ rfc1905.GetNextRequestPDU.tagSet,
+ rfc1905.GetBulkRequestPDU.tagSet
}
-writeClassPDUs = {
- rfc1157.SetRequestPDU.tagSet: 1,
- rfc1905.SetRequestPDU.tagSet: 1
+WRITE_CLASS_PDUS = {
+ rfc1157.SetRequestPDU.tagSet,
+ rfc1905.SetRequestPDU.tagSet
}
-responseClassPDUs = {
- rfc1157.GetResponsePDU.tagSet: 1,
- rfc1905.ResponsePDU.tagSet: 1,
- rfc1905.ReportPDU.tagSet: 1
+RESPONSE_CLASS_PDUS = {
+ rfc1157.GetResponsePDU.tagSet,
+ rfc1905.ResponsePDU.tagSet,
+ rfc1905.ReportPDU.tagSet
}
-notificationClassPDUs = {
- rfc1157.TrapPDU.tagSet: 1,
- rfc1905.SNMPv2TrapPDU.tagSet: 1,
- rfc1905.InformRequestPDU.tagSet: 1
+NOTIFICATION_CLASS_PDUS = {
+ rfc1157.TrapPDU.tagSet,
+ rfc1905.SNMPv2TrapPDU.tagSet,
+ rfc1905.InformRequestPDU.tagSet
}
-internalClassPDUs = {
- rfc1905.ReportPDU.tagSet: 1
+INTERNAL_CLASS_PDUS = {
+ rfc1905.ReportPDU.tagSet
}
-confirmedClassPDUs = {
- rfc1157.GetRequestPDU.tagSet: 1,
- rfc1157.GetNextRequestPDU.tagSet: 1,
- rfc1157.SetRequestPDU.tagSet: 1,
- rfc1905.GetRequestPDU.tagSet: 1,
- rfc1905.GetNextRequestPDU.tagSet: 1,
- rfc1905.GetBulkRequestPDU.tagSet: 1,
- rfc1905.SetRequestPDU.tagSet: 1,
- rfc1905.InformRequestPDU.tagSet: 1
+CONFIRMED_CLASS_PDUS = {
+ rfc1157.GetRequestPDU.tagSet,
+ rfc1157.GetNextRequestPDU.tagSet,
+ rfc1157.SetRequestPDU.tagSet,
+ rfc1905.GetRequestPDU.tagSet,
+ rfc1905.GetNextRequestPDU.tagSet,
+ rfc1905.GetBulkRequestPDU.tagSet,
+ rfc1905.SetRequestPDU.tagSet,
+ rfc1905.InformRequestPDU.tagSet
}
-unconfirmedClassPDUs = {
- rfc1157.GetResponsePDU.tagSet: 1,
- rfc1905.ResponsePDU.tagSet: 1,
- rfc1157.TrapPDU.tagSet: 1,
- rfc1905.ReportPDU.tagSet: 1,
- rfc1905.SNMPv2TrapPDU.tagSet: 1
+UNCONFIRMED_CLASS_PDUS = {
+ rfc1157.GetResponsePDU.tagSet,
+ rfc1905.ResponsePDU.tagSet,
+ rfc1157.TrapPDU.tagSet,
+ rfc1905.ReportPDU.tagSet,
+ rfc1905.SNMPv2TrapPDU.tagSet
}
diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py
index 11194984..aaef10d9 100644
--- a/pysnmp/proto/rfc3412.py
+++ b/pysnmp/proto/rfc3412.py
@@ -71,7 +71,7 @@ class MsgAndPduDispatcher(object):
# 4.3.4
self.__appsRegistration[k] = processPdu
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'registerContextEngineId: contextEngineId %r pduTypes %s' % (contextEngineId, pduTypes))
# 4.4.1
@@ -88,7 +88,7 @@ class MsgAndPduDispatcher(object):
if k in self.__appsRegistration:
del self.__appsRegistration[k]
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'unregisterContextEngineId: contextEngineId %r pduTypes %s' % (contextEngineId, pduTypes))
def getRegisteredApp(self, contextEngineId, pduType):
@@ -118,7 +118,7 @@ class MsgAndPduDispatcher(object):
errorIndication=errind.unsupportedMsgProcessingModel
)
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'sendPdu: securityName %s, PDU\n%s' % (securityName, PDU.prettyPrint()))
# 4.1.1.3
@@ -133,10 +133,10 @@ class MsgAndPduDispatcher(object):
cbCtx=cbCtx
)
- debug.logger & debug.flagDsp and debug.logger('sendPdu: current time %d ticks, one tick is %s seconds' % (
+ debug.logger & debug.FLAG_DSP and debug.logger('sendPdu: current time %d ticks, one tick is %s seconds' % (
snmpEngine.transportDispatcher.getTimerTicks(), snmpEngine.transportDispatcher.getTimerResolution()))
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'sendPdu: new sendPduHandle %s, timeout %s ticks, cbFun %s' % (sendPduHandle, timeout, cbFun))
origTransportDomain = transportDomain
@@ -153,7 +153,7 @@ class MsgAndPduDispatcher(object):
pduVersion, PDU, expectResponse, sendPduHandle
)
- debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('sendPdu: MP succeeded')
except PySnmpError:
if expectResponse:
self.__cache.pop(sendPduHandle)
@@ -222,7 +222,7 @@ class MsgAndPduDispatcher(object):
errorIndication=errind.unsupportedMsgProcessingModel
)
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'returnResponsePdu: PDU %s' % (PDU and PDU.prettyPrint() or "<empty>",))
# 4.1.2.2
@@ -236,7 +236,7 @@ class MsgAndPduDispatcher(object):
statusInformation
)
- debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('returnResponsePdu: MP suceeded')
except error.StatusInformation:
# 4.1.2.3
@@ -296,7 +296,7 @@ class MsgAndPduDispatcher(object):
snmpInASNParseErrs.syntax += 1
return null # n.b the whole buffer gets dropped
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion)
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion)
messageProcessingModel = msgVersion
@@ -328,14 +328,14 @@ class MsgAndPduDispatcher(object):
snmpEngine, transportDomain, transportAddress, wholeMsg
)
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: MP succeded')
except error.StatusInformation as exc:
statusInformation = exc
if 'sendPduHandle' in statusInformation:
# Dropped REPORT -- re-run pending reqs queue as some
# of them may be waiting for this REPORT
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'receiveMessage: MP failed, statusInformation %s, forcing a retry' % statusInformation)
self.__expireRequest(
statusInformation['sendPduHandle'],
@@ -346,19 +346,19 @@ class MsgAndPduDispatcher(object):
return restOfWholeMsg
except PyAsn1Error as exc:
- debug.logger & debug.flagMP and debug.logger('receiveMessage: %s' % exc)
+ debug.logger & debug.FLAG_MP and debug.logger('receiveMessage: %s' % exc)
snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs')
snmpInASNParseErrs.syntax += 1
return restOfWholeMsg
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint())
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint())
# 4.2.2
if sendPduHandle is None:
# 4.2.2.1 (request or notification)
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: pduType %s' % pduType)
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: pduType %s' % pduType)
# 4.2.2.1.1
processPdu = self.getRegisteredApp(contextEngineId, pduType)
@@ -376,7 +376,7 @@ class MsgAndPduDispatcher(object):
'val': snmpUnknownPDUHandlers.syntax
}
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: unhandled PDU type')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: unhandled PDU type')
# 4.2.2.1.2.c
try:
@@ -396,11 +396,11 @@ class MsgAndPduDispatcher(object):
)
except PySnmpError as exc:
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'receiveMessage: report failed, statusInformation %s' % exc)
else:
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: reporting succeeded')
# 4.2.2.1.2.d
return restOfWholeMsg
@@ -440,7 +440,7 @@ class MsgAndPduDispatcher(object):
if stateReference is not None:
del self.__transportInfo[stateReference]
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: processPdu initiated')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: processPdu initiated')
return restOfWholeMsg
else:
# 4.2.2.2 (response)
@@ -455,7 +455,7 @@ class MsgAndPduDispatcher(object):
snmpUnknownPDUHandlers.syntax += 1
return restOfWholeMsg
- debug.logger & debug.flagDsp and debug.logger(
+ debug.logger & debug.FLAG_DSP and debug.logger(
'receiveMessage: cache read by sendPduHandle %s' % sendPduHandle)
# 4.2.2.2.3
@@ -489,7 +489,7 @@ class MsgAndPduDispatcher(object):
snmpEngine, 'rfc3412.receiveMessage:response'
)
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: processResponsePdu succeeded')
+ debug.logger & debug.FLAG_DSP and debug.logger('receiveMessage: processResponsePdu succeeded')
return restOfWholeMsg
@@ -515,7 +515,7 @@ class MsgAndPduDispatcher(object):
processResponsePdu = cachedParams['cbFun']
- debug.logger & debug.flagDsp and debug.logger('__expireRequest: req cachedParams %s' % cachedParams)
+ debug.logger & debug.FLAG_DSP and debug.logger('__expireRequest: req cachedParams %s' % cachedParams)
# Fail timed-out requests
if not statusInformation:
diff --git a/pysnmp/proto/secmod/base.py b/pysnmp/proto/secmod/base.py
index 63df39c7..70850bcf 100644
--- a/pysnmp/proto/secmod/base.py
+++ b/pysnmp/proto/secmod/base.py
@@ -9,7 +9,7 @@ from pysnmp.proto import error
class AbstractSecurityModel(object):
- securityModelID = None
+ SECURITY_MODEL_ID = None
def __init__(self):
self._cache = cache.Cache()
diff --git a/pysnmp/proto/secmod/eso/priv/aes192.py b/pysnmp/proto/secmod/eso/priv/aes192.py
index 399a225b..7df0a0f5 100644
--- a/pysnmp/proto/secmod/eso/priv/aes192.py
+++ b/pysnmp/proto/secmod/eso/priv/aes192.py
@@ -14,8 +14,8 @@ class AesBlumenthal192(aesbase.AbstractAesBlumenthal):
http://tools.ietf.org/html/draft-blumenthal-aes-usm-04
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol
- keySize = 24
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol
+ KEY_SIZE = 24
class Aes192(aesbase.AbstractAesReeder):
@@ -29,5 +29,5 @@ class Aes192(aesbase.AbstractAesReeder):
Known to be used by many vendors including Cisco and others.
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 101) # cusmAESCfb192PrivProtocol (non-standard OID)
- keySize = 24
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 101) # cusmAESCfb192PrivProtocol (non-standard OID)
+ KEY_SIZE = 24
diff --git a/pysnmp/proto/secmod/eso/priv/aes256.py b/pysnmp/proto/secmod/eso/priv/aes256.py
index 360f26c3..94a255ff 100644
--- a/pysnmp/proto/secmod/eso/priv/aes256.py
+++ b/pysnmp/proto/secmod/eso/priv/aes256.py
@@ -12,8 +12,8 @@ class AesBlumenthal256(aesbase.AbstractAesBlumenthal):
http://tools.ietf.org/html/draft-blumenthal-aes-usm-04
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol
- keySize = 32
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol
+ KEY_SIZE = 32
class Aes256(aesbase.AbstractAesReeder):
@@ -27,5 +27,5 @@ class Aes256(aesbase.AbstractAesReeder):
Known to be used by many vendors including Cisco and others.
"""
- serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 102) # cusmAESCfb256PrivProtocol (non-standard OID)
- keySize = 32
+ SERVICE_ID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 102) # cusmAESCfb256PrivProtocol (non-standard OID)
+ KEY_SIZE = 32
diff --git a/pysnmp/proto/secmod/eso/priv/aesbase.py b/pysnmp/proto/secmod/eso/priv/aesbase.py
index 676afbbb..f2527cec 100644
--- a/pysnmp/proto/secmod/eso/priv/aesbase.py
+++ b/pysnmp/proto/secmod/eso/priv/aesbase.py
@@ -13,6 +13,7 @@ from math import ceil
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -22,17 +23,17 @@ except ImportError:
class AbstractAesBlumenthal(aes.Aes):
- serviceID = ()
- keySize = 0
+ SERVICE_ID = ()
+ KEY_SIZE = 0
# 3.1.2.1
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -41,10 +42,10 @@ class AbstractAesBlumenthal(aes.Aes):
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
# now extend this key if too short by repeating steps that includes the hashPassphrase step
- for count in range(1, int(ceil(self.keySize * 1.0 / len(localPrivKey)))):
+ for count in range(1, int(ceil(self.KEY_SIZE * 1.0 / len(localPrivKey)))):
localPrivKey += hashAlgo(localPrivKey).digest()
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
class AbstractAesReeder(aes.Aes):
@@ -62,17 +63,17 @@ class AbstractAesReeder(aes.Aes):
The difference between the two is that the Reeder draft does key extension by repeating
the steps in the password to key algorithm (hash phrase, then localize with SNMPEngine ID).
"""
- serviceID = ()
- keySize = 0
+ SERVICE_ID = ()
+ KEY_SIZE = 0
# 2.1 of https://tools.itef.org/pdf/draft_bluementhal-aes-usm-04.txt
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -81,9 +82,9 @@ class AbstractAesReeder(aes.Aes):
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
# now extend this key if too short by repeating steps that includes the hashPassphrase step
- while len(localPrivKey) < self.keySize:
+ while len(localPrivKey) < self.KEY_SIZE:
# this is the difference between reeder and bluementhal
newKey = localkey.hashPassphrase(localPrivKey, hashAlgo)
localPrivKey += localkey.localizeKey(newKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
diff --git a/pysnmp/proto/secmod/eso/priv/des3.py b/pysnmp/proto/secmod/eso/priv/des3.py
index fa6e20b9..bb3f8516 100644
--- a/pysnmp/proto/secmod/eso/priv/des3.py
+++ b/pysnmp/proto/secmod/eso/priv/des3.py
@@ -5,8 +5,10 @@
# License: http://snmplabs.com/pysnmp/license.html
#
import random
+
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -39,17 +41,18 @@ class Des3(base.AbstractEncryptionService):
https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00
"""
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol
- keySize = 32
- _localInt = random.randrange(0, 0xffffffff)
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol
+ KEY_SIZE = 32
+
+ local_int = random.randrange(0, 0xffffffff)
def hashPassphrase(self, authProtocol, privKey):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -58,12 +61,12 @@ class Des3(base.AbstractEncryptionService):
# 2.1
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -71,12 +74,12 @@ class Des3(base.AbstractEncryptionService):
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
# now extend this key if too short by repeating steps that includes the hashPassphrase step
- while len(localPrivKey) < self.keySize:
+ while len(localPrivKey) < self.KEY_SIZE:
# this is the difference between reeder and bluementhal
newKey = localkey.hashPassphrase(localPrivKey, hashAlgo)
localPrivKey += localkey.localizeKey(newKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
# 5.1.1.1
def __getEncryptionKey(self, privKey, snmpEngineBoots):
@@ -91,15 +94,15 @@ class Des3(base.AbstractEncryptionService):
securityEngineBoots >> 16 & 0xff,
securityEngineBoots >> 8 & 0xff,
securityEngineBoots & 0xff,
- self._localInt >> 24 & 0xff,
- self._localInt >> 16 & 0xff,
- self._localInt >> 8 & 0xff,
- self._localInt & 0xff
+ self.local_int >> 24 & 0xff,
+ self.local_int >> 16 & 0xff,
+ self.local_int >> 8 & 0xff,
+ self.local_int & 0xff
]
- if self._localInt == 0xffffffff:
- self._localInt = 0
+ if self.local_int == 0xffffffff:
+ self.local_int = 0
else:
- self._localInt += 1
+ self.local_int += 1
# salt not yet hashed XXX
diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py
index 4b49b83a..392294f9 100644
--- a/pysnmp/proto/secmod/rfc2576.py
+++ b/pysnmp/proto/secmod/rfc2576.py
@@ -15,7 +15,7 @@ from pysnmp import debug
class SnmpV1SecurityModel(base.AbstractSecurityModel):
- securityModelID = 1
+ SECURITY_MODEL_ID = 1
# According to rfc2576, community name <-> contextEngineId/contextName
# mapping is up to MP module for notifications but belongs to secmod
@@ -56,7 +56,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2com: table entries %r/%r hashing failed' % (
nextMibNode.syntax, mibNode.syntax)
)
@@ -103,7 +103,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
_contextName)] = nextMibNode.syntax
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2com: table entries %r/%r/%r hashing failed' % (
_securityName, _contextEngineId, _contextName)
)
@@ -111,7 +111,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__securityBranchId = snmpCommunityName.branchVersionId
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2com: built securityName to communityName map, version %s: %s' % (
self.__securityBranchId, self.__securityMap))
@@ -154,11 +154,11 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
targetAddrTDomain = tuple(targetAddrTDomain)
- if targetAddrTDomain[:len(udp.snmpUDPDomain)] == udp.snmpUDPDomain:
+ if targetAddrTDomain[:len(udp.SNMP_UDP_DOMAIN)] == udp.SNMP_UDP_DOMAIN:
SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM',
'SnmpUDPAddress')
targetAddrTAddress = tuple(SnmpUDPAddress(targetAddrTAddress))
- elif targetAddrTDomain[:len(udp6.snmpUDP6Domain)] == udp6.snmpUDP6Domain:
+ elif targetAddrTDomain[:len(udp6.SNMP_UDP6_DOMAIN)] == udp6.SNMP_UDP6_DOMAIN:
TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6')
targetAddrTAddress = tuple(TransportAddressIPv6(targetAddrTAddress))
@@ -180,7 +180,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__transportToTagMap[targetAddr].add(self.__emptyTag)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: table entries %r/%r hashing failed' % (
targetAddr, targetAddrTagList)
)
@@ -188,7 +188,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__transportBranchId = snmpTargetAddrTAddress.branchVersionId
- debug.logger & debug.flagSM and debug.logger('_com2sec: built transport-to-tag map version %s: %s' % (
+ debug.logger & debug.FLAG_SM and debug.logger('_com2sec: built transport-to-tag map version %s: %s' % (
self.__transportBranchId, self.__transportToTagMap))
snmpTargetParamsSecurityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
@@ -220,7 +220,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: table entries %r/%r hashing failed' % (
nextMibNode.syntax, mibNode.syntax)
)
@@ -231,7 +231,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
# invalidate next map as it include this one
self.__communityBranchId = -1
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: built securityName to securityModel map, version %s: %s' % (
self.__paramsBranchId, self.__nameToModelMap))
@@ -285,7 +285,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__communityToTagMap[nextMibNode.syntax].add(transportTag)
except PyAsn1Error:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: table entries %r/%r hashing failed' % (
_tagAndCommunity, nextMibNode.syntax)
)
@@ -293,13 +293,13 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
self.__communityBranchId = snmpCommunityName.branchVersionId
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: built communityName to tag map (securityModel %s), version %s: %s' % (
- self.securityModelID, self.__communityBranchId, self.__communityToTagMap))
+ self.SECURITY_MODEL_ID, self.__communityBranchId, self.__communityToTagMap))
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: built tag & community to securityName map (securityModel %s), version %s: %s' % (
- self.securityModelID, self.__communityBranchId, self.__tagAndCommunityToSecurityMap))
+ self.SECURITY_MODEL_ID, self.__communityBranchId, self.__tagAndCommunityToSecurityMap))
if communityName in self.__communityToTagMap:
if transportInformation in self.__transportToTagMap:
@@ -319,11 +319,11 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
# Picks first match but favors entries already in targets table
if candidateSecurityNames:
candidateSecurityNames.sort(
- key=lambda x, m=self.__nameToModelMap, v=self.securityModelID: (
+ key=lambda x, m=self.__nameToModelMap, v=self.SECURITY_MODEL_ID: (
not int(x[0] in m and v in m[x[0]]), str(x[0]))
)
chosenSecurityName = candidateSecurityNames[0] # min()
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_com2sec: securityName candidates for communityName \'%s\' are %s; choosing securityName \'%s\'' % (
communityName, candidateSecurityNames, chosenSecurityName[0]))
return chosenSecurityName
@@ -341,7 +341,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
communityName = self._sec2com(snmpEngine, securityName,
contextEngineId, contextName)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'generateRequestMsg: using community %r for securityModel %r, securityName %r, contextEngineId %r contextName %r' % (
communityName, securityModel, securityName, contextEngineId, contextName))
@@ -353,13 +353,13 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),))
try:
return securityParameters, encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'generateRequestMsg: serialization failure: %s' % exc)
raise error.StatusInformation(errorIndication=errind.serializationError)
@@ -373,7 +373,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
cachedSecurityData = self._cache.pop(securityStateReference)
communityName = cachedSecurityData['communityName']
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'generateResponseMsg: recovered community %r by securityStateReference %s' % (
communityName, securityStateReference))
@@ -383,13 +383,13 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))
+ debug.logger & debug.FLAG_MP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))
try:
return communityName, encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagMP and debug.logger(
+ debug.logger & debug.FLAG_MP and debug.logger(
'generateResponseMsg: serialization failure: %s' % exc)
raise error.StatusInformation(errorIndication=errind.serializationError)
@@ -442,9 +442,9 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
snmpEngine, 'rfc2576.processIncomingMsg'
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: looked up securityName %r securityModel %r contextEngineId %r contextName %r by communityName %r AND transportInformation %r' % (
- securityName, self.securityModelID, contextEngineId, contextName, communityName, transportInformation))
+ securityName, self.SECURITY_MODEL_ID, contextEngineId, contextName, communityName, transportInformation))
stateReference = self._cache.push(communityName=communityName)
@@ -453,7 +453,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
maxSizeResponseScopedPDU = maxMessageSize - 128
securityStateReference = stateReference
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: generated maxSizeResponseScopedPDU %s securityStateReference %s' % (
maxSizeResponseScopedPDU, securityStateReference))
@@ -462,7 +462,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
class SnmpV2cSecurityModel(SnmpV1SecurityModel):
- securityModelID = 2
+ SECURITY_MODEL_ID = 2
# XXX
# contextEngineId/contextName goes to globalData
diff --git a/pysnmp/proto/secmod/rfc3414/auth/base.py b/pysnmp/proto/secmod/rfc3414/auth/base.py
index 3ff8778f..1c019aea 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/base.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/base.py
@@ -8,7 +8,7 @@ from pysnmp.proto import errind, error
class AbstractAuthenticationService(object):
- serviceID = None
+ SERVICE_ID = None
def hashPassphrase(self, authKey):
raise error.ProtocolError(errind.noAuthentication)
diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
index 761bf3d9..3ce12da2 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
@@ -6,25 +6,28 @@
#
try:
from hashlib import md5
+
except ImportError:
import md5
md5 = md5.new
+
from pyasn1.type import univ
from pysnmp.proto.secmod.rfc3414.auth import base
from pysnmp.proto.secmod.rfc3414 import localkey
from pysnmp.proto import errind, error
-_twelveZeros = univ.OctetString((0,) * 12).asOctets()
-_fortyEightZeros = (0,) * 48
+TWELVE_ZEROS = univ.OctetString((0,) * 12).asOctets()
+FORTY_EIGHT_ZEROS = (0,) * 48
# rfc3414: 6.2.4
class HmacMd5(base.AbstractAuthenticationService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol
- __ipad = [0x36] * 64
- __opad = [0x5C] * 64
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol
+
+ IPAD = [0x36] * 64
+ OPAD = [0x5C] * 64
def hashPassphrase(self, authKey):
return localkey.hashPassphraseMD5(authKey)
@@ -42,7 +45,7 @@ class HmacMd5(base.AbstractAuthenticationService):
# should be in the substrate. Also, it pre-sets digest placeholder
# so we hash wholeMsg out of the box.
# Yes, that's ugly but that's rfc...
- l = wholeMsg.find(_twelveZeros)
+ l = wholeMsg.find(TWELVE_ZEROS)
if l == -1:
raise error.ProtocolError('Cant locate digest placeholder')
wholeHead = wholeMsg[:l]
@@ -51,20 +54,20 @@ class HmacMd5(base.AbstractAuthenticationService):
# 6.3.1.1
# 6.3.1.2a
- extendedAuthKey = authKey.asNumbers() + _fortyEightZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_EIGHT_ZEROS
# 6.3.1.2b --> no-op
# 6.3.1.2c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 6.3.1.2d --> no-op
# 6.3.1.2e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 6.3.1.3
@@ -93,23 +96,23 @@ class HmacMd5(base.AbstractAuthenticationService):
raise error.ProtocolError('Cant locate digest in wholeMsg')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l + 12:]
- authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail
+ authenticatedWholeMsg = wholeHead + TWELVE_ZEROS + wholeTail
# 6.3.2.4a
- extendedAuthKey = authKey.asNumbers() + _fortyEightZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_EIGHT_ZEROS
# 6.3.2.4b --> no-op
# 6.3.2.4c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 6.3.2.4d --> no-op
# 6.3.2.4e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 6.3.2.5a
diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
index 3efe9c49..8776f6fb 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
@@ -10,21 +10,23 @@ except ImportError:
import sha
sha1 = sha.new
+
from pyasn1.type import univ
from pysnmp.proto.secmod.rfc3414.auth import base
from pysnmp.proto.secmod.rfc3414 import localkey
from pysnmp.proto import errind, error
-_twelveZeros = univ.OctetString((0,) * 12).asOctets()
-_fortyFourZeros = (0,) * 44
+TWELVE_ZEROS = univ.OctetString((0,) * 12).asOctets()
+FORTY_FOUR_ZEROS = (0,) * 44
# 7.2.4
class HmacSha(base.AbstractAuthenticationService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol
- __ipad = [0x36] * 64
- __opad = [0x5C] * 64
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol
+
+ IPAD = [0x36] * 64
+ OPAD = [0x5C] * 64
def hashPassphrase(self, authKey):
return localkey.hashPassphraseSHA(authKey)
@@ -43,27 +45,27 @@ class HmacSha(base.AbstractAuthenticationService):
# should be in the substrate. Also, it pre-sets digest placeholder
# so we hash wholeMsg out of the box.
# Yes, that's ugly but that's rfc...
- l = wholeMsg.find(_twelveZeros)
+ l = wholeMsg.find(TWELVE_ZEROS)
if l == -1:
raise error.ProtocolError('Cant locate digest placeholder')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l + 12:]
# 7.3.1.2a
- extendedAuthKey = authKey.asNumbers() + _fortyFourZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_FOUR_ZEROS
# 7.3.1.2b -- no-op
# 7.3.1.2c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 7.3.1.2d -- no-op
# 7.3.1.2e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 7.3.1.3
@@ -90,23 +92,23 @@ class HmacSha(base.AbstractAuthenticationService):
raise error.ProtocolError('Cant locate digest in wholeMsg')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l + 12:]
- authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail
+ authenticatedWholeMsg = wholeHead + TWELVE_ZEROS + wholeTail
# 7.3.2.4a
- extendedAuthKey = authKey.asNumbers() + _fortyFourZeros
+ extendedAuthKey = authKey.asNumbers() + FORTY_FOUR_ZEROS
# 7.3.2.4b --> no-op
# 7.3.2.4c
k1 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.IPAD)
)
# 7.3.2.4d --> no-op
# 7.3.2.4e
k2 = univ.OctetString(
- map(lambda x, y: x ^ y, extendedAuthKey, self.__opad)
+ map(lambda x, y: x ^ y, extendedAuthKey, self.OPAD)
)
# 7.3.2.5a
diff --git a/pysnmp/proto/secmod/rfc3414/auth/noauth.py b/pysnmp/proto/secmod/rfc3414/auth/noauth.py
index d1dea4f5..d97d4888 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/noauth.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/noauth.py
@@ -9,7 +9,7 @@ from pysnmp.proto import errind, error
class NoAuth(base.AbstractAuthenticationService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol
def hashPassphrase(self, authKey):
return
diff --git a/pysnmp/proto/secmod/rfc3414/priv/base.py b/pysnmp/proto/secmod/rfc3414/priv/base.py
index a7c68a11..08c2930d 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/base.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/base.py
@@ -8,8 +8,8 @@ from pysnmp.proto import error
class AbstractEncryptionService(object):
- serviceID = None
- keySize = 0
+ SERVICE_ID = None
+ KEY_SIZE = 0
def hashPassphrase(self, authProtocol, privKey):
raise error.ProtocolError('no encryption')
diff --git a/pysnmp/proto/secmod/rfc3414/priv/des.py b/pysnmp/proto/secmod/rfc3414/priv/des.py
index 881989be..c9b483a2 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/des.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/des.py
@@ -5,8 +5,10 @@
# License: http://snmplabs.com/pysnmp/license.html
#
import random
+
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -36,21 +38,21 @@ random.seed()
# 8.2.4
class Des(base.AbstractEncryptionService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol
- keySize = 16
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol
+ KEY_SIZE = 16
if version_info < (2, 3):
- _localInt = int(random.random() * 0xffffffff)
+ local_int = int(random.random() * 0xffffffff)
else:
- _localInt = random.randrange(0, 0xffffffff)
+ local_int = random.randrange(0, 0xffffffff)
def hashPassphrase(self, authProtocol, privKey):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -58,18 +60,18 @@ class Des(base.AbstractEncryptionService):
return localkey.hashPassphrase(privKey, hashAlgo)
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
)
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
# 8.1.1.1
def __getEncryptionKey(self, privKey, snmpEngineBoots):
@@ -82,14 +84,14 @@ class Des(base.AbstractEncryptionService):
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
+ self.local_int >> 24 & 0xff,
+ self.local_int >> 16 & 0xff,
+ self.local_int >> 8 & 0xff,
+ self.local_int & 0xff]
+ if self.local_int == 0xffffffff:
+ self.local_int = 0
else:
- self._localInt += 1
+ self.local_int += 1
return (desKey.asOctets(),
univ.OctetString(salt).asOctets(),
diff --git a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py b/pysnmp/proto/secmod/rfc3414/priv/nopriv.py
index 6721153b..7283e6ec 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/nopriv.py
@@ -9,7 +9,7 @@ from pysnmp.proto import errind, error
class NoPriv(base.AbstractEncryptionService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol
def hashPassphrase(self, authProtocol, privKey):
return
diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py
index b9fa9a2c..a09b98ed 100644
--- a/pysnmp/proto/secmod/rfc3414/service.py
+++ b/pysnmp/proto/secmod/rfc3414/service.py
@@ -38,23 +38,28 @@ class UsmSecurityParameters(rfc1155.TypeCoercionHackMixIn, univ.Sequence):
class SnmpUSMSecurityModel(AbstractSecurityModel):
- securityModelID = 3
- authServices = {hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(),
- hmacsha.HmacSha.serviceID: hmacsha.HmacSha(),
- hmacsha2.HmacSha2.sha224ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha224ServiceID),
- hmacsha2.HmacSha2.sha256ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha256ServiceID),
- hmacsha2.HmacSha2.sha384ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha384ServiceID),
- hmacsha2.HmacSha2.sha512ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha512ServiceID),
- noauth.NoAuth.serviceID: noauth.NoAuth(),
- }
- privServices = {des.Des.serviceID: des.Des(),
- des3.Des3.serviceID: des3.Des3(),
- aes.Aes.serviceID: aes.Aes(),
- aes192.AesBlumenthal192.serviceID: aes192.AesBlumenthal192(),
- aes256.AesBlumenthal256.serviceID: aes256.AesBlumenthal256(),
- aes192.Aes192.serviceID: aes192.Aes192(), # non-standard
- aes256.Aes256.serviceID: aes256.Aes256(), # non-standard
- nopriv.NoPriv.serviceID: nopriv.NoPriv()}
+ SECURITY_MODEL_ID = 3
+
+ AUTH_SERVICES = {
+ hmacmd5.HmacMd5.SERVICE_ID: hmacmd5.HmacMd5(),
+ hmacsha.HmacSha.SERVICE_ID: hmacsha.HmacSha(),
+ hmacsha2.HmacSha2.SHA224_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA224_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA256_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA256_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA384_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA384_SERVICE_ID),
+ hmacsha2.HmacSha2.SHA512_SERVICE_ID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.SHA512_SERVICE_ID),
+ noauth.NoAuth.SERVICE_ID: noauth.NoAuth(),
+ }
+
+ PRIV_SERVICES = {
+ des.Des.SERVICE_ID: des.Des(),
+ des3.Des3.SERVICE_ID: des3.Des3(),
+ aes.Aes.SERVICE_ID: aes.Aes(),
+ aes192.AesBlumenthal192.SERVICE_ID: aes192.AesBlumenthal192(),
+ aes256.AesBlumenthal256.SERVICE_ID: aes256.AesBlumenthal256(),
+ aes192.Aes192.SERVICE_ID: aes192.Aes192(), # non-standard
+ aes256.Aes256.SERVICE_ID: aes256.Aes256(), # non-standard
+ nopriv.NoPriv.SERVICE_ID: nopriv.NoPriv()
+ }
def __init__(self):
AbstractSecurityModel.__init__(self)
@@ -82,7 +87,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
except NoSuchInstanceError:
self.__paramsBranchId = usmUserEngineID.branchVersionId
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2usr: built snmpEngineId + securityName to userName map, version %s: %r' % (
self.__paramsBranchId, self.__securityToUserMap))
break
@@ -106,11 +111,11 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
try:
userName = self.__securityToUserMap[(securityEngineID, securityName)]
except KeyError:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2usr: no entry exists for snmpEngineId %r, securityName %r' % (securityEngineID, securityName))
raise NoSuchInstanceError() # emulate MIB lookup
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'_sec2usr: using userName %r for snmpEngineId %r, securityName %r' % (
userName, securityEngineID, securityName))
@@ -196,8 +201,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode(
pysnmpUsmKeyEntry.name + (1,) + tblIdx2
)
- if usmUserAuthProtocol.syntax in self.authServices:
- localizeKey = self.authServices[usmUserAuthProtocol.syntax].localizeKey
+ if usmUserAuthProtocol.syntax in self.AUTH_SERVICES:
+ localizeKey = self.AUTH_SERVICES[usmUserAuthProtocol.syntax].localizeKey
localAuthKey = localizeKey(pysnmpUsmKeyAuth.syntax,
securityEngineID)
else:
@@ -209,8 +214,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode(
pysnmpUsmKeyEntry.name + (2,) + tblIdx2
)
- if usmUserPrivProtocol.syntax in self.privServices:
- localizeKey = self.privServices[usmUserPrivProtocol.syntax].localizeKey
+ if usmUserPrivProtocol.syntax in self.PRIV_SERVICES:
+ localizeKey = self.PRIV_SERVICES[usmUserPrivProtocol.syntax].localizeKey
localPrivKey = localizeKey(usmUserAuthProtocol.syntax,
pysnmpUsmKeyPriv.syntax,
securityEngineID)
@@ -243,7 +248,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if 'usmUserAuthProtocol' in cachedSecurityData:
usmUserAuthProtocol = cachedSecurityData['usmUserAuthProtocol']
else:
- usmUserAuthProtocol = noauth.NoAuth.serviceID
+ usmUserAuthProtocol = noauth.NoAuth.SERVICE_ID
if 'usmUserAuthKeyLocalized' in cachedSecurityData:
usmUserAuthKeyLocalized = cachedSecurityData['usmUserAuthKeyLocalized']
else:
@@ -251,13 +256,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if 'usmUserPrivProtocol' in cachedSecurityData:
usmUserPrivProtocol = cachedSecurityData['usmUserPrivProtocol']
else:
- usmUserPrivProtocol = nopriv.NoPriv.serviceID
+ usmUserPrivProtocol = nopriv.NoPriv.SERVICE_ID
if 'usmUserPrivKeyLocalized' in cachedSecurityData:
usmUserPrivKeyLocalized = cachedSecurityData['usmUserPrivKeyLocalized']
else:
usmUserPrivKeyLocalized = None
securityEngineID = snmpEngineID
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: user info read from cache')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: user info read from cache')
elif securityName:
# 3.1.1b
try:
@@ -268,7 +273,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityEngineID,
self.__sec2usr(snmpEngine, securityName, securityEngineID)
)
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read user info')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: read user info')
except NoSuchInstanceError:
pysnmpUsmDiscovery, = mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery')
@@ -292,10 +297,10 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
errorIndication=errind.unknownSecurityName
)
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: clone user info')
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: %s' % exc)
snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs')
snmpInGenErrs.syntax += 1
@@ -305,13 +310,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
else:
# empty username used for engineID discovery
usmUserName = usmUserSecurityName = null
- usmUserAuthProtocol = noauth.NoAuth.serviceID
- usmUserPrivProtocol = nopriv.NoPriv.serviceID
+ usmUserAuthProtocol = noauth.NoAuth.SERVICE_ID
+ usmUserPrivProtocol = nopriv.NoPriv.SERVICE_ID
usmUserAuthKeyLocalized = usmUserPrivKeyLocalized = None
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use empty USM data')
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: use empty USM data')
# noinspection PyUnboundLocalVariable
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: local usmUserName %r usmUserSecurityName %r usmUserAuthProtocol %s usmUserPrivProtocol %s securityEngineID %r securityName %r' % (
usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, securityEngineID, securityName))
@@ -319,15 +324,15 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.2
if securityLevel == 3:
- if (usmUserAuthProtocol == noauth.NoAuth.serviceID or
- usmUserPrivProtocol == nopriv.NoPriv.serviceID):
+ if (usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID or
+ usmUserPrivProtocol == nopriv.NoPriv.SERVICE_ID):
raise error.StatusInformation(
errorIndication=errind.unsupportedSecurityLevel
)
# 3.1.3
if securityLevel == 3 or securityLevel == 2:
- if usmUserAuthProtocol == noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID:
raise error.StatusInformation(
errorIndication=errind.unsupportedSecurityLevel
)
@@ -345,14 +350,14 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
pdu = scopedPDU.getComponentByPosition(2).getComponent()
# 3.1.6.b
- if pdu.tagSet in rfc3411.unconfirmedClassPDUs:
+ if pdu.tagSet in rfc3411.UNCONFIRMED_CLASS_PDUS:
(snmpEngineBoots,
snmpEngineTime) = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime')
snmpEngineBoots = snmpEngineBoots.syntax
snmpEngineTime = snmpEngineTime.syntax.clone()
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD')
# 3.1.6a
@@ -362,41 +367,41 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
latestReceivedEngineTime,
latestUpdateTimestamp) = self.__timeline[securityEngineID]
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline')
# 3.1.6.c
else:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime')
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: use snmpEngineBoots %s snmpEngineTime %s for securityEngineID %r' % (
snmpEngineBoots, snmpEngineTime, securityEngineID))
# 3.1.4a
if securityLevel == 3:
- if usmUserPrivProtocol in self.privServices:
- privHandler = self.privServices[usmUserPrivProtocol]
+ if usmUserPrivProtocol in self.PRIV_SERVICES:
+ privHandler = self.PRIV_SERVICES[usmUserPrivProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.encryptionError
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU %s' % scopedPDU.prettyPrint())
try:
dataToEncrypt = encoder.encode(scopedPDU)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU encoded into %s' % debug.hexdump(dataToEncrypt))
# noinspection PyUnboundLocalVariable
@@ -413,14 +418,14 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
1, encryptedData, verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: scopedPDU ciphered into %s' % debug.hexdump(encryptedData))
# 3.1.4b
elif securityLevel == 1 or securityLevel == 2:
securityParameters.setComponentByPosition(5, '')
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint())
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint())
# 3.1.5
securityParameters.setComponentByPosition(
@@ -440,8 +445,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.1.8a
if securityLevel == 3 or securityLevel == 2:
- if usmUserAuthProtocol in self.authServices:
- authHandler = self.authServices[usmUserAuthProtocol]
+ if usmUserAuthProtocol in self.AUTH_SERVICES:
+ authHandler = self.AUTH_SERVICES[usmUserAuthProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.authenticationFailure
@@ -452,27 +457,27 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
4, '\x00' * authHandler.digestLength
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),))
try:
msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: securityParameters serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: auth outgoing msg: %s' % msg.prettyPrint())
try:
wholeMsg = encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: msg serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
@@ -489,32 +494,32 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
4, '', verifyConstraints=False, matchTags=False, matchConstraints=False
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),))
try:
msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False, matchTags=False, matchConstraints=False)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: secutiryParameters serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
try:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: plain outgoing msg: %s' % msg.prettyPrint())
authenticatedWholeMsg = encoder.encode(msg)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'__generateRequestOrResponseMsg: msg serialization error: %s' % exc)
raise error.StatusInformation(
errorIndication=errind.serializationError
)
- debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s outgoing msg: %s' % (
+ debug.logger & debug.FLAG_SM and debug.logger('__generateRequestOrResponseMsg: %s outgoing msg: %s' % (
securityLevel > 1 and "authenticated" or "plain", debug.hexdump(authenticatedWholeMsg)))
# 3.1.9
@@ -556,7 +561,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# (48 - maximum SNMPv3 header length)
maxSizeResponseScopedPDU = int(maxMessageSize) - len(securityParameters) - 48
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: securityParameters %s' % debug.hexdump(securityParameters))
# 3.2.1
@@ -564,7 +569,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityParameters, asn1Spec=self.__securityParametersSpec
)
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),))
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),))
if eoo.endOfOctets.isSameTypeWith(securityParameters):
raise error.StatusInformation(errorIndication=errind.parseError)
@@ -575,7 +580,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
msgUserName=securityParameters.getComponentByPosition(3)
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: cache write securityStateReference %s by msgUserName %s' % (
securityStateReference, securityParameters.getComponentByPosition(3)))
@@ -593,26 +598,26 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
if (msgAuthoritativeEngineId and
4 < len(msgAuthoritativeEngineId) < 33):
# 3.2.3a - cloned user when request was sent
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: non-synchronized securityEngineID %r' % (msgAuthoritativeEngineId,))
else:
# 3.2.3b
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: peer requested snmpEngineID discovery')
usmStatsUnknownEngineIDs, = mibBuilder.importSymbols(
'__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs')
usmStatsUnknownEngineIDs.syntax += 1
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: null or malformed msgAuthoritativeEngineId')
pysnmpUsmDiscoverable, = mibBuilder.importSymbols(
'__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable')
if pysnmpUsmDiscoverable.syntax:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: starting snmpEngineID discovery procedure')
# Report original contextName
if scopedPduData.getName() != 'plaintext':
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: scopedPduData not plaintext %s' % scopedPduData.prettyPrint())
raise error.StatusInformation(
errorIndication=errind.unknownEngineID
@@ -635,7 +640,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
maxSizeResponseScopedPDU=maxSizeResponseScopedPDU
)
else:
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: will not discover EngineID')
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: will not discover EngineID')
# free securityStateReference XXX
raise error.StatusInformation(
errorIndication=errind.unknownEngineID
@@ -643,7 +648,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
msgUserName = securityParameters.getComponentByPosition(3)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: read from securityParams msgAuthoritativeEngineId %r msgUserName %r' % (
msgAuthoritativeEngineId, msgUserName))
@@ -659,10 +664,10 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
snmpEngine.msgAndPduDsp.mibInstrumController,
msgAuthoritativeEngineId, msgUserName
)
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read user info from LCD')
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: read user info from LCD')
except NoSuchInstanceError:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: unknown securityEngineID %r msgUserName %r' % (
msgAuthoritativeEngineId, msgUserName))
@@ -683,18 +688,18 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % exc)
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: %s' % exc)
snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs')
snmpInGenErrs.syntax += 1
raise error.StatusInformation(errorIndication=errind.invalidMsg)
else:
# empty username used for engineID discovery
usmUserName = usmUserSecurityName = null
- usmUserAuthProtocol = noauth.NoAuth.serviceID
- usmUserPrivProtocol = nopriv.NoPriv.serviceID
+ usmUserAuthProtocol = noauth.NoAuth.SERVICE_ID
+ usmUserPrivProtocol = nopriv.NoPriv.SERVICE_ID
usmUserAuthKeyLocalized = usmUserPrivKeyLocalized = None
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: now have usmUserName %r usmUserSecurityName %r usmUserAuthProtocol %r usmUserPrivProtocol %r for msgUserName %r' % (
usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, msgUserName))
@@ -733,28 +738,28 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# Authoritative SNMP engine: make sure securityLevel is sufficient
badSecIndication = None
if securityLevel == 3:
- if usmUserAuthProtocol == noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID:
badSecIndication = 'authPriv wanted while auth not expected'
- if usmUserPrivProtocol == nopriv.NoPriv.serviceID:
+ if usmUserPrivProtocol == nopriv.NoPriv.SERVICE_ID:
badSecIndication = 'authPriv wanted while priv not expected'
elif securityLevel == 2:
- if usmUserAuthProtocol == noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol == noauth.NoAuth.SERVICE_ID:
badSecIndication = 'authNoPriv wanted while auth not expected'
- if usmUserPrivProtocol != nopriv.NoPriv.serviceID:
+ if usmUserPrivProtocol != nopriv.NoPriv.SERVICE_ID:
# 4 (discovery phase always uses authenticated messages)
if msgAuthoritativeEngineBoots or msgAuthoritativeEngineTime:
badSecIndication = 'authNoPriv wanted while priv expected'
elif securityLevel == 1:
- if usmUserAuthProtocol != noauth.NoAuth.serviceID:
+ if usmUserAuthProtocol != noauth.NoAuth.SERVICE_ID:
badSecIndication = 'noAuthNoPriv wanted while auth expected'
- if usmUserPrivProtocol != nopriv.NoPriv.serviceID:
+ if usmUserPrivProtocol != nopriv.NoPriv.SERVICE_ID:
badSecIndication = 'noAuthNoPriv wanted while priv expected'
if badSecIndication:
usmStatsUnsupportedSecLevels, = mibBuilder.importSymbols(
'__SNMP-USER-BASED-SM-MIB', 'usmStatsUnsupportedSecLevels')
usmStatsUnsupportedSecLevels.syntax += 1
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: reporting inappropriate security level for user %s: %s' % (
msgUserName, badSecIndication))
raise error.StatusInformation(
@@ -771,8 +776,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.6
if securityLevel == 3 or securityLevel == 2:
- if usmUserAuthProtocol in self.authServices:
- authHandler = self.authServices[usmUserAuthProtocol]
+ if usmUserAuthProtocol in self.AUTH_SERVICES:
+ authHandler = self.AUTH_SERVICES[usmUserAuthProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.authenticationFailure
@@ -801,7 +806,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
maxSizeResponseScopedPDU=maxSizeResponseScopedPDU
)
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authenticated')
+ debug.logger & debug.FLAG_SM and debug.logger('processIncomingMsg: incoming msg authenticated')
# synchronize time with authed peer
self.__timeline[msgAuthoritativeEngineId] = (
@@ -817,7 +822,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
self.__timelineExpQueue[expireAt] = []
self.__timelineExpQueue[expireAt].append(msgAuthoritativeEngineId)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: store timeline for securityEngineID %r' % (msgAuthoritativeEngineId,))
# 3.2.7
@@ -830,7 +835,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
snmpEngineBoots = snmpEngineBoots.syntax
snmpEngineTime = snmpEngineTime.syntax.clone()
idleTime = 0
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: read snmpEngineBoots (%s), snmpEngineTime (%s) from LCD' % (
snmpEngineBoots, snmpEngineTime))
else:
@@ -843,7 +848,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
]
# time passed since last talk with this SNMP engine
idleTime = int(time.time()) - latestUpdateTimestamp
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: read timeline snmpEngineBoots %s snmpEngineTime %s for msgAuthoritativeEngineId %r, idle time %s secs' % (
snmpEngineBoots, snmpEngineTime, msgAuthoritativeEngineId, idleTime))
else:
@@ -888,7 +893,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
self.__timelineExpQueue[expireAt] = []
self.__timelineExpQueue[expireAt].append(msgAuthoritativeEngineId)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineId %r' % (
msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineId))
@@ -904,8 +909,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.8a
if securityLevel == 3:
- if usmUserPrivProtocol in self.privServices:
- privHandler = self.privServices[usmUserPrivProtocol]
+ if usmUserPrivProtocol in self.PRIV_SERVICES:
+ privHandler = self.PRIV_SERVICES[usmUserPrivProtocol]
else:
raise error.StatusInformation(
errorIndication=errind.decryptionError,
@@ -926,7 +931,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
securityParameters.getComponentByPosition(5)),
encryptedPDU
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: PDU deciphered into %s' % debug.hexdump(decryptedData))
except error.StatusInformation:
@@ -949,7 +954,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
scopedPDU, rest = decoder.decode(decryptedData, asn1Spec=scopedPduSpec)
except PyAsn1Error as exc:
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: scopedPDU decoder failed %s' % exc)
raise error.StatusInformation(
errorIndication=errind.decryptionError,
@@ -970,13 +975,13 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
msgUserName=msgUserName
)
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: scopedPDU decoded %s' % scopedPDU.prettyPrint())
# 3.2.10
securityName = usmUserSecurityName
- debug.logger & debug.flagSM and debug.logger(
+ debug.logger & debug.FLAG_SM and debug.logger(
'processIncomingMsg: cached msgUserName %s info by securityStateReference %s' % (
msgUserName, securityStateReference))
@@ -1008,7 +1013,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
for engineIdKey in self.__timelineExpQueue[self.__expirationTimer]:
if engineIdKey in self.__timeline:
del self.__timeline[engineIdKey]
- debug.logger & debug.flagSM and debug.logger('__expireTimelineInfo: expiring %r' % (engineIdKey,))
+ debug.logger & debug.FLAG_SM and debug.logger('__expireTimelineInfo: expiring %r' % (engineIdKey,))
del self.__timelineExpQueue[self.__expirationTimer]
self.__expirationTimer += 1
diff --git a/pysnmp/proto/secmod/rfc3826/priv/aes.py b/pysnmp/proto/secmod/rfc3826/priv/aes.py
index b7e32684..8a67ecc2 100644
--- a/pysnmp/proto/secmod/rfc3826/priv/aes.py
+++ b/pysnmp/proto/secmod/rfc3826/priv/aes.py
@@ -5,8 +5,10 @@
# License: http://snmplabs.com/pysnmp/license.html
#
import random
+
try:
from hashlib import md5, sha1
+
except ImportError:
import md5
import sha
@@ -36,25 +38,26 @@ random.seed()
#
class Aes(base.AbstractEncryptionService):
- serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol
- keySize = 16
- _localInt = random.randrange(0, 0xffffffffffffffff)
+ SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol
+ KEY_SIZE = 16
+
+ local_int = random.randrange(0, 0xffffffffffffffff)
# 3.1.2.1
def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime):
- salt = [self._localInt >> 56 & 0xff,
- self._localInt >> 48 & 0xff,
- self._localInt >> 40 & 0xff,
- self._localInt >> 32 & 0xff,
- self._localInt >> 24 & 0xff,
- self._localInt >> 16 & 0xff,
- self._localInt >> 8 & 0xff,
- self._localInt & 0xff]
-
- if self._localInt == 0xffffffffffffffff:
- self._localInt = 0
+ salt = [self.local_int >> 56 & 0xff,
+ self.local_int >> 48 & 0xff,
+ self.local_int >> 40 & 0xff,
+ self.local_int >> 32 & 0xff,
+ self.local_int >> 24 & 0xff,
+ self.local_int >> 16 & 0xff,
+ self.local_int >> 8 & 0xff,
+ self.local_int & 0xff]
+
+ if self.local_int == 0xffffffffffffffff:
+ self.local_int = 0
else:
- self._localInt += 1
+ self.local_int += 1
return self.__getDecryptionKey(privKey, snmpEngineBoots, snmpEngineTime, salt) + (
univ.OctetString(salt).asOctets(),)
@@ -74,15 +77,15 @@ class Aes(base.AbstractEncryptionService):
snmpEngineTime >> 8 & 0xff,
snmpEngineTime & 0xff] + salt
- return privKey[:self.keySize].asOctets(), univ.OctetString(iv).asOctets()
+ return privKey[:self.KEY_SIZE].asOctets(), univ.OctetString(iv).asOctets()
def hashPassphrase(self, authProtocol, privKey):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
@@ -90,18 +93,18 @@ class Aes(base.AbstractEncryptionService):
return localkey.hashPassphrase(privKey, hashAlgo)
def localizeKey(self, authProtocol, privKey, snmpEngineID):
- if authProtocol == hmacmd5.HmacMd5.serviceID:
+ if authProtocol == hmacmd5.HmacMd5.SERVICE_ID:
hashAlgo = md5
- elif authProtocol == hmacsha.HmacSha.serviceID:
+ elif authProtocol == hmacsha.HmacSha.SERVICE_ID:
hashAlgo = sha1
- elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms:
- hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol]
+ elif authProtocol in hmacsha2.HmacSha2.HASH_ALGORITHM:
+ hashAlgo = hmacsha2.HmacSha2.HASH_ALGORITHM[authProtocol]
else:
raise error.ProtocolError(
'Unknown auth protocol %s' % (authProtocol,)
)
localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo)
- return localPrivKey[:self.keySize]
+ return localPrivKey[:self.KEY_SIZE]
# 3.2.4.1
def encryptData(self, encryptKey, privParameters, dataToEncrypt):
diff --git a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py
index 219b90d6..495f8fcd 100644
--- a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py
+++ b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py
@@ -26,37 +26,40 @@ from pysnmp.proto import errind, error
# 7.2.4
class HmacSha2(base.AbstractAuthenticationService):
- sha224ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 4) # usmHMAC128SHA224AuthProtocol
- sha256ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 5) # usmHMAC192SHA256AuthProtocol
- sha384ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 6) # usmHMAC256SHA384AuthProtocol
- sha512ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 7) # usmHMAC384SHA512AuthProtocol
- keyLengths = {
- sha224ServiceID: 28,
- sha256ServiceID: 32,
- sha384ServiceID: 48,
- sha512ServiceID: 64
+ SHA224_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 4) # usmHMAC128SHA224AuthProtocol
+ SHA256_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 5) # usmHMAC192SHA256AuthProtocol
+ SHA384_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 6) # usmHMAC256SHA384AuthProtocol
+ SHA512_SERVICE_ID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 7) # usmHMAC384SHA512AuthProtocol
+
+ KEY_LENGTH = {
+ SHA224_SERVICE_ID: 28,
+ SHA256_SERVICE_ID: 32,
+ SHA384_SERVICE_ID: 48,
+ SHA512_SERVICE_ID: 64
}
- digestLengths = {
- sha224ServiceID: 16,
- sha256ServiceID: 24,
- sha384ServiceID: 32,
- sha512ServiceID: 48
+
+ DIGEST_LENGTH = {
+ SHA224_SERVICE_ID: 16,
+ SHA256_SERVICE_ID: 24,
+ SHA384_SERVICE_ID: 32,
+ SHA512_SERVICE_ID: 48
}
- hashAlgorithms = {
- sha224ServiceID: sha224,
- sha256ServiceID: sha256,
- sha384ServiceID: sha384,
- sha512ServiceID: sha512
+
+ HASH_ALGORITHM = {
+ SHA224_SERVICE_ID: sha224,
+ SHA256_SERVICE_ID: sha256,
+ SHA384_SERVICE_ID: sha384,
+ SHA512_SERVICE_ID: sha512
}
- __ipad = [0x36] * 64
- __opad = [0x5C] * 64
+ IPAD = [0x36] * 64
+ OPAD = [0x5C] * 64
def __init__(self, oid):
- if oid not in self.hashAlgorithms:
+ if oid not in self.HASH_ALGORITHM:
raise error.ProtocolError('No SHA-2 authentication algorithm %s available' % (oid,))
- self.__hashAlgo = self.hashAlgorithms[oid]
- self.__digestLength = self.digestLengths[oid]
+ self.__hashAlgo = self.HASH_ALGORITHM[oid]
+ self.__digestLength = self.DIGEST_LENGTH[oid]
self.__placeHolder = univ.OctetString((0,) * self.__digestLength).asOctets()
def hashPassphrase(self, authKey):
diff --git a/pysnmp/smi/builder.py b/pysnmp/smi/builder.py
index 01273491..dedf95a2 100644
--- a/pysnmp/smi/builder.py
+++ b/pysnmp/smi/builder.py
@@ -14,8 +14,10 @@ import traceback
try:
from errno import ENOENT
+
except ImportError:
ENOENT = -1
+
from pysnmp import __version__ as pysnmp_version
from pysnmp.smi import error
from pysnmp import debug
@@ -38,7 +40,7 @@ class __AbstractMibSource(object):
if typ not in self.__sfx:
self.__sfx[typ] = []
self.__sfx[typ].append((sfx, len(sfx), mode))
- debug.logger & debug.flagBld and debug.logger('trying %s' % self)
+ debug.logger & debug.FLAG_BLD and debug.logger('trying %s' % self)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self._srcName)
@@ -82,7 +84,7 @@ class __AbstractMibSource(object):
except IOError as exc:
if ENOENT == -1 or exc.errno == ENOENT:
- debug.logger & debug.flagBld and debug.logger(
+ debug.logger & debug.FLAG_BLD and debug.logger(
'file %s access error: %s' % (f + pycSfx, exc)
)
@@ -94,13 +96,13 @@ class __AbstractMibSource(object):
pycData = pycData[4:]
pycTime = struct.unpack('<L', pycData[:4])[0]
pycData = pycData[4:]
- debug.logger & debug.flagBld and debug.logger(
+ debug.logger & debug.FLAG_BLD and debug.logger(
'file %s mtime %d' % (pycPath, pycTime)
)
break
else:
- debug.logger & debug.flagBld and debug.logger('bad magic in %s' % pycPath)
+ debug.logger & debug.FLAG_BLD and debug.logger('bad magic in %s' % pycPath)
for pySfx, pySfxLen, pyMode in self.__sfx[imp.PY_SOURCE]:
try:
@@ -108,7 +110,7 @@ class __AbstractMibSource(object):
except IOError as exc:
if ENOENT == -1 or exc.errno == ENOENT:
- debug.logger & debug.flagBld and debug.logger(
+ debug.logger & debug.FLAG_BLD and debug.logger(
'file %s access error: %s' % (f + pySfx, exc)
)
@@ -116,7 +118,7 @@ class __AbstractMibSource(object):
raise error.MibLoadError('MIB file %s access error: %s' % (f + pySfx, exc))
else:
- debug.logger & debug.flagBld and debug.logger('file %s mtime %d' % (f + pySfx, pyTime))
+ debug.logger & debug.FLAG_BLD and debug.logger('file %s mtime %d' % (f + pySfx, pyTime))
break
if pycTime != -1 and pycTime >= pyTime:
@@ -212,7 +214,7 @@ class DirMibSource(__AbstractMibSource):
try:
return self._uniqNames(os.listdir(self._srcName))
except OSError as exc:
- debug.logger & debug.flagBld and debug.logger(
+ debug.logger & debug.FLAG_BLD and debug.logger(
'listdir() failed for %s: %s' % (self._srcName, exc))
return ()
@@ -243,10 +245,11 @@ class DirMibSource(__AbstractMibSource):
class MibBuilder(object):
- defaultCoreMibs = os.pathsep.join(
+ DEFAULT_CORE_MIBS = os.pathsep.join(
('pysnmp.smi.mibs.instances', 'pysnmp.smi.mibs')
)
- defaultMiscMibs = 'pysnmp_mibs'
+
+ DEFAULT_MISC_MIBS = 'pysnmp_mibs'
moduleID = 'PYSNMP_MODULE_ID'
@@ -262,10 +265,10 @@ class MibBuilder(object):
if ev in os.environ:
for m in os.environ[ev].split(os.pathsep):
sources.append(ZipMibSource(m))
- if not sources and self.defaultMiscMibs:
- for m in self.defaultMiscMibs.split(os.pathsep):
+ if not sources and self.DEFAULT_MISC_MIBS:
+ for m in self.DEFAULT_MISC_MIBS.split(os.pathsep):
sources.append(ZipMibSource(m))
- for m in self.defaultCoreMibs.split(os.pathsep):
+ for m in self.DEFAULT_CORE_MIBS.split(os.pathsep):
sources.insert(0, ZipMibSource(m))
self.mibSymbols = {}
self.__mibSources = []
@@ -288,11 +291,11 @@ class MibBuilder(object):
def addMibSources(self, *mibSources):
self.__mibSources.extend([s.init() for s in mibSources])
- debug.logger & debug.flagBld and debug.logger('addMibSources: new MIB sources %s' % (self.__mibSources,))
+ debug.logger & debug.FLAG_BLD and debug.logger('addMibSources: new MIB sources %s' % (self.__mibSources,))
def setMibSources(self, *mibSources):
self.__mibSources = [s.init() for s in mibSources]
- debug.logger & debug.flagBld and debug.logger('setMibSources: new MIB sources %s' % (self.__mibSources,))
+ debug.logger & debug.FLAG_BLD and debug.logger('setMibSources: new MIB sources %s' % (self.__mibSources,))
def getMibSources(self):
return tuple(self.__mibSources)
@@ -300,25 +303,25 @@ class MibBuilder(object):
def loadModule(self, modName, **userCtx):
"""Load and execute MIB modules as Python code"""
for mibSource in self.__mibSources:
- debug.logger & debug.flagBld and debug.logger('loadModule: trying %s at %s' % (modName, mibSource))
+ debug.logger & debug.FLAG_BLD and debug.logger('loadModule: trying %s at %s' % (modName, mibSource))
try:
codeObj, sfx = mibSource.read(modName)
except IOError as exc:
- debug.logger & debug.flagBld and debug.logger(
+ debug.logger & debug.FLAG_BLD and debug.logger(
'loadModule: read %s from %s failed: %s' % (modName, mibSource, exc))
continue
modPath = mibSource.fullPath(modName, sfx)
if modPath in self.__modPathsSeen:
- debug.logger & debug.flagBld and debug.logger('loadModule: seen %s' % modPath)
+ debug.logger & debug.FLAG_BLD and debug.logger('loadModule: seen %s' % modPath)
break
else:
self.__modPathsSeen.add(modPath)
- debug.logger & debug.flagBld and debug.logger('loadModule: evaluating %s' % modPath)
+ debug.logger & debug.FLAG_BLD and debug.logger('loadModule: evaluating %s' % modPath)
g = {'mibBuilder': self, 'userCtx': userCtx}
@@ -333,7 +336,7 @@ class MibBuilder(object):
self.__modSeen[modName] = modPath
- debug.logger & debug.flagBld and debug.logger('loadModule: loaded %s' % modPath)
+ debug.logger & debug.FLAG_BLD and debug.logger('loadModule: loaded %s' % modPath)
break
@@ -366,7 +369,7 @@ class MibBuilder(object):
except error.MibNotFoundError:
if self.__mibCompiler:
- debug.logger & debug.flagBld and debug.logger('loadModules: calling MIB compiler for %s' % modName)
+ debug.logger & debug.FLAG_BLD and debug.logger('loadModules: calling MIB compiler for %s' % modName)
status = self.__mibCompiler.compile(modName, genTexts=self.loadTexts)
errs = '; '.join([hasattr(x, 'error') and str(x.error) or x for x in status.values() if
x in ('failed', 'missing')])
@@ -390,7 +393,7 @@ class MibBuilder(object):
self.__modPathsSeen.remove(self.__modSeen[modName])
del self.__modSeen[modName]
- debug.logger & debug.flagBld and debug.logger('unloadModules: %s' % modName)
+ debug.logger & debug.FLAG_BLD and debug.logger('unloadModules: %s' % modName)
return self
@@ -420,7 +423,7 @@ class MibBuilder(object):
mibSymbols = self.mibSymbols[modName]
for symObj in anonymousSyms:
- debug.logger & debug.flagBld and debug.logger(
+ debug.logger & debug.FLAG_BLD and debug.logger(
'exportSymbols: anonymous symbol %s::__pysnmp_%ld' % (modName, self._autoName))
mibSymbols['__pysnmp_%ld' % self._autoName] = symObj
self._autoName += 1
@@ -440,7 +443,7 @@ class MibBuilder(object):
mibSymbols[symName] = symObj
- debug.logger & debug.flagBld and debug.logger('exportSymbols: symbol %s::%s' % (modName, symName))
+ debug.logger & debug.FLAG_BLD and debug.logger('exportSymbols: symbol %s::%s' % (modName, symName))
self.lastBuildId += 1
@@ -457,7 +460,7 @@ class MibBuilder(object):
)
del mibSymbols[symName]
- debug.logger & debug.flagBld and debug.logger('unexportSymbols: symbol %s::%s' % (modName, symName))
+ debug.logger & debug.FLAG_BLD and debug.logger('unexportSymbols: symbol %s::%s' % (modName, symName))
if not self.mibSymbols[modName]:
del self.mibSymbols[modName]
diff --git a/pysnmp/smi/compiler.py b/pysnmp/smi/compiler.py
index 08e38811..231685f8 100644
--- a/pysnmp/smi/compiler.py
+++ b/pysnmp/smi/compiler.py
@@ -7,15 +7,15 @@
import os
import sys
-defaultSources = ['file:///usr/share/snmp/mibs', 'file:///usr/share/mibs']
+DEFAULT_SOURCES = ['file:///usr/share/snmp/mibs', 'file:///usr/share/mibs']
if sys.platform[:3] == 'win':
- defaultDest = os.path.join(os.path.expanduser("~"),
+ DEFAULT_DEST = os.path.join(os.path.expanduser("~"),
'PySNMP Configuration', 'mibs')
else:
- defaultDest = os.path.join(os.path.expanduser("~"), '.pysnmp', 'mibs')
+ DEFAULT_DEST = os.path.join(os.path.expanduser("~"), '.pysnmp', 'mibs')
-defaultBorrowers = []
+DEFAULT_BORROWERS = []
try:
from pysmi.reader.url import getReadersFromUrls
@@ -50,16 +50,16 @@ else:
compiler = MibCompiler(parserFactory(**smiV1Relaxed)(),
PySnmpCodeGen(),
- PyFileWriter(kwargs.get('destination') or defaultDest))
+ PyFileWriter(kwargs.get('destination') or DEFAULT_DEST))
- compiler.addSources(*getReadersFromUrls(*kwargs.get('sources') or defaultSources))
+ compiler.addSources(*getReadersFromUrls(*kwargs.get('sources') or DEFAULT_SOURCES))
compiler.addSearchers(StubSearcher(*baseMibs))
compiler.addSearchers(*[PyPackageSearcher(x.fullPath()) for x in mibBuilder.getMibSources()])
compiler.addBorrowers(*[PyFileBorrower(x, genTexts=mibBuilder.loadTexts) for x in
- getReadersFromUrls(*kwargs.get('borrowers') or defaultBorrowers,
+ getReadersFromUrls(*kwargs.get('borrowers') or DEFAULT_BORROWERS,
lowcaseMatching=False)])
mibBuilder.setMibCompiler(
- compiler, kwargs.get('destination') or defaultDest
+ compiler, kwargs.get('destination') or DEFAULT_DEST
)
diff --git a/pysnmp/smi/instrum.py b/pysnmp/smi/instrum.py
index f6940957..05c5c30b 100644
--- a/pysnmp/smi/instrum.py
+++ b/pysnmp/smi/instrum.py
@@ -200,7 +200,7 @@ class MibInstrumController(AbstractMibInstrumController):
self.lastBuildId = self.mibBuilder.lastBuildId
- debug.logger & debug.flagIns and debug.logger('__indexMib: rebuilt')
+ debug.logger & debug.FLAG_INS and debug.logger('__indexMib: rebuilt')
def flipFlopFsm(self, fsmTable, *varBinds, **context):
"""Read, modify, create or remove Managed Objects Instances.
@@ -275,19 +275,19 @@ class MibInstrumController(AbstractMibInstrumController):
count[0] += 1
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'_cbFun: var-bind %d, processed %d, expected %d' % (
idx, count[0], len(varBinds)))
if count[0] < len(varBinds):
return
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'_cbFun: finished, output var-binds %r' % (_varBinds,))
self.flipFlopFsm(fsmTable, *varBinds, **dict(context, cbFun=cbFun))
- debug.logger & debug.flagIns and debug.logger('flipFlopFsm: input var-binds %r' % (varBinds,))
+ debug.logger & debug.FLAG_INS and debug.logger('flipFlopFsm: input var-binds %r' % (varBinds,))
mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso')
@@ -306,7 +306,7 @@ class MibInstrumController(AbstractMibInstrumController):
self.__indexMib()
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'flipFlopFsm: current state %s, status %s' % (state, status))
try:
@@ -319,7 +319,7 @@ class MibInstrumController(AbstractMibInstrumController):
except KeyError:
raise error.SmiError('Unresolved FSM state %s, %s' % (state, status))
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'flipFlopFsm: state %s status %s -> transitioned into state %s' % (state, status, newState))
state = newState
@@ -352,7 +352,7 @@ class MibInstrumController(AbstractMibInstrumController):
instances=instances, errors=errors,
varBinds=_varBinds, nextName=None))
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'flipFlopFsm: func %s initiated for %r' % (actionFun, varBind))
@staticmethod
diff --git a/pysnmp/smi/mibs/SNMPv2-SMI.py b/pysnmp/smi/mibs/SNMPv2-SMI.py
index 03a085a1..68b2922a 100644
--- a/pysnmp/smi/mibs/SNMPv2-SMI.py
+++ b/pysnmp/smi/mibs/SNMPv2-SMI.py
@@ -512,7 +512,7 @@ class ManagedMibObject(ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readTest(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -533,7 +533,7 @@ class ManagedMibObject(ObjectType):
val = exval.noSuchInstance
except error.SmiError as exc:
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: exception %r' % (self, exc)))
if not node:
@@ -583,7 +583,7 @@ class ManagedMibObject(ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -604,7 +604,7 @@ class ManagedMibObject(ObjectType):
val = exval.noSuchInstance
except error.SmiError as exc:
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: exception %r' % (self, exc)))
if not node:
@@ -647,7 +647,7 @@ class ManagedMibObject(ObjectType):
val = exval.noSuchInstance
except error.SmiError as exc:
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: exception %r' % (self, exc)))
if not node:
@@ -714,7 +714,7 @@ class ManagedMibObject(ObjectType):
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readTestNext(%s, %r)' % (self, name, val)))
self._readNext('readTestNext', varBind, **context)
@@ -759,7 +759,7 @@ class ManagedMibObject(ObjectType):
In case of an error, the `error` key in the `context` dict will contain
an exception object.
"""
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
self._readNext('readGetNext', varBind, **context)
@@ -812,7 +812,7 @@ class ManagedMibObject(ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeTest(%s, %r)' % (self, name, val)))
try:
@@ -866,7 +866,7 @@ class ManagedMibObject(ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -930,7 +930,7 @@ class ManagedMibObject(ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCleanup(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -996,7 +996,7 @@ class ManagedMibObject(ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeUndo(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1151,7 +1151,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1221,7 +1221,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
acFun = context.get('acFun')
@@ -1290,7 +1290,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeTest(%s, %r)' % (self, name, val)))
acFun = context.get('acFun')
@@ -1352,7 +1352,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: createTest(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1365,7 +1365,7 @@ class MibScalar(ManagedMibObject):
acFun = context.get('acFun')
if acFun:
if self.maxAccess != 'readcreate' or acFun('write', varBind, **context):
- debug.logger & debug.flagACL and debug.logger(
+ debug.logger & debug.FLAG_ACL and debug.logger(
'createTest: %s=%r %s at %s' % (name, val, self.maxAccess, self.name))
exc = error.NoCreationError(name=name, idx=context.get('idx'))
cbFun(varBind, **dict(context, error=exc))
@@ -1429,7 +1429,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1488,7 +1488,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: createCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -1542,7 +1542,7 @@ class MibScalar(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: createUndo(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -1587,7 +1587,7 @@ class MibScalarInstance(ManagedMibObject):
#
def getValue(self, name, **context):
- debug.logger & debug.flagIns and debug.logger('getValue: returning %r for %s' % (self.syntax, self.name))
+ debug.logger & debug.FLAG_INS and debug.logger('getValue: returning %r for %s' % (self.syntax, self.name))
return self.syntax.clone()
def setValue(self, value, name, **context):
@@ -1601,7 +1601,7 @@ class MibScalarInstance(ManagedMibObject):
return self.syntax.clone(value)
except PyAsn1Error as exc:
- debug.logger & debug.flagIns and debug.logger('setValue: %s=%r failed with traceback %s' % (
+ debug.logger & debug.FLAG_INS and debug.logger('setValue: %s=%r failed with traceback %s' % (
self.name, value, traceback.format_exception(*sys.exc_info())))
if isinstance(exc, error.TableRowManagement):
raise exc
@@ -1678,7 +1678,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readTest(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1729,7 +1729,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readGet(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1788,7 +1788,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readTestNext(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1846,7 +1846,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: readGetNext(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1911,7 +1911,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeTest(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -1985,7 +1985,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -2037,7 +2037,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCleanup(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -2092,7 +2092,7 @@ class MibScalarInstance(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeUndo(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -2197,7 +2197,7 @@ class MibTableColumn(MibScalar, ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyTest(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -2213,7 +2213,7 @@ class MibTableColumn(MibScalar, ObjectType):
acFun = context.get('acFun')
if acFun:
if self.maxAccess != 'readcreate' or acFun('write', varBind, **context):
- debug.logger & debug.flagACL and debug.logger(
+ debug.logger & debug.FLAG_ACL and debug.logger(
'destroyTest: %s=%r %s at %s' % (name, val, self.maxAccess, self.name))
exc = error.NotWritableError(name=name, idx=context.get('idx'))
cbFun(varBind, **dict(context, error=exc))
@@ -2226,7 +2226,7 @@ class MibTableColumn(MibScalar, ObjectType):
pass
else:
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: terminated columnar instance %s creation' % (self, name)))
cbFun(varBind, **context)
@@ -2276,7 +2276,7 @@ class MibTableColumn(MibScalar, ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyCommit(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -2335,7 +2335,7 @@ class MibTableColumn(MibScalar, ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyCleanup(%s, %r)' % (self, name, val)))
self.branchVersionId += 1
@@ -2391,7 +2391,7 @@ class MibTableColumn(MibScalar, ObjectType):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: destroyUndo(%s, %r)' % (self, name, val)))
instances = context['instances'].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}})
@@ -2657,7 +2657,7 @@ class MibTableRow(ManagedMibObject):
mibObj, = mibBuilder.importSymbols(modName, mibSym)
mibObj.receiveManagementEvent(action, (baseIndices, val), **dict(context, cbFun=_cbFun))
- debug.logger & debug.flagIns and debug.logger('announceManagementEvent %s to %s' % (action, mibObj))
+ debug.logger & debug.FLAG_INS and debug.logger('announceManagementEvent %s to %s' % (action, mibObj))
def receiveManagementEvent(self, action, varBind, **context):
"""Apply mass operation on extending table's row.
@@ -2712,7 +2712,7 @@ class MibTableRow(ManagedMibObject):
parentIndices.append(syntax)
if instId:
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'receiveManagementEvent %s for suffix %s' % (action, instId))
self._manageColumns(action, (self.name + (0,) + instId, val), **context)
@@ -2789,7 +2789,7 @@ class MibTableRow(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: _manageColumns(%s, %s, %r)' % (self, action, name, val)))
cbFun = context['cbFun']
@@ -2841,7 +2841,7 @@ class MibTableRow(ManagedMibObject):
actionFun((colInstanceName, colInstanceValue),
**dict(context, acFun=acFun, cbFun=_cbFun))
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'_manageColumns: action %s name %s instance %s %svalue %r' % (
action, name, instId, name in indexVals and "index " or "", indexVals.get(name, val)))
@@ -2876,7 +2876,7 @@ class MibTableRow(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: _checkColumns(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -2912,7 +2912,7 @@ class MibTableRow(ManagedMibObject):
colObj.readGet((instName, None), **dict(context, cbFun=_cbFun))
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'%s: _checkColumns: checking instance %s' % (self, instName))
def writeTest(self, varBind, **context):
@@ -2963,7 +2963,7 @@ class MibTableRow(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeTest(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -3045,7 +3045,7 @@ class MibTableRow(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCommit(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -3131,7 +3131,7 @@ class MibTableRow(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeCleanup(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -3204,7 +3204,7 @@ class MibTableRow(ManagedMibObject):
"""
name, val = varBind
- (debug.logger & debug.flagIns and
+ (debug.logger & debug.FLAG_INS and
debug.logger('%s: writeUndo(%s, %r)' % (self, name, val)))
cbFun = context['cbFun']
@@ -3253,7 +3253,7 @@ class MibTableRow(ManagedMibObject):
try:
syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices)
except PyAsn1Error as exc:
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, exc))
indices = [instId]
instId = ()
diff --git a/pysnmp/smi/mibs/SNMPv2-TC.py b/pysnmp/smi/mibs/SNMPv2-TC.py
index 1367e936..f234a2f3 100644
--- a/pysnmp/smi/mibs/SNMPv2-TC.py
+++ b/pysnmp/smi/mibs/SNMPv2-TC.py
@@ -501,7 +501,7 @@ class RowStatus(TextualConvention, Integer):
newState = self.clone(newState)
- debug.logger & debug.flagIns and debug.logger(
+ debug.logger & debug.FLAG_INS and debug.logger(
'RowStatus state change from %r to %r produced new state %r, error indication %r' % (
self, value, newState, excValue))
diff --git a/pysnmp/smi/rfc1902.py b/pysnmp/smi/rfc1902.py
index 506434e9..35c9f628 100644
--- a/pysnmp/smi/rfc1902.py
+++ b/pysnmp/smi/rfc1902.py
@@ -79,14 +79,14 @@ class ObjectIdentity(object):
ObjectIdentity('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123)
"""
- stDirty, stClean = 1, 2
+ ST_DIRTY, ST_CLEAN = 1, 2
def __init__(self, *args, **kwargs):
self.__args = args
self.__kwargs = kwargs
self.__mibSourcesToAdd = self.__modNamesToLoad = None
self.__asn1SourcesToAdd = self.__asn1SourcesOptions = None
- self.__state = self.stDirty
+ self.__state = self.ST_DIRTY
self.__indices = self.__oid = self.__label = ()
self.__modName = self.__symName = ''
self.__mibNode = None
@@ -117,7 +117,7 @@ class ObjectIdentity(object):
>>>
"""
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__modName, self.__symName, self.__indices
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
@@ -144,7 +144,7 @@ class ObjectIdentity(object):
>>>
"""
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
@@ -180,19 +180,19 @@ class ObjectIdentity(object):
>>>
"""
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__label
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
def getMibNode(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__mibNode
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
def isFullyResolved(self):
- return self.__state & self.stClean
+ return self.__state & self.ST_CLEAN
#
# A gateway to MIBs manipulation routines
@@ -346,7 +346,7 @@ class ObjectIdentity(object):
"""
if self.__mibSourcesToAdd is not None:
- debug.logger & debug.flagMIB and debug.logger('adding MIB sources %s' % ', '.join(self.__mibSourcesToAdd))
+ debug.logger & debug.FLAG_MIB and debug.logger('adding MIB sources %s' % ', '.join(self.__mibSourcesToAdd))
mibViewController.mibBuilder.addMibSources(
*[ZipMibSource(x) for x in self.__mibSourcesToAdd]
)
@@ -356,7 +356,7 @@ class ObjectIdentity(object):
addMibCompiler(mibViewController.mibBuilder,
ifAvailable=True, ifNotAdded=True)
else:
- debug.logger & debug.flagMIB and debug.logger(
+ debug.logger & debug.FLAG_MIB and debug.logger(
'adding MIB compiler with source paths %s' % ', '.join(self.__asn1SourcesToAdd))
addMibCompiler(
mibViewController.mibBuilder,
@@ -370,11 +370,11 @@ class ObjectIdentity(object):
self.__asn1SourcesToAdd = self.__asn1SourcesOptions = None
if self.__modNamesToLoad is not None:
- debug.logger & debug.flagMIB and debug.logger('loading MIB modules %s' % ', '.join(self.__modNamesToLoad))
+ debug.logger & debug.FLAG_MIB and debug.logger('loading MIB modules %s' % ', '.join(self.__modNamesToLoad))
mibViewController.mibBuilder.loadModules(*self.__modNamesToLoad)
self.__modNamesToLoad = None
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self
MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar',
@@ -386,7 +386,7 @@ class ObjectIdentity(object):
self.__args[0].resolveWithMib(mibViewController)
if len(self.__args) == 1: # OID or label or MIB module
- debug.logger & debug.flagMIB and debug.logger('resolving %s as OID or label' % self.__args)
+ debug.logger & debug.FLAG_MIB and debug.logger('resolving %s as OID or label' % self.__args)
try:
# pyasn1 ObjectIdentifier or sequence of ints or string OID
self.__oid = rfc1902.ObjectName(self.__args[0]) # OID
@@ -421,7 +421,7 @@ class ObjectIdentity(object):
self.__oid
)
- debug.logger & debug.flagMIB and debug.logger(
+ debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r into prefix %r and suffix %r' % (self.__args, prefix, suffix))
modName, symName, _ = mibViewController.getNodeLocation(prefix)
@@ -437,7 +437,7 @@ class ObjectIdentity(object):
self.__mibNode = mibNode
- debug.logger & debug.flagMIB and debug.logger('resolved prefix %r into MIB node %r' % (prefix, mibNode))
+ debug.logger & debug.FLAG_MIB and debug.logger('resolved prefix %r into MIB node %r' % (prefix, mibNode))
if isinstance(mibNode, MibTableColumn): # table column
if suffix:
@@ -454,9 +454,9 @@ class ObjectIdentity(object):
else:
if suffix:
self.__indices = (rfc1902.ObjectName(suffix),)
- self.__state |= self.stClean
+ self.__state |= self.ST_CLEAN
- debug.logger & debug.flagMIB and debug.logger('resolved indices are %r' % (self.__indices,))
+ debug.logger & debug.FLAG_MIB and debug.logger('resolved indices are %r' % (self.__indices,))
return self
elif len(self.__args) > 1: # MIB, symbol[, index, index ...]
@@ -490,7 +490,7 @@ class ObjectIdentity(object):
)
self.__label = label
- debug.logger & debug.flagMIB and debug.logger(
+ debug.logger & debug.FLAG_MIB and debug.logger(
'resolved %r into prefix %r and suffix %r' % (self.__args, prefix, suffix))
if isinstance(mibNode, MibTableColumn): # table
@@ -515,16 +515,16 @@ class ObjectIdentity(object):
)
self.__oid += instId
self.__indices = (instId,)
- self.__state |= self.stClean
+ self.__state |= self.ST_CLEAN
- debug.logger & debug.flagMIB and debug.logger('resolved indices are %r' % (self.__indices,))
+ debug.logger & debug.FLAG_MIB and debug.logger('resolved indices are %r' % (self.__indices,))
return self
else:
raise SmiError('Non-OID, label or MIB symbol')
def prettyPrint(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
s = rfc1902.OctetString()
return '%s::%s%s%s' % (
self.__modName, self.__symName,
@@ -540,91 +540,91 @@ class ObjectIdentity(object):
# Redirect some attrs access to the OID object to behave alike
def __str__(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return str(self.__oid)
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __eq__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid == other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __ne__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid != other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __lt__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid < other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __le__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid <= other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __gt__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid > other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __ge__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid > other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __nonzero__(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid != 0
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __bool__(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return bool(self.__oid)
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __getitem__(self, i):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid[i]
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __len__(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return len(self.__oid)
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __add__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__oid + other
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __radd__(self, other):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return other + self.__oid
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __hash__(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return hash(self.__oid)
else:
raise SmiError('%s object not properly initialized' % self.__class__.__name__)
def __getattr__(self, attr):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
if attr in ('asTuple', 'clone', 'subtype', 'isPrefixOf',
'isSameTypeWith', 'isSuperTypeOf', 'getTagSet',
'getEffectiveTagSet', 'getTagMap', 'tagSet', 'index'):
@@ -693,16 +693,16 @@ class ObjectType(object):
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')
"""
- stDirty, stClean = 1, 2
+ ST_DIRTY, ST_CLEAM = 1, 2
def __init__(self, objectIdentity, objectSyntax=rfc1905.unSpecified):
if not isinstance(objectIdentity, ObjectIdentity):
raise SmiError('initializer should be ObjectIdentity instance, not %r' % (objectIdentity,))
self.__args = [objectIdentity, objectSyntax]
- self.__state = self.stDirty
+ self.__state = self.ST_DIRTY
def __getitem__(self, i):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAM:
return self.__args[i]
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
@@ -714,7 +714,7 @@ class ObjectType(object):
return '%s(%s)' % (self.__class__.__name__, ', '.join([repr(x) for x in self.__args]))
def isFullyResolved(self):
- return self.__state & self.stClean
+ return self.__state & self.ST_CLEAM
def addAsn1MibSource(self, *asn1Sources, **kwargs):
"""Adds path to a repository to search ASN.1 MIB files.
@@ -841,7 +841,7 @@ class ObjectType(object):
>>>
"""
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAM:
return self
self.__args[0].resolveWithMib(mibViewController)
@@ -853,14 +853,14 @@ class ObjectType(object):
(MibScalar, MibTableColumn)):
if not isinstance(self.__args[1], AbstractSimpleAsn1Item):
raise SmiError('MIB object %r is not OBJECT-TYPE (MIB not loaded?)' % (self.__args[0],))
- self.__state |= self.stClean
+ self.__state |= self.ST_CLEAM
return self
if isinstance(self.__args[1], (rfc1905.UnSpecified,
rfc1905.NoSuchObject,
rfc1905.NoSuchInstance,
rfc1905.EndOfMibView)):
- self.__state |= self.stClean
+ self.__state |= self.ST_CLEAM
return self
try:
@@ -873,14 +873,14 @@ class ObjectType(object):
if rfc1902.ObjectIdentifier().isSuperTypeOf(self.__args[1], matchConstraints=False):
self.__args[1] = ObjectIdentity(self.__args[1]).resolveWithMib(mibViewController)
- self.__state |= self.stClean
+ self.__state |= self.ST_CLEAM
- debug.logger & debug.flagMIB and debug.logger('resolved %r syntax is %r' % (self.__args[0], self.__args[1]))
+ debug.logger & debug.FLAG_MIB and debug.logger('resolved %r syntax is %r' % (self.__args[0], self.__args[1]))
return self
def prettyPrint(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAM:
return '%s = %s' % (self.__args[0].prettyPrint(),
self.__args[1].prettyPrint())
else:
@@ -951,7 +951,7 @@ class NotificationType(object):
NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3'), ObjectName('3.5'), {})
"""
- stDirty, stClean = 1, 2
+ ST_DIRTY, ST_CLEAN = 1, 2
def __init__(self, objectIdentity, instanceIndex=(), objects={}):
if not isinstance(objectIdentity, ObjectIdentity):
@@ -961,10 +961,10 @@ class NotificationType(object):
self.__objects = objects
self.__varBinds = []
self.__additionalVarBinds = []
- self.__state = self.stDirty
+ self.__state = self.ST_DIRTY
def __getitem__(self, i):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self.__varBinds[i]
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
@@ -1000,8 +1000,8 @@ class NotificationType(object):
>>>
"""
- debug.logger & debug.flagMIB and debug.logger('additional var-binds: %r' % (varBinds,))
- if self.__state & self.stClean:
+ debug.logger & debug.FLAG_MIB and debug.logger('additional var-binds: %r' % (varBinds,))
+ if self.__state & self.ST_CLEAN:
raise SmiError('%s object is already sealed' % self.__class__.__name__)
else:
self.__additionalVarBinds.extend(varBinds)
@@ -1097,7 +1097,7 @@ class NotificationType(object):
return self
def isFullyResolved(self):
- return self.__state & self.stClean
+ return self.__state & self.ST_CLEAN
def resolveWithMib(self, mibViewController):
"""Perform MIB variable ID conversion and notification objects expansion.
@@ -1137,7 +1137,7 @@ class NotificationType(object):
>>>
"""
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return self
self.__objectIdentity.resolveWithMib(mibViewController)
@@ -1164,7 +1164,7 @@ class NotificationType(object):
)
varBindsLocation[objectIdentity] = len(self.__varBinds) - 1
else:
- debug.logger & debug.flagMIB and debug.logger(
+ debug.logger & debug.FLAG_MIB and debug.logger(
'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not loaded?)' % (self.__objectIdentity,))
for varBinds in self.__additionalVarBinds:
@@ -1178,14 +1178,14 @@ class NotificationType(object):
self.__additionalVarBinds = []
- self.__state |= self.stClean
+ self.__state |= self.ST_CLEAN
- debug.logger & debug.flagMIB and debug.logger('resolved %r into %r' % (self.__objectIdentity, self.__varBinds))
+ debug.logger & debug.FLAG_MIB and debug.logger('resolved %r into %r' % (self.__objectIdentity, self.__varBinds))
return self
def prettyPrint(self):
- if self.__state & self.stClean:
+ if self.__state & self.ST_CLEAN:
return ' '.join(['%s = %s' % (x[0].prettyPrint(), x[1].prettyPrint()) for x in self.__varBinds])
else:
raise SmiError('%s object not fully initialized' % self.__class__.__name__)
diff --git a/pysnmp/smi/view.py b/pysnmp/smi/view.py
index 223e22d8..46e74d8a 100644
--- a/pysnmp/smi/view.py
+++ b/pysnmp/smi/view.py
@@ -33,7 +33,7 @@ class MibViewController(object):
if self.lastBuildId == self.mibBuilder.lastBuildId:
return
- debug.logger & debug.flagMIB and debug.logger('indexMib: re-indexing MIB view')
+ debug.logger & debug.FLAG_MIB and debug.logger('indexMib: re-indexing MIB view')
MibScalarInstance, = self.mibBuilder.importSymbols(
'SNMPv2-SMI', 'MibScalarInstance'
@@ -210,7 +210,7 @@ class MibViewController(object):
str='Can\'t resolve node name %s::%s at %s' %
(modName, nodeName, self)
)
- debug.logger & debug.flagMIB and debug.logger(
+ debug.logger & debug.FLAG_MIB and debug.logger(
'getNodeNameByOid: resolved %s:%s -> %s.%s' % (modName, nodeName, label, suffix))
return oid, label, suffix
@@ -226,7 +226,7 @@ class MibViewController(object):
raise error.NoSuchObjectError(
str='No such symbol %s::%s at %s' % (modName, nodeName, self)
)
- debug.logger & debug.flagMIB and debug.logger(
+ debug.logger & debug.FLAG_MIB and debug.logger(
'getNodeNameByDesc: resolved %s:%s -> %s' % (modName, nodeName, oid))
return self.getNodeNameByOid(oid, modName)