summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGES22
-rw-r--r--README15
-rw-r--r--docs/pysnmp-tutorial.html285
-rw-r--r--examples/smi/backend.py28
-rw-r--r--examples/smi/instrum.py4
-rw-r--r--examples/smi/view.py54
-rw-r--r--examples/v1arch/agent/cmdrsp.py16
-rw-r--r--examples/v1arch/manager/bulkgen.py82
-rw-r--r--examples/v1arch/manager/getgen.py6
-rw-r--r--examples/v1arch/manager/nextgen.py15
-rw-r--r--examples/v1arch/manager/ntfrcv.py24
-rw-r--r--examples/v1arch/manager/setgen.py6
-rw-r--r--examples/v3arch/agent/ntforg.py2
-rw-r--r--examples/v3arch/manager/bulkgen.py9
-rw-r--r--examples/v3arch/manager/getgen.py6
-rw-r--r--examples/v3arch/manager/nextgen.py7
-rw-r--r--examples/v3arch/manager/ntfrcv.py5
-rw-r--r--examples/v3arch/manager/setgen.py9
-rw-r--r--examples/v3arch/oneliner/manager/async/nextgen.py20
-rw-r--r--examples/v3arch/oneliner/manager/bulkgen.py7
-rw-r--r--examples/v3arch/oneliner/manager/getgen.py7
-rw-r--r--examples/v3arch/oneliner/manager/nextgen.py7
-rw-r--r--examples/v3arch/oneliner/manager/setgen.py7
-rw-r--r--examples/v3arch/oneliner/manager/withmib/nextgen.py11
-rw-r--r--examples/v3arch/oneliner/manager/withmib/setgen.py11
-rw-r--r--examples/v3arch/proxy/cmdproxy.py9
-rw-r--r--examples/v3arch/twisted/agent/ntforg.py5
-rw-r--r--examples/v3arch/twisted/manager/bulkgen.py10
-rw-r--r--examples/v3arch/twisted/manager/getgen.py11
-rw-r--r--examples/v3arch/twisted/manager/nextgen.py10
-rw-r--r--examples/v3arch/twisted/manager/ntfrcv.py5
-rw-r--r--examples/v3arch/twisted/manager/setgen.py11
-rw-r--r--pysnmp/__init__.py2
-rw-r--r--pysnmp/cache.py8
-rw-r--r--pysnmp/carrier/asynsock/base.py4
-rw-r--r--pysnmp/carrier/asynsock/dgram/base.py28
-rw-r--r--pysnmp/carrier/base.py10
-rw-r--r--pysnmp/carrier/twisted/dgram/base.py10
-rw-r--r--pysnmp/carrier/twisted/dgram/udp.py11
-rw-r--r--pysnmp/carrier/twisted/dgram/unix.py11
-rw-r--r--pysnmp/carrier/twisted/dispatch.py8
-rw-r--r--pysnmp/entity/config.py20
-rw-r--r--pysnmp/entity/rfc3413/cmdgen.py33
-rw-r--r--pysnmp/entity/rfc3413/cmdrsp.py88
-rw-r--r--pysnmp/entity/rfc3413/config.py3
-rw-r--r--pysnmp/entity/rfc3413/context.py9
-rw-r--r--pysnmp/entity/rfc3413/mibvar.py21
-rw-r--r--pysnmp/entity/rfc3413/ntforg.py11
-rw-r--r--pysnmp/entity/rfc3413/ntfrcv.py9
-rw-r--r--pysnmp/entity/rfc3413/oneliner/cmdgen.py82
-rw-r--r--pysnmp/entity/rfc3413/oneliner/ntforg.py9
-rw-r--r--pysnmp/entity/rfc3413/twisted/cmdgen.py11
-rw-r--r--pysnmp/entity/rfc3413/twisted/ntforg.py5
-rw-r--r--pysnmp/error.py2
-rw-r--r--pysnmp/nextid.py4
-rw-r--r--pysnmp/proto/acmod/rfc3415.py4
-rw-r--r--pysnmp/proto/api/v1.py8
-rw-r--r--pysnmp/proto/cache.py2
-rw-r--r--pysnmp/proto/errind.py16
-rw-r--r--pysnmp/proto/mpmod/cache.py6
-rw-r--r--pysnmp/proto/mpmod/rfc2576.py13
-rw-r--r--pysnmp/proto/mpmod/rfc3412.py20
-rw-r--r--pysnmp/proto/proxy/rfc2576.py2
-rw-r--r--pysnmp/proto/rfc1155.py57
-rw-r--r--pysnmp/proto/rfc1902.py50
-rw-r--r--pysnmp/proto/rfc1905.py2
-rw-r--r--pysnmp/proto/rfc3412.py26
-rw-r--r--pysnmp/proto/secmod/eso/priv/des3.py53
-rw-r--r--pysnmp/proto/secmod/rfc2576.py5
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py46
-rw-r--r--pysnmp/proto/secmod/rfc3414/auth/hmacsha.py44
-rw-r--r--pysnmp/proto/secmod/rfc3414/localkey.py13
-rw-r--r--pysnmp/proto/secmod/rfc3414/priv/des.py33
-rw-r--r--pysnmp/proto/secmod/rfc3414/service.py25
-rw-r--r--pysnmp/proto/secmod/rfc3826/priv/aes.py62
-rw-r--r--pysnmp/smi/builder.py44
-rw-r--r--pysnmp/smi/indices.py29
-rw-r--r--pysnmp/smi/instrum.py34
-rw-r--r--pysnmp/smi/mibs/PYSNMP-MIB.py4
-rw-r--r--pysnmp/smi/mibs/PYSNMP-USM-MIB.py6
-rw-r--r--pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py24
-rw-r--r--pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py29
-rw-r--r--pysnmp/smi/mibs/SNMP-MPD-MIB.py13
-rw-r--r--pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py22
-rw-r--r--pysnmp/smi/mibs/SNMP-PROXY-MIB.py74
-rw-r--r--pysnmp/smi/mibs/SNMP-TARGET-MIB.py29
-rw-r--r--pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py33
-rw-r--r--pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py16
-rw-r--r--pysnmp/smi/mibs/SNMP-USM-AES-MIB.py4
-rw-r--r--pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py17
-rw-r--r--pysnmp/smi/mibs/SNMPv2-CONF.py9
-rw-r--r--pysnmp/smi/mibs/SNMPv2-MIB.py47
-rw-r--r--pysnmp/smi/mibs/SNMPv2-SMI.py196
-rw-r--r--pysnmp/smi/mibs/SNMPv2-TC.py41
-rw-r--r--pysnmp/smi/mibs/SNMPv2-TM.py13
-rw-r--r--pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py46
-rw-r--r--pysnmp/smi/mibs/instances/__SNMPv2-MIB.py2
-rw-r--r--pysnmp/smi/view.py41
-rw-r--r--setup.py36
-rw-r--r--tools/libsmi2pysnmp269
100 files changed, 1521 insertions, 1169 deletions
diff --git a/CHANGES b/CHANGES
index daba690..ceb96e9 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,3 +1,25 @@
+Revision 4.2.1
+--------------
+
+- Support string OIDs at one-liner API.
+- Code quality of libsmi2pysnmp tool improved, MIBs re-built.
+- SNMP-PROXY-MIB & SNMP-USER-BASED-SM-3DES-MIB added
+- v1arch bulkgen.py example added
+- Major overhawl for Python 2.4 -- 3.2 compatibility:
+ + get rid of old-style types
+ + drop string module usage
+ + switch to rich comparation
+ + drop explicit long integer type use
+ + map()/filter() replaced with list comprehension
+ + apply() replaced with */**args
+ + dictionary operations made 2K/3K compatible
+ + division operator made 2K/3K compatible
+ + sorting function now operates on key
+ + iterators returned by some funcs in py3k converted to lists
+ + exception syntax made 2K/3K compatible
+ + tuple function arguments resolved to scalars to become py3k compatible
+ + BER octetstream is now of type bytes (Py3k) or still string (Py2k)
+
Revision 4.1.16d
----------------
diff --git a/README b/README
index 8c0afcc..112c9f6 100644
--- a/README
+++ b/README
@@ -2,8 +2,8 @@
PYTHON SNMP FRAMEWORK
---------------------
-This is a beta-quality revision of pure-Python, open source and free
-implementation of v1/v2c/v3 SNMP engine.
+This is a pure-Python, open source and free implementation of v1/v2c/v3
+SNMP engine.
The PySNMP project has been sponsored by a PSF grant [10]. Thanks!
@@ -20,7 +20,7 @@ FEATURES
* Twisted (http://twistedmatrix.com) integration
* IPv6 transport support
* Python eggs and py2exe friendly
-* 100% Python, works with Python 2.2 though 2.7
+* 100% Python, works with Python 2.4 though 3.2
* MT-safe (only if run locally to a thread)
Features, specific to SNMPv3 model include:
@@ -42,9 +42,10 @@ MISFEATURES
INSTALLATION
------------
-The PySNMP package uses distutils for package management. The PyASN1 [8]
+The PySNMP package uses setuptools for package management. The PyASN1 [8]
package is required. For secure SNMPv3 communication, PyCrypto [9]
-should also be installed.
+should also be installed. In case of Python 3, a SVN version of Python 3
+compliant release of PyCrypto is needed.
OPERATION
---------
@@ -156,8 +157,8 @@ REFERENCES
[8] PyASN1 project homepage:
http://pyasn1.sf.net
-[9] PyCrypto project:
- http://www.amk.ca/python/code/crypto.html
+[9] PyCrypto package:
+ http://pycrypto.org
[10] Python Software Foundation
http://www.python.org/psf/
diff --git a/docs/pysnmp-tutorial.html b/docs/pysnmp-tutorial.html
index 5ecb657..6812aff 100644
--- a/docs/pysnmp-tutorial.html
+++ b/docs/pysnmp-tutorial.html
@@ -6,12 +6,12 @@
<BODY BGCOLOR="#ffffff" TEXT="#000000"
LINK="#0000bb" VLINK="#551a8b" ALINK="#ff0000">
<FONT SIZE=2 FACE="arial, helvetica">
-<TABLE ALIGN="CENTER" WIDTH="70%"><TR><TD><TABLE ALIGN="LEFT"><TR><TD>
+<TABLE ALIGN="CENTER" WIDTH="60%"><TR><TD><TABLE ALIGN="LEFT"><TR><TD>
<H4>
PySNMP tutorial
</H4>
-<I>by <A HREF=mailto:ilya@glas.net>Ilya Etingof</A>, Nov 2007</I>
+<I>by <A HREF=mailto:ilya@glas.net>Ilya Etingof</A>, 2007-2011</I>
<P><B>Table of contents</B></P>
<UL>
@@ -27,12 +27,12 @@ PySNMP tutorial
<LI><A HREF="#SYNCH-ONELINER-APPS">2.1.1 Synchronous Applications</A>
<UL>
<LI><A HREF="#CommandGenerator">2.1.1.1 Command Generator</A>
-<LI><A HREF="#NotificationOriginator">2.1.1.2 Notification Originator</A
+<LI><A HREF="#NotificationOriginator">2.1.1.2 Notification Originator</A>
</UL>
<LI><A HREF="#ASYNCH-ONELINER-APPS">2.1.2 Asynchronous Applications</A>
<UL>
<LI><A HREF="#AsynCommandGenerator">2.1.2.1 Asynchronous Command Generator</A>
-<LI><A HREF="#AsynNotificationOriginator">2.1.2.2 Asynchronous Notification Originator</A
+<LI><A HREF="#AsynNotificationOriginator">2.1.2.2 Asynchronous Notification Originator</A>
</UL>
<LI><A HREF="#SECURITY-CONFIGURATION">2.1.3 Security configuration</A>
<UL>
@@ -88,7 +88,7 @@ configuration facilities.
<P>
For any information to be exchanged between entities, some agreement on
-information format and transmission procedure should be settled beforehand.
+information format and transmission procedure needs to be settled beforehand.
This is what is conventionally called a <STRONG>Protocol</STRONG>.
</P>
@@ -108,8 +108,8 @@ in a reasonably short period of time, an important feature of a network
management software would be <STRONG>Performance</STRONG>.
<P>
-Some of network devices may run on strictly limited resources what require
-another property of network management facility:
+Some of network devices may run on severely limited resources what invokes
+another property of a proper network management facility:
<STRONG>Low resource consumption</STRONG>.
</P>
@@ -132,7 +132,7 @@ be at least authentic and sometimes hidden from possible observers.
</P>
<P>
-All these problems were approached many times during about three decades
+All these problems were approached many times through about three decades
of networking history. Some solutions collapsed over time for one reason or
another, while others, such as Simple Network Management Protocol (SNMP),
evolve into an industry standard.
@@ -363,7 +363,7 @@ applications are Manager, Agent and Proxy (
<P>
PySNMP stands for a pure-Python SNMP implementation. This software deals with
-darkest corners of SNMP specifications all in Python programming language.
+the darkest corners of SNMP specifications all in Python programming language.
</P>
<P>
@@ -486,7 +486,7 @@ of all kinds.
<P>
Transport subsystem is used for sending SNMP messages to and accepting them
-from network. The I/O subsystem consists of a an abstract Dispatcher and one
+from network. The I/O subsystem consists of an abstract Dispatcher and one
or more abstract Transport classes. Concrete Dispatcher implementation
is I/O method-specific, consider BSD sockets for example. Concrete Transport
classes are transport domain-specific. SNMP frequently uses UDP Transport
@@ -578,7 +578,7 @@ Methods of the <STRONG>CommandGenerator</STRONG> class instances implement
specific request types.
</P>
-<A NAME="CommandGenerator.setCmd"></A>
+<A NAME="CommandGenerator.getCmd"></A>
<DL>
<DT><STRONG>getCmd</STRONG>(
<STRONG>authData</STRONG>,
@@ -596,8 +596,8 @@ The <STRONG>authData</STRONG> is a
SNMP <A HREF="#UsmUserData">Security Parameters object</A>,
<STRONG>transportTarget</STRONG> is a SNMP
<A HREF="#UdpTransportTarget">Transport Configuration object</A>
-and <STRONG>*varNames</STRONG> are Managed Objects names
-(ASN.1 <A HREF="#OID-IMPL">OID</A>s).
+and <STRONG>*varNames</STRONG> is a sequence of
+<A HREF="#MANAGED-OBJECT-NAME-VALUE">Managed Objects names</A>.
</P>
<P>
@@ -615,18 +615,18 @@ error.
<P>
The pair of <STRONG>errorStatus</STRONG> and <STRONG>errorIndex</STRONG>
-variables determines SNMP PDU-level error. If <STRONG>errorStatus</STRONG>
-evaluates to true, this indicates SNMP PDU error caused by Managed Object
-at position <STRONG>errorIndex</STRONG>-1 in <STRONG>varBinds</STRONG>.
+variables determines SNMP PDU-level error. These are instances of pyasn1
+<A HREF="http://pyasn1.sourceforge.net/#1.1.3">Integer class</A>.
+If <STRONG>errorStatus</STRONG> evaluates to true, this indicates SNMP PDU
+error caused by Managed Object at position <STRONG>errorIndex</STRONG>-1
+in <STRONG>varBinds</STRONG>.
Doing <STRONG>errorStatus.prettyPrint</STRONG>() would return an
explanatory text error message.
</P>
<P>
-The <STRONG>varBinds</STRONG> is a tuple of Managed Objects. Managed Objects
-found in response are position-bound to Managed Object names passed in request.
-Each Managed Object is a tuple of <STRONG>Object Name</STRONG> and
-<STRONG>Object Value</STRONG>.
+The <STRONG>varBinds</STRONG> is a tuple of <A HREF="#MANAGED-OBJECT-NAME-VALUE">Managed Objects</A>. Those found in response are bound by position to
+Managed Object names passed in request.
</P>
</DD>
</DL>
@@ -641,14 +641,16 @@ The following code performs SNMP GET operation over SNMPv1:
>>> errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
... cmdgen.CommunityData('my-agent', 'public', 0),
... cmdgen.UdpTransportTarget(('localhost', 161)),
-... (1,3,6,1,2,1,1,1,0)
+... '1.3.6.1.2.1.1.1.0',
+... '1.3.6.1.2.1.1.2.0'
... )
->>> print errorIndication
+>>> print(errorIndication)
None
->>> print errorStatus
+>>> print(errorStatus)
0
->>> print varBinds
-[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux my.domain.com 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
+>>> print(varBinds)
+[(ObjectName(1.3.6.1.2.1.1.1.0), OctetString('Linux saturn 2.6.37.6-smp #2 SMP Sat Apr 9 23:39:07 CDT 2011 i686')),
+(ObjectName(1.3.6.1.2.1.1.2.0), ObjectIdentifier(1.3.6.1.4.1.8072.3.2.10))]
</PRE>
</TD></TR></TABLE>
@@ -667,13 +669,15 @@ Perform SNMP SET request and return a response or error indication.
<P>
The <STRONG>authData</STRONG> and <STRONG>transportTarget</STRONG> parameters
-have he same semantics as in <STRONG>getCmd</STRONG> method.
+have he same semantics as in <A HREF="#CommandGenerator.getCmd">getCmd</A>
+method.
</P>
<P>
-The <STRONG>*varBinds</STRONG> input parameter is a tuple of Managed
-Objects to be applied at Agent. The syntax of <STRONG>*varBinds</STRONG>
-is the same as in <STRONG>getCmd</STRONG>.
+The <STRONG>*varBinds</STRONG> input parameter is a sequence of
+Managed Objects to be applied at Agent. The syntax of
+<STRONG>*varBinds</STRONG> is the same as in
+<A HREF="#CommandGenerator.getCmd">getCmd</A> method.
</P>
<P>
@@ -687,7 +691,7 @@ The <STRONG>setCmd</STRONG> method returns a tuple of
<P>
The <STRONG>errorIndication</STRONG>, <STRONG>errorStatus</STRONG> and
<STRONG>errorIndex</STRONG> parameters have the same meaning as in
-<STRONG>getCmd</STRONG> method.
+<A HREF="#CommandGenerator.getCmd">getCmd</A> method.
</P>
</DD>
@@ -706,11 +710,11 @@ The following code performs SNMP SET operation over SNMPv2c:
... cmdgen.UdpTransportTarget(('localhost', 161)),
... ((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('my system description'))
... )
->>> print errorIndication
+>>> print(errorIndication)
None
->>> print errorStatus
+>>> print(errorStatus)
17
->>> print errorStatus.prettyPrint()
+>>> print(errorStatus.prettyPrint())
notWritable(17)
</PRE>
</TD></TR></TABLE>
@@ -732,7 +736,7 @@ Names are next to those used in request.
<P>
Input parameters to the <STRONG>nextCmd</STRONG> method are the same as to
-<STRONG>getCmd</STRONG>.
+<A HREF="#CommandGenerator.getCmd">getCmd</A>.
</P>
<P>
@@ -746,7 +750,7 @@ The <STRONG>nextCmd</STRONG> method returns a tuple of
<P>
The <STRONG>errorIndication</STRONG>, <STRONG>errorStatus</STRONG> and
<STRONG>errorIndex</STRONG> parameters have the same meaning as in
-<STRONG>getCmd</STRONG> method.
+<A HREF="#CommandGenerator.getCmd">getCmd</A> method.
</P>
<P>
@@ -761,8 +765,21 @@ a sequence of Managed Objects so that Object Name passed in request would
be a prefix for Object Names returned in response (as a side note, the same
method in Applications API would return <STRONG>varBinds</STRONG> as held
in a single response, and regardless of the prefix property).
+</P>
+
+<P>
+It's also possible to modify the above behaviour so that the
+<STRONG>varBindTable</STRONG> returned would contain *all*
+Managed Objects from those passed in request up till the end of
+the list of available Managed Objects at the Agent. This option
+is enabled by setting the <STRONG>lexicographicMode</STRONG>
+attribute of the <STRONG>CommandGenerator</STRONG> class instance
+to True.
+</P>
+
+<P>
Properties of the <STRONG>varBinds</STRONG> parameter is the same as in
-<STRONG>getCmd</STRONG> method.
+<A HREF="#CommandGenerator.getCmd">getCmd</A> method.
</P>
</DD>
</DL>
@@ -780,14 +797,14 @@ over SNMPv3:
... cmdgen.UdpTransportTarget(('localhost', 161)),
... (1,3,6,1,2,1,1)
... )
->>> print errorIndication
+>>> print(errorIndication)
None
->>> print errorStatus
+>>> print(errorStatus)
0
>>> for varBindTableRow in varBindTable:
-... print varBindTableRow
+... print(varBindTableRow)
...
-[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux my.domain.com 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
+[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux saturn 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
[(ObjectName('1.3.6.1.2.1.1.2.0'), ObjectIdentifier('1.3.6.1.4.1.8072.3.2.10'))]
[ skipped ]
[(ObjectName('1.3.6.1.2.1.1.9.1.4.9'), TimeTicks('17'))]
@@ -841,7 +858,7 @@ The <STRONG>bulkCmd</STRONG> method returns a tuple of
<P>
The <STRONG>errorIndication</STRONG>, <STRONG>errorStatus</STRONG>,
<STRONG>errorIndex</STRONG> and <STRONG>varBindTable</STRONG> parameters have
-the same meaning as in <STRONG>getCmd</STRONG> method.
+the same meaning as in <A HREF="#CommandGenerator.getCmd">getCmd</A> method.
</P>
</DD>
</DL>
@@ -860,14 +877,14 @@ over SNMPv3:
... 0, 25, # nonRepeaters, maxRepetitions
... (1,3,6,1,2,1,1)
... )
->>> print errorIndication
+>>> print(errorIndication)
None
->>> print errorStatus
+>>> print(errorStatus)
0
>>> for varBindTableRow in varBindTable:
-... print varBindTableRow
+... print(varBindTableRow)
...
-[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux my.domain.com 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
+[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux saturn 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
[(ObjectName('1.3.6.1.2.1.1.2.0'), ObjectIdentifier('1.3.6.1.4.1.8072.3.2.10'))]
[ skipped ]
[(ObjectName('1.3.6.1.2.1.1.9.1.4.9'), TimeTicks('17'))]
@@ -912,7 +929,8 @@ and possibly return an error indication.
<P>
The <STRONG>authData</STRONG> and <STRONG>transportTarget</STRONG> parameters
-have the same semantics as in <STRONG>CommandGenerator.getCmd</STRONG> method.
+have the same semantics as in <A HREF="#CommandGenerator.getCmd">getCmd</A>
+method.
</P>
<P>
@@ -938,13 +956,13 @@ is a value of coldStart notification type as defined in SNMPv2-MIB module.
The <STRONG>*varBinds</STRONG> input parameter is a tuple of Managed
Objects to be passed over to Manager along with Notification. The syntax
of <STRONG>*varBinds</STRONG> is the same as in
-<STRONG>CommandGenerator.getCmd</STRONG>.
+<A HREF="#CommandGenerator.getCmd">getCmd</A>
</P>
<P>
The <STRONG>sendNotification</STRONG> method returns an
<STRONG>errorIndication</STRONG> parameter which has the same meaning as
-in <STRONG>CommandGenerator.getCmd</STRONG>.
+in <A HREF="#CommandGenerator.getCmd">getCmd</A> method.
</P>
</DD>
@@ -965,9 +983,9 @@ The following code sends SNMP TRAP over SNMPv3:
... (('SNMPv2-MIB', 'coldStart'),),
... ((1,3,6,1,2,1,1,3,0), v2c.TimeTicks(44100))
)
->>> print errorIndication
+>>> print(errorIndication)
None
->>> print errorStatus
+>>> print(errorStatus)
0
</PRE>
</TD></TR></TABLE>
@@ -1054,7 +1072,7 @@ through response methods.
<P>
The <STRONG>errorIndication</STRONG>, <STRONG>errorStatus</STRONG>,
<STRONG>errorIndex</STRONG> and <STRONG>varBinds</STRONG> parameters
-have the same meaning as in <A HREF="#getCmd">CommandGenerator.getCmd</A>
+have the same meaning as in <A HREF="#CommandGenerator.getCmd">getCmd</A>
method.
</P>
@@ -1068,7 +1086,7 @@ it must return a true value. Otherwise, it returns false.
<P>
The <STRONG>authData</STRONG>, <STRONG>transportTarget</STRONG> and
<STRONG>varNames</STRONG> parameters have the same meaning as in
-<A HREF="#CommandGenerator.getCmd">CommandGenerator.getCmd</A>
+<A HREF="#CommandGenerator.getCmd">getCmd</A>
method.
</P>
@@ -1098,7 +1116,7 @@ Prepare SNMP SET request to be dispatched. Return the
<P>
The <STRONG>authData</STRONG> and <STRONG>transportTarget</STRONG>
parameters have the same meaning as in
-<A HREF="#CommandGenerator.setCmd">CommandGenerator.setCmd</A> method.
+<A HREF="#CommandGenerator.getCmd">CommandGenerator.getCmd</A> method.
</P>
<P>
@@ -1223,11 +1241,11 @@ SNMPv3:
>>> from pysnmp.entity.rfc3413.oneliner import cmdgen
>>>
>>> def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx):
-... print 'sendRequestHandle =', sendRequestHandle
-... print 'errorIndication =', errorIndication
-... print 'errorStatus =', errorStatus
-... print 'varBinds =', varBinds
-... print 'cbCtx =', cbCtx
+... print('sendRequestHandle = %d' % sendRequestHandle)
+... print('errorIndication = %s' % errorIndication)
+... print('errorStatus = %s' % errorStatus)
+... print('varBinds = %s' % (varBinds,))
+... print('cbCtx = %s' % cbCtx)
...
>>> asynCommandGenerator = cmdgen.AsynCommandGenerator()
>>> # This is a non-blocking call
@@ -1236,13 +1254,13 @@ SNMPv3:
... cmdgen.UdpTransportTarget(('localhost', 161)),
... ((1,3,6,1,2,1,1,1,0),),
... (cbFun, None))
->>> print sendRequestHandle
+>>> print(sendRequestHandle)
1
>>> asynCommandGenerator.snmpEngine.transportDispatcher.runDispatcher()
sendRequestHandle = 1
errorIndication = None
errorStatus = 0
-varBinds = [(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux my.domain.com 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
+varBinds = [(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux saturn 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]
cbCtx = None
>>>
</PRE>
@@ -1370,9 +1388,9 @@ SNMPv3:
>>> from pysnmp.proto.api import v2c
>>>
>>> def cbFun(sendRequestHandle, errorIndication, cbCtx):
-... print 'sendRequestHandle =', sendRequestHandle
-... print 'errorIndication =', errorIndication
-... print 'cbCtx =', cbCtx
+... print('sendRequestHandle = %d' % sendRequestHandle)
+... print('errorIndication = %s' % errorIndication)
+... print('cbCtx = %s' % (cbCtx,))
...
>>> asynNotificationOriginator = ntforg.AsynNotificationOriginator()
>>> # This is a non-blocking call
@@ -1383,7 +1401,7 @@ SNMPv3:
... ('SNMPv2-MIB', 'coldStart'),
... ((1,3,6,1,2,1,1,1,0), v2c.TimeTicks(44100)),
... (cbFun, None))
->>> print sendRequestHandle
+>>> print(sendRequestHandle)
1
>>> asynNotificationOriginator.snmpEngine.transportDispatcher.runDispatcher()
sendRequestHandle = 1
@@ -1450,20 +1468,33 @@ means of further <STRONG>authProtocol</STRONG> and/or
<P>
Optional <STRONG>authProtocol</STRONG> parameter may be used to specify
-non-default hash function algorithm. Possible values include
-<STRONG>usmHMACMD5AuthProtocol</STRONG>,
-<STRONG>usmHMACSHAAuthProtocol</STRONG> and
-<STRONG>usmNoAuthProtocol</STRONG>. These symbols are defined in
-<STRONG>pysnmp.entity.rfc3413.oneliner.cmdgen</STRONG> module.
+non-default hash function algorithm. Possible values include:
</P>
+<UL>
+<LI><STRONG>usmHMACMD5AuthProtocol</STRONG> -- MD5-based authentication protocol
+<LI><STRONG>usmHMACSHAAuthProtocol</STRONG> -- SHA-based authentication protocol
+<LI><STRONG>usmNoAuthProtocol</STRONG> -- no authentication to use
+</UL>
<P>
Optional <STRONG>privProtocol</STRONG> parameter may be used to specify
-non-default ciphering algorithm. Possible values include
-<STRONG>usmDESPrivProtocol</STRONG>,
-<STRONG>usmAesCfb128Protocol</STRONG>, and
-<STRONG>usmNoPrivProtocol</STRONG>.
+non-default ciphering algorithm. Possible values include:
</P>
+<P>
+<UL>
+<LI><STRONG>usmDESPrivProtocol</STRONG> -- DES-based encryption protocol
+<LI><STRONG>usmAesCfb128Protocol</STRONG> -- AES128-based encryption protocol (<A HREF="http://www.ietf.org/rfc/rfc3826.txt">RFC3826</A>)
+<LI><STRONG>usm3DESEDEPrivProtocol</STRONG> -- triple DES-based encryption protocol (<A HREF="http://www.snmp.com/protocol/eso.shtml">Extended Security Options</A>)
+<LI><STRONG>usmAesCfb192Protocol</STRONG> -- AES192-based encryption protocol (<A HREF="http://www.snmp.com/protocol/eso.shtml">Extended Security Options</A>)
+<LI><STRONG>usmAesCfb256Protocol</STRONG> -- AES256-based encryption protocol (<A HREF="http://www.snmp.com/protocol/eso.shtml">Extended Security Options</A>)
+<LI><STRONG>usmNoPrivProtocol</STRONG> -- no encryption to use
+</UL>
+
+<P>
+All these symbols are defined in
+<STRONG>pysnmp.entity.rfc3413.oneliner.cmdgen</STRONG> module.
+</P>
+
</DD>
</DL>
@@ -1539,62 +1570,34 @@ of succesive request retries (5 times).
<A NAME="OIDVAL-IMPL">
<P>
-In PySNMP programming context, <A HREF="#MANAGED-OBJECTS">
-Managed Object</A> term (also called <STRONG>Variable-Binding</STRONG> in
-protocol specifications) refers to a tuple of Managed Object (or
-Managed Object Instance) Name and Managed Object Instance Value.
+At the protocol level, each <A HREF="#MANAGED-OBJECTS">Managed Object</A>
+instance is represented by a pair of Name and Value collectively called
+a <STRONG>Variable-Binding</STRONG>.
</P>
<P>
-Managed Objects Names and Values are <A HREF="#ASN1">ASN.1</A> types.
-Both Names and Values are derived from
-<A HREF="http://pyasn1.sf.net">PyASN1</A> classes. These are defined in
-<STRONG>pysnmp.proto.rfc1902</STRONG> module.
+In PySNMP programming context, at the high-level API, each Managed Object is
+represented by a tuple of two class instances -- one represents Managed
+Object Instance Name, and another -- its value.
</P>
<A NAME="OID-IMPL">
<P>
-Managed Object Name is a tuple or tuple-like
-<A HREF="#OID">Object Identifier</A> class instance.
+Managed Object Name is an instance of <STRONG>ObjectName</STRONG> class,
+which is derived from PyASN1
+<A HREF="http://pyasn1.sourceforge.net/#1.1.8">ObjectIdentifier</A>.
+In most cases, PySNMP APIs will automatically create an instance of
+ObjectIdentifier class from its initialization value. Therefore it's
+allowed to use a plain tuple of integers as a Managed Object Name.
</P>
-<DL>
-<DT>class <STRONG>ObjectIdentifier</STRONG>(
-<STRONG>objectIdentifier</STRONG>
-)</DT>
-<DD>
-<P>
-Create an <A HREF="#OID">ASN.1 Object Identifier</A> object. The
-<STRONG>objectIdentifier</STRONG> parameter represents Object Identifier
-value. It should be either a tuple or tuple-like object or a string
-representing Object Identifier in dotted notation (like "1.3.6.1").
-</P>
-
-<P>
-Instances of this class mimic basic properties of Python tuple. Sub-OIDs
-of an OID translate into tuple components.
-</P>
-
-<P>
-For more information on <STRONG>ObjectIdentifier</STRONG> class properties,
-refer to <A HREF="http://pyasn1.sf.net">PyASN1</A> documentation.
-</P>
-</DD>
-</DL>
-
<A NAME="VAL-IMPL">
<P>
-It's PySNMP the design decision to always use <A HREF="#SMI">SMIv2</A>
-definitions for Managed Objects regardless of SNMP protocol version being
-used.
-</P>
-
-<P>
Managed Object Instance Value is an instance of some
<A HREF="http://pyasn1.sf.net">PyASN1</A> class or its
SNMP-specific derivative. The latter case reflects SNMP-specific
<A HREF="#ASN1">ASN.1</A> sub-type. The list of Managed Object
-Instance Value classes follows.
+Instance Value classes follow.
</P>
<A NAME="INTEGER-IMPL"></A>
@@ -1606,7 +1609,8 @@ Instance Value classes follows.
<P>
Create a SMIv2 <STRONG>Integer</STRONG> object. The <STRONG>value</STRONG>
parameter should be an integer value. Instances of this class mimic basic
-properties of a Python integer.
+properties of a Python integer. SMIv2 Integer class is derived from
+PyASN1 <A HREF="http://pyasn1.sourceforge.net/#1.1.3">Integer</A>.
</P>
</DD>
</DL>
@@ -1624,6 +1628,22 @@ Create a SMIv2 <STRONG>Integer32</STRONG> object. This object is similar to
</DD>
</DL>
+<A NAME="OBJECTIDENTIFIER-IMPL"></A>
+<DL>
+<DT>class <STRONG>OctetIdentifier</STRONG>(
+<STRONG>value</STRONG>
+)</DT>
+<DD>
+<P>
+Create a SMIv2 <STRONG>OctetIdentifier</STRONG> object.
+The <STRONG>value</STRONG>
+parameter could be a tuple of integer sub-IDs or a human-friendly
+string form like ".1.3.6.1.3.1". SMIv2 OctetString class is derived from
+PyASN1 <A HREF="http://pyasn1.sourceforge.net/#1.1.8">OctetIdentifier</A>.
+</P>
+</DD>
+</DL>
+
<A NAME="OCTETSTRING-IMPL"></A>
<DL>
<DT>class <STRONG>OctetString</STRONG>(
@@ -1633,7 +1653,8 @@ Create a SMIv2 <STRONG>Integer32</STRONG> object. This object is similar to
<P>
Create a SMIv2 <STRONG>OctetString</STRONG> object. The <STRONG>value</STRONG>
parameter should be a string value. Instances of this class mimic basic
-properties of a Python string.
+properties of a Python string. SMIv2 OctetString class is derived from
+PyASN1 <A HREF="http://pyasn1.sourceforge.net/#1.1.7">OctetString</A>.
</P>
</DD>
</DL>
@@ -1647,7 +1668,8 @@ properties of a Python string.
<P>
Create a SMIv2 <STRONG>IpAddress</STRONG> object. The <STRONG>value</STRONG>
parameter should be an IP address expressed in quad-dotted notation (e.g.
-"127.0.0.1").
+"127.0.0.1"). SMIv2 IpAddress class is derived from
+PyASN1 <A HREF="http://pyasn1.sourceforge.net/#1.1.7">OctetString</A>.
</P>
</DD>
</DL>
@@ -1744,12 +1766,21 @@ class instance.
<P>
Create a SMIv2 <STRONG>Bits</STRONG> object. The <STRONG>value</STRONG>
parameter should be sequence of names of bits raised to one. Unmentioned
-bits default to zero.
+bits default to zero. The Bits class is derived from
+PyASN1 <A HREF="http://pyasn1.sourceforge.net/#1.1.7">OctetString</A>.
+
</P>
</DD>
</DL>
<P>
+It's PySNMP design decision to always use <A HREF="#SMI">SMIv2</A>
+definitions for Managed Objects at the high-level API regardless of SNMP
+protocol version being used. For instance, an SNMPv3 Manager will always report
+SMIv2 types even when talking to SNMPv1 Agent (which is SMIv1-compliant).
+</P>
+
+<P>
For more information on SNMP Managed Value objects properties,
refer to their base classes in <A HREF="http://pyasn1.sf.net">PyASN1</A>
documentation.
@@ -2221,9 +2252,9 @@ loaded up and Managed Object definition looked up by symbolic name:
>>>
>>> # get Managed Object definition by symbol name
... mibNode, = mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr')
->>> print mibNode.getName()
+>>> print(mibNode.getName())
(1, 3, 6, 1, 2, 1, 1, 1)
->>> print repr(mibNode.getSyntax())
+>>> print(repr(mibNode.getSyntax()))
DisplayString('')
>>>
</PRE>
@@ -2334,11 +2365,11 @@ raised.
>>> mibViewController = view.MibViewController(mibBuilder)
>>>
>>> oid, label, suffix = mibViewController.getNodeName((1,3,6,1,2,'mib-2',1,'sysDescr'))
->>> print oid
+>>> print(oid)
(1, 3, 6, 1, 2, 1, 1, 1)
->>> print label
+>>> print(label)
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
->>> print suffix
+>>> print(suffix)
()
</PRE>
</TD></TR></TABLE>
@@ -2408,11 +2439,11 @@ as used in <A HREF="#MibBuilder">MibBuilder</A> interface. The
>>> mibViewController = view.MibViewController(mibBuilder)
>>>
>>> modName, symName, suffix = mibViewController.getNodeLocation((1,3,6,1,2,1,1,1,123))
->>> print modName
+>>> print(modName)
SNMPv2-MIB
->>> print symName
+>>> print(symName)
sysDescr
->>> print suffix
+>>> print(suffix)
(123,)
</PRE>
</TD></TR></TABLE>
@@ -3105,7 +3136,7 @@ octet-streams manipulations.
<I>
<P>
-Warning! This document is a draft.
+Disclaimer: this document is a work-in-progress.
It is neither complete nor accurate.
Take it with a grain of salt!
</P>
diff --git a/examples/smi/backend.py b/examples/smi/backend.py
index 3260a5e..91a0eba 100644
--- a/examples/smi/backend.py
+++ b/examples/smi/backend.py
@@ -1,31 +1,31 @@
# SNMP agent backend e.g. Agent access to Managed Objects
from pysnmp.smi import builder, instrum, exval
-print 'Loading MIB modules...',
+print('Loading MIB modules...'),
mibBuilder = builder.MibBuilder().loadModules(
'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB'
)
-print 'done'
+print('done')
-print 'Building MIB tree...',
+print('Building MIB tree...'),
mibInstrum = instrum.MibInstrumController(mibBuilder)
-print 'done'
+print('done')
-print 'Remote manager write/create access to MIB instrumentation: ',
-print mibInstrum.writeVars(
- (((1,3,6,1,6,3,18,1,1,1,2,109,121,110,109,115), 'mycomm'),
- ((1,3,6,1,6,3,18,1,1,1,3,109,121,110,109,115), 'mynmsname'),
- ((1,3,6,1,6,3,18,1,1,1,7,109,121,110,109,115), 'volatile'))
- )
+print('Remote manager write/create access to MIB instrumentation: '),
+print(mibInstrum.writeVars(
+ ( ((1,3,6,1,6,3,18,1,1,1,2,109,121,110,109,115), 'mycomm'),
+ ((1,3,6,1,6,3,18,1,1,1,3,109,121,110,109,115), 'mynmsname'),
+ ((1,3,6,1,6,3,18,1,1,1,7,109,121,110,109,115), 'volatile')) )
+)
-print 'Remote manager read access to MIB instrumentation (table walk)'
+print('Remote manager read access to MIB instrumentation (table walk)')
oid, val = (), None
while 1:
oid, val = mibInstrum.readNextVars(((oid, val),))[0]
if exval.endOfMib.isSameTypeWith(val):
break
- print oid, val.prettyPrint()
+ print(oid, val.prettyPrint())
-print 'Unloading MIB modules...',
+print('Unloading MIB modules...'),
mibBuilder.unloadModules()
-print 'done'
+print('done')
diff --git a/examples/smi/instrum.py b/examples/smi/instrum.py
index 836a41e..a5abda7 100644
--- a/examples/smi/instrum.py
+++ b/examples/smi/instrum.py
@@ -41,10 +41,10 @@ if __name__ == '__main__':
mibInstrum = instrum.MibInstrumController(mibBuilder)
- print 'Remote manager read access to MIB instrumentation (table walk)'
+ print('Remote manager read access to MIB instrumentation (table walk)')
oid, val = (), None
while 1:
oid, val = mibInstrum.readNextVars(((oid, val),))[0]
if exval.endOfMib.isSameTypeWith(val):
break
- print oid, val.prettyPrint()
+ print(oid, val.prettyPrint())
diff --git a/examples/smi/view.py b/examples/smi/view.py
index 38ad236..e0134c2 100644
--- a/examples/smi/view.py
+++ b/examples/smi/view.py
@@ -5,69 +5,69 @@ from pysnmp.smi import builder, view, error
mibBuilder = builder.MibBuilder()
# Optionally set an alternative path to compiled MIBs
-#print 'Setting MIB sources...'
+#print('Setting MIB sources...')
#mibSources = mibBuilder.getMibSources() + (
# builder.DirMibSource('/opt/pysnmp_mibs'),
# )
#mibBuilder.setMibSources(*mibSources)
-#print mibBuilder.getMibSources()
-#print 'done'
+#print(mibBuilder.getMibSources())
+#print('done')
-print 'Loading MIB modules...',
+print('Loading MIB modules...'),
mibBuilder.loadModules(
'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB'
)
-print 'done'
+print('done')
-print 'Indexing MIB objects...',
+print('Indexing MIB objects...'),
mibView = view.MibViewController(mibBuilder)
-print 'done'
+print('done')
-print 'MIB symbol name lookup by OID: ',
+print('MIB symbol name lookup by OID: '),
oid, label, suffix = mibView.getNodeName((1,3,6,1,2,1,1,1))
-print oid, label, suffix
+print(oid, label, suffix)
-print 'MIB symbol name lookup by label: ',
+print('MIB symbol name lookup by label: '),
oid, label, suffix = mibView.getNodeName((1,3,6,1,2,'mib-2',1,'sysDescr'))
-print oid, label, suffix
+print(oid, label, suffix)
-print 'MIB symbol name lookup by symbol description: ',
+print('MIB symbol name lookup by symbol description: '),
oid, label, suffix = mibView.getNodeName(('sysDescr',))
oid, label, suffix = mibView.getNodeName(('snmpEngineID',), 'SNMP-FRAMEWORK-MIB')
-print oid, label, suffix
+print(oid, label, suffix)
-print 'MIB object value pretty print: ',
+print('MIB object value pretty print: '),
mibNode, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'snmpEngineID')
-print mibNode.syntax
+print(mibNode.syntax.prettyPrint())
-print 'MIB symbol location lookup by name: ',
+print('MIB symbol location lookup by name: '),
modName, symName, suffix = mibView.getNodeLocation(('snmpCommunityEntry',))
-print symName, modName
+print(symName, modName)
-print 'MIB node lookup by location: ',
+print('MIB node lookup by location: '),
rowNode, = mibBuilder.importSymbols(modName, symName)
-print rowNode
+print(rowNode)
-print 'Conceptual table index value to oid convertion: ',
+print('Conceptual table index value to oid convertion: '),
oid = rowNode.getInstIdFromIndices('router')
-print oid
-print 'Conceptual table index oid to value convertion: ',
-print rowNode.getIndicesFromInstId(oid)
+print(oid)
+print('Conceptual table index oid to value convertion: '),
+print(rowNode.getIndicesFromInstId(oid))
-print 'MIB tree traversal'
+print('MIB tree traversal')
oid, label, suffix = mibView.getFirstNodeName()
while 1:
try:
modName, nodeDesc, suffix = mibView.getNodeLocation(oid)
- print '%s::%s == %s' % (modName, nodeDesc, oid)
+ print('%s::%s == %s' % (modName, nodeDesc, oid))
oid, label, suffix = mibView.getNextNodeName(oid)
except error.NoSuchObjectError:
break
-print 'Modules traversal'
+print('Modules traversal')
modName = mibView.getFirstModuleName()
while 1:
- if modName: print modName
+ if modName: print(modName)
try:
modName = mibView.getNextModuleName(modName)
except error.SmiError:
diff --git a/examples/v1arch/agent/cmdrsp.py b/examples/v1arch/agent/cmdrsp.py
index 9b3f992..d59d9e7 100644
--- a/examples/v1arch/agent/cmdrsp.py
+++ b/examples/v1arch/agent/cmdrsp.py
@@ -7,7 +7,12 @@ import time, bisect
class SysDescr:
name = (1,3,6,1,2,1,1,1,0)
- def __cmp__(self, other): return cmp(self.name, other)
+ def __eq__(self, other): return self.name == other
+ def __ne__(self, other): return self.name != other
+ def __lt__(self, other): return self.name < other
+ def __le__(self, other): return self.name <= other
+ def __gt__(self, other): return self.name > other
+ def __ge__(self, other): return self.name >= other
def __call__(self, protoVer):
return api.protoModules[protoVer].OctetString(
'PySNMP example command responder'
@@ -16,7 +21,12 @@ class SysDescr:
class Uptime:
name = (1,3,6,1,2,1,1,3,0)
birthday = time.time()
- def __cmp__(self, other): return cmp(self.name, other)
+ def __eq__(self, other): return self.name == other
+ def __ne__(self, other): return self.name != other
+ def __lt__(self, other): return self.name < other
+ def __le__(self, other): return self.name <= other
+ def __gt__(self, other): return self.name > other
+ def __ge__(self, other): return self.name >= other
def __call__(self, protoVer):
return api.protoModules[protoVer].TimeTicks(
(time.time()-self.birthday)*100
@@ -36,7 +46,7 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
if msgVer in api.protoModules:
pMod = api.protoModules[msgVer]
else:
- print 'Unsupported SNMP version %s' % msgVer
+ print('Unsupported SNMP version %s' % msgVer)
return
reqMsg, wholeMsg = decoder.decode(
wholeMsg, asn1Spec=pMod.Message(),
diff --git a/examples/v1arch/manager/bulkgen.py b/examples/v1arch/manager/bulkgen.py
new file mode 100644
index 0000000..1e70821
--- /dev/null
+++ b/examples/v1arch/manager/bulkgen.py
@@ -0,0 +1,82 @@
+# GETBULK Command Generator (SNMPv2c only)
+from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher
+from pysnmp.carrier.asynsock.dgram import udp
+from pyasn1.codec.ber import encoder, decoder
+from pysnmp.proto.api import v2c
+from time import time
+
+# SNMP table header
+headVars = [ v2c.ObjectIdentifier((1,3,6)) ]
+
+# Build PDU
+reqPDU = v2c.GetBulkRequestPDU()
+v2c.apiBulkPDU.setDefaults(reqPDU)
+v2c.apiBulkPDU.setNonRepeaters(reqPDU, 0)
+v2c.apiBulkPDU.setMaxRepetitions(reqPDU, 25)
+v2c.apiBulkPDU.setVarBinds(reqPDU, [ (x, v2c.null) for x in headVars ])
+
+# Build message
+reqMsg = v2c.Message()
+v2c.apiMessage.setDefaults(reqMsg)
+v2c.apiMessage.setCommunity(reqMsg, 'public')
+v2c.apiMessage.setPDU(reqMsg, reqPDU)
+
+startedAt = time()
+
+def cbTimerFun(timeNow):
+ if timeNow - startedAt > 3:
+ raise Exception("Request timed out")
+
+def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
+ wholeMsg, reqPDU=reqPDU, headVars=headVars):
+ while wholeMsg:
+ rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message())
+ rspPDU = v2c.apiMessage.getPDU(rspMsg)
+ # Match response to request
+ if v2c.apiBulkPDU.getRequestID(reqPDU)==v2c.apiBulkPDU.getRequestID(rspPDU):
+ # Check for SNMP errors reported
+ errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU)
+ if errorStatus and errorStatus != 2:
+ raise Exception(errorStatus)
+ # Format var-binds table
+ varBindTable = v2c.apiBulkPDU.getVarBindTable(reqPDU, rspPDU)
+ # Report SNMP table
+ for tableRow in varBindTable:
+ for name, val in tableRow:
+ print('from: %s, %s = %s' % (
+ transportAddress, name.prettyPrint(), val.prettyPrint()
+ )
+ )
+ # Stop on EOM
+ for oid, val in varBindTable[-1]:
+ if not isinstance(val, v2c.Null):
+ break
+ else:
+ transportDispatcher.jobFinished(1)
+
+ # Generate request for next row
+ v2c.apiBulkPDU.setVarBinds(
+ reqPDU, [ (x, v2c.null) for x,y in varBindTable[-1] ]
+ )
+ v2c.apiBulkPDU.setRequestID(reqPDU, v2c.getNextRequestID())
+ transportDispatcher.sendMessage(
+ encoder.encode(reqMsg), transportDomain, transportAddress
+ )
+ global startedAt
+ if time() - startedAt > 3:
+ raise Exception('Request timed out')
+ startedAt = time()
+ return wholeMsg
+
+transportDispatcher = AsynsockDispatcher()
+transportDispatcher.registerTransport(
+ udp.domainName, udp.UdpSocketTransport().openClientMode()
+ )
+transportDispatcher.registerRecvCbFun(cbRecvFun)
+transportDispatcher.registerTimerCbFun(cbTimerFun)
+transportDispatcher.sendMessage(
+ encoder.encode(reqMsg), udp.domainName, ('localhost', 161)
+ )
+transportDispatcher.jobStarted(1)
+transportDispatcher.runDispatcher()
+transportDispatcher.closeDispatcher()
diff --git a/examples/v1arch/manager/getgen.py b/examples/v1arch/manager/getgen.py
index 1189659..2ba0fea 100644
--- a/examples/v1arch/manager/getgen.py
+++ b/examples/v1arch/manager/getgen.py
@@ -24,7 +24,7 @@ pMod.apiMessage.setPDU(reqMsg, reqPDU)
def cbTimerFun(timeNow, startedAt=time()):
if timeNow - startedAt > 3:
- raise "Request timed out"
+ raise Exception("Request timed out")
def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
wholeMsg, reqPDU=reqPDU):
@@ -36,10 +36,10 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
# Check for SNMP errors reported
errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
if errorStatus:
- print errorStatus.prettyPrint()
+ print(errorStatus.prettyPrint())
else:
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
transportDispatcher.jobFinished(1)
return wholeMsg
diff --git a/examples/v1arch/manager/nextgen.py b/examples/v1arch/manager/nextgen.py
index 14dcebd..27e1493 100644
--- a/examples/v1arch/manager/nextgen.py
+++ b/examples/v1arch/manager/nextgen.py
@@ -15,9 +15,7 @@ headVars = [ pMod.ObjectIdentifier((1,3,6)) ]
# Build PDU
reqPDU = pMod.GetNextRequestPDU()
pMod.apiPDU.setDefaults(reqPDU)
-pMod.apiPDU.setVarBinds(
- reqPDU, map(lambda x, pMod=pMod: (x, pMod.Null('')), headVars)
- )
+pMod.apiPDU.setVarBinds(reqPDU, [ (x, pMod.null) for x in headVars ])
# Build message
reqMsg = pMod.Message()
@@ -29,7 +27,7 @@ startedAt = time()
def cbTimerFun(timeNow):
if timeNow - startedAt > 3:
- raise "Request timed out"
+ raise Exception("Request timed out")
def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
wholeMsg, reqPDU=reqPDU, headVars=headVars):
@@ -41,15 +39,16 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
# Check for SNMP errors reported
errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
if errorStatus and errorStatus != 2:
- raise errorStatus
+ raise Exception(errorStatus)
# Format var-binds table
varBindTable = pMod.apiPDU.getVarBindTable(reqPDU, rspPDU)
# Report SNMP table
for tableRow in varBindTable:
for name, val in tableRow:
- print 'from: %s, %s = %s' % (
+ print('from: %s, %s = %s' % (
transportAddress, name.prettyPrint(), val.prettyPrint()
)
+ )
# Stop on EOM
for oid, val in varBindTable[-1]:
if not isinstance(val, pMod.Null):
@@ -59,7 +58,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
# Generate request for next row
pMod.apiPDU.setVarBinds(
- reqPDU, map(lambda (x,y),n=pMod.Null(''): (x,n), varBindTable[-1])
+ reqPDU, [ (x, pMod.null) for x,y in varBindTable[-1] ]
)
pMod.apiPDU.setRequestID(reqPDU, pMod.getNextRequestID())
transportDispatcher.sendMessage(
@@ -67,7 +66,7 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
)
global startedAt
if time() - startedAt > 3:
- raise 'Request timed out'
+ raise Exception('Request timed out')
startedAt = time()
return wholeMsg
diff --git a/examples/v1arch/manager/ntfrcv.py b/examples/v1arch/manager/ntfrcv.py
index a38c14c..62f8147 100644
--- a/examples/v1arch/manager/ntfrcv.py
+++ b/examples/v1arch/manager/ntfrcv.py
@@ -10,38 +10,44 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg):
if msgVer in api.protoModules:
pMod = api.protoModules[msgVer]
else:
- print 'Unsupported SNMP version %s' % msgVer
+ print('Unsupported SNMP version %s' % msgVer)
return
reqMsg, wholeMsg = decoder.decode(
wholeMsg, asn1Spec=pMod.Message(),
)
- print 'Notification message from %s:%s: ' % (
+ print('Notification message from %s:%s: ' % (
transportDomain, transportAddress
)
+ )
reqPDU = pMod.apiMessage.getPDU(reqMsg)
if reqPDU.isSameTypeWith(pMod.TrapPDU()):
if msgVer == api.protoVersion1:
- print 'Enterprise: %s' % (
+ print('Enterprise: %s' % (
pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint()
)
- print 'Agent Address: %s' % (
+ )
+ print('Agent Address: %s' % (
pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint()
)
- print 'Generic Trap: %s' % (
+ )
+ print('Generic Trap: %s' % (
pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint()
)
- print 'Specific Trap: %s' % (
+ )
+ print('Specific Trap: %s' % (
pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint()
)
- print 'Uptime: %s' % (
+ )
+ print('Uptime: %s' % (
pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint()
)
+ )
varBinds = pMod.apiTrapPDU.getVarBindList(reqPDU)
else:
varBinds = pMod.apiPDU.getVarBindList(reqPDU)
- print 'Var-binds:'
+ print('Var-binds:')
for oid, val in varBinds:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
return wholeMsg
transportDispatcher = AsynsockDispatcher()
diff --git a/examples/v1arch/manager/setgen.py b/examples/v1arch/manager/setgen.py
index 0d27be5..eec3731 100644
--- a/examples/v1arch/manager/setgen.py
+++ b/examples/v1arch/manager/setgen.py
@@ -26,7 +26,7 @@ pMod.apiMessage.setPDU(reqMsg, reqPDU)
def cbTimerFun(timeNow, startedAt=time()):
if timeNow - startedAt > 3:
- raise "Request timed out"
+ raise Exception("Request timed out")
def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
wholeMsg, reqPDU=reqPDU):
@@ -38,10 +38,10 @@ def cbRecvFun(transportDispatcher, transportDomain, transportAddress,
# Check for SNMP errors reported
errorStatus = pMod.apiPDU.getErrorStatus(rspPDU)
if errorStatus:
- print errorStatus.prettyPrint()
+ print(errorStatus.prettyPrint())
else:
for oid, val in pMod.apiPDU.getVarBinds(rspPDU):
- print '%s = %s' (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' (oid.prettyPrint(), val.prettyPrint()))
transportDispatcher.jobFinished(1)
return wholeMsg
diff --git a/examples/v3arch/agent/ntforg.py b/examples/v3arch/agent/ntforg.py
index 5765e9f..f25dec3 100644
--- a/examples/v3arch/agent/ntforg.py
+++ b/examples/v3arch/agent/ntforg.py
@@ -53,7 +53,7 @@ snmpContext = context.SnmpContext(snmpEngine)
def cbFun(sendRequestHandle, errorIndication, cbCtx):
if errorIndication:
- print errorIndication
+ print(errorIndication)
ntforg.NotificationOriginator(snmpContext).sendNotification(
snmpEngine,
diff --git a/examples/v3arch/manager/bulkgen.py b/examples/v3arch/manager/bulkgen.py
index 9c7eb75..ec8653c 100644
--- a/examples/v3arch/manager/bulkgen.py
+++ b/examples/v3arch/manager/bulkgen.py
@@ -35,17 +35,18 @@ config.addSocketTransport(
def cbFun(sendRequesthandle, errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
if errorIndication:
- print errorIndication
+ print(errorIndication)
return # stop on error
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
- )
+ )
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
return 1 # continue walking
cmdgen.BulkCommandGenerator().sendReq(
diff --git a/examples/v3arch/manager/getgen.py b/examples/v3arch/manager/getgen.py
index ed8b7f4..98bbc7c 100644
--- a/examples/v3arch/manager/getgen.py
+++ b/examples/v3arch/manager/getgen.py
@@ -49,9 +49,9 @@ cmdgen.GetCommandGenerator().sendReq(
snmpEngine.transportDispatcher.runDispatcher()
if cbCtx['errorIndication']:
- print cbCtx['errorIndication']
+ print(cbCtx['errorIndication'])
elif cbCtx['errorStatus']:
- print cbCtx['errorStatus'].prettyPrint()
+ print(cbCtx['errorStatus'].prettyPrint())
else:
for oid, val in cbCtx['varBinds']:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
diff --git a/examples/v3arch/manager/nextgen.py b/examples/v3arch/manager/nextgen.py
index 9e9a502..ab0e27f 100644
--- a/examples/v3arch/manager/nextgen.py
+++ b/examples/v3arch/manager/nextgen.py
@@ -35,19 +35,20 @@ config.addSocketTransport(
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
varBindTable, cbCtx):
if errorIndication:
- print errorIndication
+ print(errorIndication)
return
# SNMPv1 response may contain noSuchName error *and* SNMPv2c exception,
# so we ignore noSuchName error here
if errorStatus and errorStatus != 2:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
+ )
return # stop on error
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
return 1 # continue walking
cmdgen.NextCommandGenerator().sendReq(
diff --git a/examples/v3arch/manager/ntfrcv.py b/examples/v3arch/manager/ntfrcv.py
index dc1e7ad..7e26cf7 100644
--- a/examples/v3arch/manager/ntfrcv.py
+++ b/examples/v3arch/manager/ntfrcv.py
@@ -37,12 +37,13 @@ def cbFun(snmpEngine,
varBinds,
cbCtx):
transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)
- print 'Notification from %s, SNMP Engine %s, Context %s' % (
+ print('Notification from %s, SNMP Engine %s, Context %s' % (
transportAddress, contextEngineId.prettyPrint(),
contextName.prettyPrint()
)
+ )
for name, val in varBinds:
- print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
# Apps registration
ntfrcv.NotificationReceiver(snmpEngine, cbFun)
diff --git a/examples/v3arch/manager/setgen.py b/examples/v3arch/manager/setgen.py
index 4b90f31..0704ae8 100644
--- a/examples/v3arch/manager/setgen.py
+++ b/examples/v3arch/manager/setgen.py
@@ -49,15 +49,16 @@ cmdgen.SetCommandGenerator().sendReq(
snmpEngine.transportDispatcher.runDispatcher()
if cbCtx['errorIndication']:
- print cbCtx['errorIndication']
+ print(cbCtx['errorIndication'])
elif cbCtx['errorStatus']:
if cbCtx['errorIndex']:
- print '%s at %s' % (
+ print('%s at %s' % (
cbCtx['errorStatus'].prettyPrint(),
cbCtx['varBinds'][int(cbCtx['errorIndex'])-1]
+ )
)
else:
- print cbCtx['errorStatus'].prettyPrint()
+ print(cbCtx['errorStatus'].prettyPrint())
else:
for o, v in cbCtx['varBinds']:
- print '%s = %s' % (o.prettyPrint(), v.prettyPrint())
+ print('%s = %s' % (o.prettyPrint(), v.prettyPrint()))
diff --git a/examples/v3arch/oneliner/manager/async/nextgen.py b/examples/v3arch/oneliner/manager/async/nextgen.py
index a8e538f..01285b8 100644
--- a/examples/v3arch/oneliner/manager/async/nextgen.py
+++ b/examples/v3arch/oneliner/manager/async/nextgen.py
@@ -20,19 +20,19 @@ targets = (
# ...
)
-def cbFun(
- sendRequestHandle, errorIndication, errorStatus, errorIndex,
- varBindTable, (varBindHead, authData, transportTarget)
- ):
- print '%s via %s' % (authData, transportTarget)
+def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
+ varBindTable, cbCtx):
+ (varBindHead, authData, transportTarget) = cbCtx
+ print('%s via %s' % (authData, transportTarget))
if errorIndication:
- print errorIndication
+ print(errorIndication)
return 1
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
+ )
return 1
varBindTableRow = varBindTable[-1]
for idx in range(len(varBindTableRow)):
@@ -41,15 +41,15 @@ def cbFun(
# still in table
break
else:
- print 'went out of table at %s' % (name, )
+ print('went out of table at %s' % (name, ))
return
for varBindRow in varBindTable:
for oid, val in varBindRow:
if val is None:
- print oid.prettyPrint()
+ print(oid.prettyPrint())
else:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
return 1 # continue table retrieval
diff --git a/examples/v3arch/oneliner/manager/bulkgen.py b/examples/v3arch/oneliner/manager/bulkgen.py
index 98646a1..80680b9 100644
--- a/examples/v3arch/oneliner/manager/bulkgen.py
+++ b/examples/v3arch/oneliner/manager/bulkgen.py
@@ -15,14 +15,15 @@ errorIndication, errorStatus, errorIndex, \
)
if errorIndication:
- print errorIndication
+ print(errorIndication)
else:
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
+ )
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
- print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
diff --git a/examples/v3arch/oneliner/manager/getgen.py b/examples/v3arch/oneliner/manager/getgen.py
index 80f52c9..1bc156d 100644
--- a/examples/v3arch/oneliner/manager/getgen.py
+++ b/examples/v3arch/oneliner/manager/getgen.py
@@ -17,13 +17,14 @@ errorIndication, errorStatus, \
)
if errorIndication:
- print errorIndication
+ print(errorIndication)
else:
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex)-1] or '?'
)
+ )
else:
for name, val in varBinds:
- print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
diff --git a/examples/v3arch/oneliner/manager/nextgen.py b/examples/v3arch/oneliner/manager/nextgen.py
index a5ad517..95c5ccb 100644
--- a/examples/v3arch/oneliner/manager/nextgen.py
+++ b/examples/v3arch/oneliner/manager/nextgen.py
@@ -14,14 +14,15 @@ errorIndication, errorStatus, errorIndex, \
)
if errorIndication:
- print errorIndication
+ print(errorIndication)
else:
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
+ )
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
- print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
diff --git a/examples/v3arch/oneliner/manager/setgen.py b/examples/v3arch/oneliner/manager/setgen.py
index 30e13fb..581bd1c 100644
--- a/examples/v3arch/oneliner/manager/setgen.py
+++ b/examples/v3arch/oneliner/manager/setgen.py
@@ -18,13 +18,14 @@ errorIndication, errorStatus, \
)
if errorIndication:
- print errorIndication
+ print(errorIndication)
else:
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex)-1] or '?'
)
+ )
else:
for name, val in varBinds:
- print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
diff --git a/examples/v3arch/oneliner/manager/withmib/nextgen.py b/examples/v3arch/oneliner/manager/withmib/nextgen.py
index 1276ce7..1565b15 100644
--- a/examples/v3arch/oneliner/manager/withmib/nextgen.py
+++ b/examples/v3arch/oneliner/manager/withmib/nextgen.py
@@ -1,5 +1,4 @@
# GETNEXT Commnd Generator with MIB resolution
-import string
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.entity.rfc3413 import mibvar
@@ -25,13 +24,14 @@ errorIndication, errorStatus, errorIndex, \
)
if errorIndication:
- print errorIndication
+ print(errorIndication)
else:
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
varBindTable[-1][int(errorIndex)-1]
)
+ )
else:
for varBindTableRow in varBindTable:
for oid, val in varBindTableRow:
@@ -41,8 +41,9 @@ else:
val = mibvar.cloneFromMibValue(
cmdGen.mibViewController, modName, symName, val
)
- print '%s::%s.%s = %s' % (
+ print('%s::%s.%s = %s' % (
modName, symName,
- string.join(map(lambda v: v.prettyPrint(), indices), '.'),
+ '.'.join([ v.prettyPrint() for v in indices]),
val.prettyPrint()
)
+ )
diff --git a/examples/v3arch/oneliner/manager/withmib/setgen.py b/examples/v3arch/oneliner/manager/withmib/setgen.py
index 1700188..ae59a85 100644
--- a/examples/v3arch/oneliner/manager/withmib/setgen.py
+++ b/examples/v3arch/oneliner/manager/withmib/setgen.py
@@ -1,5 +1,4 @@
# SET Command Generator with MIB resolution
-import string
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.entity.rfc3413 import mibvar
@@ -19,12 +18,13 @@ errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd(
)
if errorIndication:
- print errorIndication
+ print(errorIndication)
else:
if errorStatus:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(), varBinds[int(errorIndex)-1]
)
+ )
else:
for oid, val in varBinds:
(symName, modName), indices = mibvar.oidToMibName(
@@ -33,8 +33,9 @@ else:
val = mibvar.cloneFromMibValue(
cmdGen.mibViewController, modName, symName, val
)
- print '%s::%s.%s = %s' % (
+ print('%s::%s.%s = %s' % (
modName, symName,
- string.join(map(lambda v: v.prettyPrint(), indices), '.'),
+ '.'.join([ v.prettyPrint() for v in indices]),
val.prettyPrint()
)
+ )
diff --git a/examples/v3arch/proxy/cmdproxy.py b/examples/v3arch/proxy/cmdproxy.py
index 1d7233d..98ae0be 100644
--- a/examples/v3arch/proxy/cmdproxy.py
+++ b/examples/v3arch/proxy/cmdproxy.py
@@ -78,7 +78,8 @@ class GetCommandProxy(cmdrsp.GetCommandResponder):
cmdGen = cmdgen.GetCommandGenerator()
def handleMgmtOperation(self, snmpEngine, stateReference, contextName,
- PDU, (acFun, acCtx)):
+ PDU, acInfo):
+ (acFun, acCtx) = acInfo
varBinds = v2c.apiPDU.getVarBinds(PDU)
try:
# The trick here is to use contextName as SNMP Manager target name
@@ -86,12 +87,12 @@ class GetCommandProxy(cmdrsp.GetCommandResponder):
snmpEngine, contextName, varBinds,
self.handleResponse, (stateReference, varBinds)
)
- except Exception, why:
+ except Exception:
self.sendRsp(snmpEngine, stateReference, 5, 0, varBinds)
def handleResponse(self, sendRequestHandle, errorIndication,
- errorStatus, errorIndex, varBinds,
- (stateReference, reqVarBinds)):
+ errorStatus, errorIndex, varBinds, cbCtx):
+ (stateReference, reqVarBinds) = cbCtx
if errorIndication:
errorStatus = 5
varBinds = reqVarBinds
diff --git a/examples/v3arch/twisted/agent/ntforg.py b/examples/v3arch/twisted/agent/ntforg.py
index 77df949..a41290a 100644
--- a/examples/v3arch/twisted/agent/ntforg.py
+++ b/examples/v3arch/twisted/agent/ntforg.py
@@ -66,9 +66,10 @@ snmpContext = context.SnmpContext(snmpEngine)
# Twisted API follows
-def receiveResponse((sendRequestHandle, errorIndication)):
+def receiveResponse(cbCtx):
+ (sendRequestHandle, errorIndication) = cbCtx
if errorIndication:
- print 'Error: ', errorIndication
+ print('Error: %s' % errorIndication)
reactor.stop()
ntfOrg = ntforg.NotificationOriginator(snmpContext)
diff --git a/examples/v3arch/twisted/manager/bulkgen.py b/examples/v3arch/twisted/manager/bulkgen.py
index a8c4be8..5622479 100644
--- a/examples/v3arch/twisted/manager/bulkgen.py
+++ b/examples/v3arch/twisted/manager/bulkgen.py
@@ -40,21 +40,23 @@ config.addSocketTransport(
# Twisted API follows
-def receiveResponse((errorIndication, errorStatus, errorIndex, varBindTable)):
+def receiveResponse(cbCtx):
+ (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx
if errorIndication:
- print 'Error: ', errorIndication
+ print('Error: %s' % errorIndication)
reactor.stop()
return
if errorStatus and errorStatus != 2:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
+ )
reactor.stop()
return
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
for o, v in varBindTable[-1]:
if not isinstance(v, univ.Null):
diff --git a/examples/v3arch/twisted/manager/getgen.py b/examples/v3arch/twisted/manager/getgen.py
index d9cc422..05dc093 100644
--- a/examples/v3arch/twisted/manager/getgen.py
+++ b/examples/v3arch/twisted/manager/getgen.py
@@ -39,20 +39,21 @@ config.addSocketTransport(
# Twisted API follows
-def receiveResponse((errorIndication, errorStatus, errorIndex, varBinds)):
+def receiveResponse(cbCtx):
+ (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
if errorIndication:
- print 'Error: ', errorIndication
+ print('Error: %s' % errorIndication)
reactor.stop()
return
if errorStatus:
- print 'Error: ', errorStatus.prettyPrint(), errorIndex
+ print('Error: %s at %s' % (errorStatus.prettyPrint(), errorIndex))
reactor.stop()
return
for oid, val in varBinds:
if val is None:
- print oid.prettyPrint()
+ print(oid.prettyPrint())
else:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
reactor.stop()
getCmdGen = cmdgen.GetCommandGenerator()
diff --git a/examples/v3arch/twisted/manager/nextgen.py b/examples/v3arch/twisted/manager/nextgen.py
index 306c71c..b10003a 100644
--- a/examples/v3arch/twisted/manager/nextgen.py
+++ b/examples/v3arch/twisted/manager/nextgen.py
@@ -40,21 +40,23 @@ config.addSocketTransport(
# Twisted API follows
-def receiveResponse((errorIndication, errorStatus, errorIndex, varBindTable)):
+def receiveResponse(cbCtx):
+ (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx
if errorIndication:
- print 'Error: ', errorIndication
+ print('Error: %s' % errorIndication)
reactor.stop()
return
if errorStatus and errorStatus != 2:
- print '%s at %s\n' % (
+ print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
+ )
reactor.stop()
return
for varBindRow in varBindTable:
for oid, val in varBindRow:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
for o, v in varBindTable[-1]:
if not isinstance(v, univ.Null):
diff --git a/examples/v3arch/twisted/manager/ntfrcv.py b/examples/v3arch/twisted/manager/ntfrcv.py
index 5ed8232..bee7dcb 100644
--- a/examples/v3arch/twisted/manager/ntfrcv.py
+++ b/examples/v3arch/twisted/manager/ntfrcv.py
@@ -36,12 +36,13 @@ def cbFun(snmpEngine,
varBinds,
cbCtx):
transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)
- print 'Notification from %s, SNMP Engine %s, Context %s' % (
+ print('Notification from %s, SNMP Engine %s, Context %s' % (
transportAddress, contextEngineId.prettyPrint(),
contextName.prettyPrint()
)
+ )
for name, val in varBinds:
- print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
# Apps registration
ntfrcv.NotificationReceiver(snmpEngine, cbFun)
diff --git a/examples/v3arch/twisted/manager/setgen.py b/examples/v3arch/twisted/manager/setgen.py
index df92615..cd5869f 100644
--- a/examples/v3arch/twisted/manager/setgen.py
+++ b/examples/v3arch/twisted/manager/setgen.py
@@ -40,20 +40,21 @@ config.addSocketTransport(
# Twisted API follows
-def receiveResponse((errorIndication, errorStatus, errorIndex, varBinds)):
+def receiveResponse(cbCtx):
+ (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx
if errorIndication:
- print 'Error: ', errorIndication
+ print('Error: %s' % errorIndication)
reactor.stop()
return
if errorStatus:
- print 'Error: ', errorStatus.prettyPrint(), errorIndex
+ print('Error: %s at %s' % (errorStatus.prettyPrint(), errorIndex))
reactor.stop()
return
for oid, val in varBinds:
if val is None:
- print oid.prettyPrint()
+ print(oid.prettyPrint())
else:
- print '%s = %s' % (oid.prettyPrint(), val.prettyPrint())
+ print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
reactor.stop()
getCmdGen = cmdgen.SetCommandGenerator()
diff --git a/pysnmp/__init__.py b/pysnmp/__init__.py
index 8ecf756..134516f 100644
--- a/pysnmp/__init__.py
+++ b/pysnmp/__init__.py
@@ -1,3 +1,3 @@
# PySNMP, version 4
majorVersionId = '4'
-version = (4, 1, 16)
+version = (4, 2, 1)
diff --git a/pysnmp/cache.py b/pysnmp/cache.py
index f39e1d2..a07665b 100644
--- a/pysnmp/cache.py
+++ b/pysnmp/cache.py
@@ -4,7 +4,7 @@ class Cache:
def __init__(self, maxSize=256):
self.__maxSize = maxSize
self.__size = 0
- self.__chopSize = maxSize/10
+ self.__chopSize = maxSize//10
self.__chopSize = self.__chopSize and self.__chopSize or 1
self.__cache = {}
self.__usage = {}
@@ -19,15 +19,15 @@ class Cache:
def __setitem__(self, k, v):
if self.__size >= self.__maxSize:
- keys = self.__usage.keys()
- keys.sort(lambda x,y,d=self.__usage: cmp(d[x],d[y]))
+ keys = list(self.__usage.keys())
+ keys.sort(key=lambda x,d=self.__usage: d[x])
for _k in keys[:self.__chopSize]:
del self.__cache[_k]
del self.__usage[_k]
self.__size = self.__size - self.__chopSize
if k not in self.__cache:
self.__size = self.__size + 1
- self.__usage[k] = 0L
+ self.__usage[k] = 0
self.__cache[k] = v
def __delitem__(self, k):
diff --git a/pysnmp/carrier/asynsock/base.py b/pysnmp/carrier/asynsock/base.py
index e60b340..d5aa44a 100644
--- a/pysnmp/carrier/asynsock/base.py
+++ b/pysnmp/carrier/asynsock/base.py
@@ -18,8 +18,8 @@ class AbstractSocketTransport(asyncore.dispatcher):
)
try:
sock = socket.socket(self.sockFamily, self.sockType)
- except socket.error, why:
- raise error.CarrierError('socket() failed: %s' % why)
+ except socket.error:
+ raise error.CarrierError('socket() failed: %s' % sys.exc_info()[1])
if sockMap is None:
# The socket map is managed by the AsynsockDispatcher on
# which this transport is registered, so this is a fake
diff --git a/pysnmp/carrier/asynsock/dgram/base.py b/pysnmp/carrier/asynsock/dgram/base.py
index c0f7dd8..4561f03 100644
--- a/pysnmp/carrier/asynsock/dgram/base.py
+++ b/pysnmp/carrier/asynsock/dgram/base.py
@@ -1,5 +1,5 @@
"""Implements asyncore-based generic DGRAM transport"""
-import socket, errno
+import socket, errno, sys
from pysnmp.carrier.asynsock.base import AbstractSocketTransport
from pysnmp.carrier import error
from pysnmp import debug
@@ -30,15 +30,15 @@ class DgramSocketTransport(AbstractSocketTransport):
if iface is not None:
try:
self.socket.bind(iface)
- except socket.error, why:
- raise error.CarrierError('bind() failed: %s' % (why,))
+ except socket.error:
+ raise error.CarrierError('bind() failed: %s' % (sys.exc_info()[1],))
return self
def openServerMode(self, iface):
try:
self.socket.bind(iface)
- except socket.error, why:
- raise error.CarrierError('bind() failed: %s' % (why,))
+ except socket.error:
+ raise error.CarrierError('bind() failed: %s' % (sys.exc_info()[1],))
self._iface = iface
return self
@@ -55,11 +55,11 @@ class DgramSocketTransport(AbstractSocketTransport):
debug.logger & debug.flagIO and debug.logger('handle_write: transportAddress %s outgoingMessage %s' % (transportAddress, repr(outgoingMessage)))
try:
self.socket.sendto(outgoingMessage, transportAddress)
- except socket.error, why:
- if why[0] in sockErrors:
- debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (why,))
+ except socket.error:
+ if sys.exc_info()[1][0] in sockErrors:
+ debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (sys.exc_info()[1],))
else:
- raise socket.error, why
+ raise socket.error(sys.exc_info()[1])
def readable(self): return 1
def handle_read(self):
@@ -72,11 +72,11 @@ class DgramSocketTransport(AbstractSocketTransport):
else:
self._cbFun(self, transportAddress, incomingMessage)
return
- except socket.error, why:
- if why[0] in sockErrors:
- debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % (why,))
- sockErrors[why[0]] and self.handle_close()
+ except socket.error:
+ if sys.exc_info()[1][0] in sockErrors:
+ debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % (sys.exc_info()[1],))
+ sockErrors[sys.exc_info()[1][0]] and self.handle_close()
return
else:
- raise socket.error, why
+ raise socket.error(sys.exc_info()[1])
def handle_close(self): pass # no datagram connection
diff --git a/pysnmp/carrier/base.py b/pysnmp/carrier/base.py
index 3fc8c0f..5701043 100644
--- a/pysnmp/carrier/base.py
+++ b/pysnmp/carrier/base.py
@@ -12,8 +12,12 @@ class TimerCallable:
self.__cbFun(timeNow)
self.__nextCall = timeNow + self.__callInterval
- def __cmp__(self, cbFun):
- return cmp(self.__cbFun, cbFun)
+ def __eq__(self, cbFun): return self.__cbFun == cbFun
+ def __ne__(self, cbFun): return self.__cbFun != cbFun
+ def __lt__(self, cbFun): return self.__cbFun < cbFun
+ def __le__(self, cbFun): return self.__cbFun <= cbFun
+ def __gt__(self, cbFun): return self.__cbFun > cbFun
+ def __ge__(self, cbFun): return self.__cbFun >= cbFun
class AbstractTransportDispatcher:
def __init__(self):
@@ -117,7 +121,7 @@ class AbstractTransportDispatcher:
raise error.CarrierError('Method not implemented')
def closeDispatcher(self):
- for tDomain in self.__transports.keys():
+ for tDomain in list(self.__transports):
self.__transports[tDomain].closeTransport()
self.unregisterTransport(tDomain)
self.unregisterRecvCbFun()
diff --git a/pysnmp/carrier/twisted/dgram/base.py b/pysnmp/carrier/twisted/dgram/base.py
index 75dd455..f9475ec 100644
--- a/pysnmp/carrier/twisted/dgram/base.py
+++ b/pysnmp/carrier/twisted/dgram/base.py
@@ -1,5 +1,5 @@
"""Implements twisted-based generic DGRAM transport"""
-from time import time
+import sys
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from pysnmp.carrier.twisted.base import AbstractTwistedTransport
@@ -26,8 +26,8 @@ class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport):
debug.logger & debug.flagIO and debug.logger('startProtocol: transportAddress %s outgoingMessage %s' % (transportAddress, repr(outgoingMessage)))
try:
self.transport.write(outgoingMessage, transportAddress)
- except Exception, why:
- raise error.CarrierError('Twisted exception: %s' % (why,))
+ except Exception:
+ raise error.CarrierError('Twisted exception: %s' % (sys.exc_info()[1],))
def stopProtocol(self):
debug.logger & debug.flagIO and debug.logger('stopProtocol: invoked')
@@ -40,5 +40,5 @@ class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport):
else:
try:
self.transport.write(outgoingMessage, transportAddress)
- except Exception, why:
- raise error.CarrierError('Twisted exception: %s' % (why,))
+ except Exception:
+ raise error.CarrierError('Twisted exception: %s' % (sys.exc_info()[1],))
diff --git a/pysnmp/carrier/twisted/dgram/udp.py b/pysnmp/carrier/twisted/dgram/udp.py
index 850ff1b..4c91130 100644
--- a/pysnmp/carrier/twisted/dgram/udp.py
+++ b/pysnmp/carrier/twisted/dgram/udp.py
@@ -1,4 +1,5 @@
"""Implements twisted-based UDP transport"""
+import sys
from twisted.internet import reactor
from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport
from pysnmp.carrier import error
@@ -11,15 +12,15 @@ class UdpTwistedTransport(DgramTwistedTransport):
def openClientMode(self, iface=''):
try:
self._lport = reactor.listenUDP(0, self, iface)
- except Exception, why:
- raise error.CarrierError(why)
+ except Exception:
+ raise error.CarrierError(sys.exc_info()[1])
return self
def openServerMode(self, iface=None):
try:
self._lport = reactor.listenUDP(iface[1], self, iface[0])
- except Exception, why:
- raise error.CarrierError(why)
+ except Exception:
+ raise error.CarrierError(sys.exc_info()[1])
return self
-UdpTransport = UdpTwistedTransport \ No newline at end of file
+UdpTransport = UdpTwistedTransport
diff --git a/pysnmp/carrier/twisted/dgram/unix.py b/pysnmp/carrier/twisted/dgram/unix.py
index 75bfe17..fa248bf 100644
--- a/pysnmp/carrier/twisted/dgram/unix.py
+++ b/pysnmp/carrier/twisted/dgram/unix.py
@@ -1,4 +1,5 @@
"""Implements twisted-based UNIX domain socket transport"""
+import sys
from twisted.internet import reactor
from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport
from pysnmp.carrier import error
@@ -11,16 +12,16 @@ class UnixTwistedTransport(DgramTwistedTransport):
def openClientMode(self, iface=''):
try:
self._lport = reactor.connectUNIXDatagram(iface, self)
- except Exception, why:
- raise error.CarrierError(why)
+ except Exception:
+ raise error.CarrierError(sys.exc_info()[1])
return self
def openServerMode(self, iface=None):
try:
self._lport = reactor.listenUNIXDatagram(iface, self)
- except Exception, why:
- raise error.CarrierError(why)
+ except Exception:
+ raise error.CarrierError(sys.exc_info()[1])
return self
-UnixTransport = UnixTwistedTransport \ No newline at end of file
+UnixTransport = UnixTwistedTransport
diff --git a/pysnmp/carrier/twisted/dispatch.py b/pysnmp/carrier/twisted/dispatch.py
index df4d1e0..89e1629 100644
--- a/pysnmp/carrier/twisted/dispatch.py
+++ b/pysnmp/carrier/twisted/dispatch.py
@@ -8,7 +8,7 @@
#
# Description: Transport dispatcher based on twisted.internet.reactor
#
-from time import time
+import sys, time
from twisted.internet import reactor, task
from pysnmp.carrier.base import AbstractTransportDispatcher
from pysnmp.carrier import error
@@ -25,14 +25,14 @@ class TwistedDispatcher(AbstractTransportDispatcher):
self.loopingcall = task.LoopingCall(self.handleTimeout)
def handleTimeout(self):
- self.handleTimerTick(time())
+ self.handleTimerTick(time.time())
def runDispatcher(self, timeout=0.0):
if not reactor.running:
try:
reactor.run()
- except Exception, why:
- raise error.CarrierError(why)
+ except Exception:
+ raise error.CarrierError(sys.exc_info()[1])
# jobstarted/jobfinished might be okay as-is
diff --git a/pysnmp/entity/config.py b/pysnmp/entity/config.py
index d486e50..bb5c141 100644
--- a/pysnmp/entity/config.py
+++ b/pysnmp/entity/config.py
@@ -1,6 +1,6 @@
# Initial SNMP engine configuration functions. During further operation,
# SNMP engine might be configured remotely (through SNMP).
-import string
+from pyasn1.compat.octets import null
from pysnmp.carrier.asynsock import dispatch
from pysnmp.carrier.asynsock.dgram import udp, udp6
try:
@@ -70,7 +70,7 @@ def addV1System(snmpEngine, securityName, communityName,
if contextEngineId is None:
contextEngineId = snmpEngineID.syntax
if contextName is None:
- contextName = ''
+ contextName = null
snmpEngine.msgAndPduDsp.mibInstrumController.writeVars(
((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),)
@@ -139,7 +139,7 @@ def addV3User(snmpEngine, securityName,
# Localize keys
if authProtocol in authServices:
hashedAuthPassphrase = authServices[authProtocol].hashPassphrase(
- authKey and authKey or ''
+ authKey and authKey or null
)
localAuthKey = authServices[authProtocol].localizeKey(
hashedAuthPassphrase, snmpEngineID
@@ -149,7 +149,7 @@ def addV3User(snmpEngine, securityName,
if privProtocol in privServices:
hashedPrivPassphrase = privServices[privProtocol].hashPassphrase(
- authProtocol, privKey and privKey or ''
+ authProtocol, privKey and privKey or null
)
localPrivKey = privServices[privProtocol].localizeKey(
authProtocol, hashedPrivPassphrase, snmpEngineID
@@ -246,7 +246,7 @@ def addTargetAddr(
params,
timeout=None,
retryCount=None,
- tagList=''
+ tagList=null
):
snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo(
snmpEngine, addrName
@@ -425,7 +425,7 @@ def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel):
def addVacmUser(snmpEngine, securityModel, securityName, securityLevel,
readSubTree=(), writeSubTree=(), notifySubTree=(),
- contextName=''):
+ contextName=null):
( groupName, securityLevel,
readView, writeView, notifyView ) = __cookVacmUserInfo(
snmpEngine, securityModel, securityName, securityLevel,
@@ -439,15 +439,15 @@ def addVacmUser(snmpEngine, securityModel, securityName, securityLevel,
)
if readSubTree:
addVacmView(
- snmpEngine, readView, "included", readSubTree, '',
+ snmpEngine, readView, "included", readSubTree, null,
)
if writeSubTree:
addVacmView(
- snmpEngine, writeView, "included", writeSubTree, '',
+ snmpEngine, writeView, "included", writeSubTree, null,
)
if notifySubTree:
addVacmView(
- snmpEngine, notifyView, "included", notifySubTree, '',
+ snmpEngine, notifyView, "included", notifySubTree, null,
)
def delVacmUser(snmpEngine, securityModel, securityName, securityLevel,
@@ -460,7 +460,7 @@ def delVacmUser(snmpEngine, securityModel, securityName, securityLevel,
snmpEngine, securityModel, securityName
)
delVacmAccess(
- snmpEngine, groupName, '', securityModel, securityLevel
+ snmpEngine, groupName, null, securityModel, securityLevel
)
if readSubTree:
delVacmView(
diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py
index efaccae..95b0a81 100644
--- a/pysnmp/entity/rfc3413/cmdgen.py
+++ b/pysnmp/entity/rfc3413/cmdgen.py
@@ -1,9 +1,10 @@
-import types, time
+import time
from pysnmp.proto import rfc1157, rfc1905, api, errind
from pysnmp.entity.rfc3413 import config
from pysnmp.proto.proxy import rfc2576
from pysnmp import error, nextid, debug
from pyasn1.type import univ
+from pyasn1.compat.octets import null
getNextHandle = nextid.Integer(0x7fffffff)
@@ -52,8 +53,9 @@ class CommandGeneratorBase:
PDU,
statusInformation,
sendPduHandle,
- (cbFun, cbCtx)
+ cbInfo
):
+ (cbFun, cbCtx) = cbInfo
# 3.1.1
( origTransportDomain,
origTransportAddress,
@@ -154,7 +156,7 @@ class CommandGeneratorBase:
cbFun,
cbCtx=None,
contextEngineId=None,
- contextName=''
+ contextName=null
):
raise error.PySnmpError('Method not implemented')
@@ -175,8 +177,9 @@ class CommandGeneratorBase:
retryCount,
retries,
sendRequestHandle,
- (processResponsePdu, cbCtx)
- ):
+ cbInfo
+ ):
+ (processResponsePdu, cbCtx) = cbInfo
# 3.1
sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu(
snmpEngine,
@@ -226,7 +229,7 @@ class GetCommandGenerator(CommandGeneratorBase):
cbFun,
cbCtx=None,
contextEngineId=None,
- contextName=''
+ contextName=null
):
( transportDomain,
transportAddress,
@@ -285,8 +288,9 @@ class GetCommandGenerator(CommandGeneratorBase):
pMod,
rspPDU,
sendRequestHandle,
- (cbFun, cbCtx)
+ cbInfo
):
+ (cbFun, cbCtx) = cbInfo
cbFun(sendRequestHandle,
None,
pMod.apiPDU.getErrorStatus(rspPDU),
@@ -303,7 +307,7 @@ class SetCommandGenerator(CommandGeneratorBase):
cbFun,
cbCtx=None,
contextEngineId=None,
- contextName=''
+ contextName=null
):
( transportDomain,
transportAddress,
@@ -367,8 +371,9 @@ class SetCommandGenerator(CommandGeneratorBase):
pMod,
rspPDU,
sendRequestHandle,
- (cbFun, cbCtx)
+ cbInfo
):
+ (cbFun, cbCtx) = cbInfo
cbFun(sendRequestHandle,
None,
pMod.apiPDU.getErrorStatus(rspPDU),
@@ -385,7 +390,7 @@ class NextCommandGenerator(CommandGeneratorBase):
cbFun,
cbCtx=None,
contextEngineId=None,
- contextName=''
+ contextName=null
):
( transportDomain,
transportAddress,
@@ -444,8 +449,9 @@ class NextCommandGenerator(CommandGeneratorBase):
pMod,
rspPDU,
sendRequestHandle,
- (cbFun, cbCtx)
+ cbInfo
):
+ (cbFun, cbCtx) = cbInfo
varBindTable = pMod.apiPDU.getVarBindTable(PDU, rspPDU)
if pMod.apiPDU.getErrorStatus(rspPDU):
@@ -500,7 +506,7 @@ class BulkCommandGenerator(CommandGeneratorBase):
cbFun,
cbCtx=None,
contextEngineId=None,
- contextName=''
+ contextName=null
):
( transportDomain,
transportAddress,
@@ -564,8 +570,9 @@ class BulkCommandGenerator(CommandGeneratorBase):
pMod,
rspPDU,
sendRequestHandle,
- (cbFun, cbCtx)
+ cbInfo
):
+ (cbFun, cbCtx) = cbInfo
varBindTable = pMod.apiBulkPDU.getVarBindTable(PDU, rspPDU)
if pMod.apiBulkPDU.getErrorStatus(rspPDU):
diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py
index 5cc664d..eb3c336 100644
--- a/pysnmp/entity/rfc3413/cmdrsp.py
+++ b/pysnmp/entity/rfc3413/cmdrsp.py
@@ -1,3 +1,4 @@
+import sys
from pysnmp.proto import rfc1157, rfc1902, rfc1905, rfc3411, errind, error
from pysnmp.proto.api import v2c # backend is always SMIv2 compliant
from pysnmp.proto.proxy import rfc2576
@@ -17,7 +18,7 @@ class CommandResponderBase:
self.__pendingReqs = {}
def handleMgmtOperation(
- self, snmpEngine, stateReference, contextName, PDU, (acFun, acCtx)
+ self, snmpEngine, stateReference, contextName, PDU, acInfo
): pass
def close(self, snmpEngine):
@@ -65,8 +66,8 @@ class CommandResponderBase:
stateReference,
statusInformation
)
- except error.StatusInformation, why:
- debug.logger & debug.flagApp and debug.logger('sendRsp: stateReference %s, statusInformation %s' % (stateReference, why))
+ except error.StatusInformation:
+ debug.logger & debug.flagApp and debug.logger('sendRsp: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1]))
snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops')
snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1
@@ -145,7 +146,8 @@ class CommandResponderBase:
)
return
# SNMPv2 SMI exceptions
- except pysnmp.smi.error.GenError, errorIndication:
+ except pysnmp.smi.error.GenError:
+ errorIndication = sys.exc_info()[1]
debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication))
if 'oid' in errorIndication:
# Request REPORT generation
@@ -153,31 +155,31 @@ class CommandResponderBase:
statusInformation['val'] = errorIndication['val']
# PDU-level SMI errors
- except pysnmp.smi.error.NoAccessError, errorIndication:
- errorStatus, errorIndex = 'noAccess', errorIndication['idx'] + 1
- except pysnmp.smi.error.WrongTypeError, errorIndication:
- errorStatus, errorIndex = 'wrongType', errorIndication['idx'] + 1
- except pysnmp.smi.error.WrongValueError, errorIndication:
- errorStatus, errorIndex = 'wrongValue', errorIndication['idx'] + 1
- except pysnmp.smi.error.NoCreationError, errorIndication:
- errorStatus, errorIndex = 'noCreation', errorIndication['idx'] + 1
- except pysnmp.smi.error.InconsistentValueError, errorIndication:
- errorStatus, errorIndex = 'inconsistentValue', errorIndication['idx'] + 1
- except pysnmp.smi.error.ResourceUnavailableError, errorIndication:
- errorStatus, errorIndex = 'resourceUnavailable', errorIndication['idx'] + 1
- except pysnmp.smi.error.CommitFailedError, errorIndication:
- errorStatus, errorIndex = 'commitFailedError', errorIndication['idx'] + 1
- except pysnmp.smi.error.UndoFailedError, errorIndication:
- errorStatus, errorIndex = 'undoFailedError', errorIndication['idx'] + 1
- except pysnmp.smi.error.AuthorizationError, errorIndication:
- errorStatus, errorIndex = 'authorizationError', errorIndication['idx'] + 1
- except pysnmp.smi.error.NotWritableError, errorIndication:
- errorStatus, errorIndex = 'notWritable', errorIndication['idx'] + 1
- except pysnmp.smi.error.InconsistentNameError, errorIndication:
- errorStatus, errorIndex = 'inconsistentName', errorIndication['idx'] + 1
- except pysnmp.smi.error.SmiError, errorIndication:
+ except pysnmp.smi.error.NoAccessError:
+ errorStatus, errorIndex = 'noAccess', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.WrongTypeError:
+ errorStatus, errorIndex = 'wrongType', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.WrongValueError:
+ errorStatus, errorIndex = 'wrongValue', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.NoCreationError:
+ errorStatus, errorIndex = 'noCreation', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.InconsistentValueError:
+ errorStatus, errorIndex = 'inconsistentValue', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.ResourceUnavailableError:
+ errorStatus, errorIndex = 'resourceUnavailable', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.CommitFailedError:
+ errorStatus, errorIndex = 'commitFailedError', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.UndoFailedError:
+ errorStatus, errorIndex = 'undoFailedError', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.AuthorizationError:
+ errorStatus, errorIndex = 'authorizationError', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.NotWritableError:
+ errorStatus, errorIndex = 'notWritable', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.InconsistentNameError:
+ errorStatus, errorIndex = 'inconsistentName', sys.exc_info()[1]['idx']+1
+ except pysnmp.smi.error.SmiError:
errorStatus, errorIndex = 'genErr', len(varBinds) and 1 or 0
- except pysnmp.error.PySnmpError, errorIndication:
+ except pysnmp.error.PySnmpError:
self.releaseStateInformation(stateReference)
return
@@ -187,17 +189,17 @@ class CommandResponderBase:
self.releaseStateInformation(stateReference)
- def __verifyAccess(self, name, syntax, idx, viewType,
- (snmpEngine, securityModel, securityName,
- securityLevel, contextName, pduType)
- ):
+ def __verifyAccess(self, name, syntax, idx, viewType, acCtx):
+ (snmpEngine, securityModel, securityName, securityLevel,
+ contextName, pduType) = acCtx
try:
snmpEngine.accessControlModel[self.acmID].isAccessAllowed(
snmpEngine, securityModel, securityName,
securityLevel, viewType, contextName, name
)
# Map ACM errors onto SMI ones
- except error.StatusInformation, statusInformation:
+ except error.StatusInformation:
+ statusInformation = sys.exc_info()[1]
debug.logger & debug.flagApp and debug.logger('__verifyAccess: name %s, statusInformation %s' % (name, statusInformation))
errorIndication = statusInformation['errorIndication']
# 3.2.5...
@@ -238,8 +240,9 @@ class GetCommandResponder(CommandResponderBase):
# rfc1905: 4.2.1
def handleMgmtOperation(
- self, snmpEngine, stateReference, contextName, PDU, (acFun, acCtx)
+ self, snmpEngine, stateReference, contextName, PDU, acInfo
):
+ (acFun, acCtx) = acInfo
# rfc1905: 4.2.1.1
mgmtFun = self.snmpContext.getMibInstrum(contextName).readVars
self.sendRsp(
@@ -254,8 +257,9 @@ class NextCommandResponder(CommandResponderBase):
# rfc1905: 4.2.2
def handleMgmtOperation(
- self, snmpEngine, stateReference, contextName, PDU, (acFun, acCtx)
+ self, snmpEngine, stateReference, contextName, PDU, acInfo
):
+ (acFun, acCtx) = acInfo
# rfc1905: 4.2.2.1
mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars
varBinds = v2c.apiPDU.getVarBinds(PDU)
@@ -263,8 +267,8 @@ class NextCommandResponder(CommandResponderBase):
rspVarBinds = mgmtFun(varBinds, (acFun, acCtx))
try:
self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds)
- except error.StatusInformation, statusInformation:
- idx = statusInformation['idx']
+ except error.StatusInformation:
+ idx = sys.exc_info()[1]['idx']
varBinds[idx] = (rspVarBinds[idx][0], varBinds[idx][1])
else:
break
@@ -276,8 +280,9 @@ class BulkCommandResponder(CommandResponderBase):
# rfc1905: 4.2.3
def handleMgmtOperation(
- self, snmpEngine, stateReference, contextName, PDU, (acFun, acCtx)
+ self, snmpEngine, stateReference, contextName, PDU, acInfo
):
+ (acFun, acCtx) = acInfo
nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU)
if nonRepeaters < 0:
nonRepeaters = 0
@@ -323,8 +328,9 @@ class SetCommandResponder(CommandResponderBase):
# rfc1905: 4.2.5
def handleMgmtOperation(
- self, snmpEngine, stateReference, contextName, PDU, (acFun, acCtx)
+ self, snmpEngine, stateReference, contextName, PDU, acInfo
):
+ (acFun, acCtx) = acInfo
mgmtFun = self.snmpContext.getMibInstrum(contextName).writeVars
# rfc1905: 4.2.5.1-13
try:
@@ -335,7 +341,7 @@ class SetCommandResponder(CommandResponderBase):
)
self.releaseStateInformation(stateReference)
except ( pysnmp.smi.error.NoSuchObjectError,
- pysnmp.smi.error.NoSuchInstanceError ), errorIndication:
+ pysnmp.smi.error.NoSuchInstanceError ):
e = pysnmp.smi.error.NotWritableError()
- e.update(errorIndication)
+ e.update(sys.exc_info()[1])
raise e
diff --git a/pysnmp/entity/rfc3413/config.py b/pysnmp/entity/rfc3413/config.py
index 2750bdc..d031e09 100644
--- a/pysnmp/entity/rfc3413/config.py
+++ b/pysnmp/entity/rfc3413/config.py
@@ -1,5 +1,4 @@
# Shortcuts to MIB instrumentation items used internally in SNMP applications
-import string
from pysnmp.smi.error import SmiError, NoSuchObjectError
from pysnmp.smi.exval import noSuchInstance
from pysnmp.entity import config
@@ -147,7 +146,7 @@ def getTargetNames(snmpEngine, tag):
except NoSuchObjectError:
break
# XXX stop on eot
- if tag in string.split(str(mibNode.syntax)): # XXX add __split__()
+ if tag in mibNode.syntax.asOctets().split(): # XXX add __split__()
idx = mibNode.name[len(snmpTargetAddrTagList.name):]
targetNames.append(
snmpTargetAddrEntry.getIndicesFromInstId(idx)[0]
diff --git a/pysnmp/entity/rfc3413/context.py b/pysnmp/entity/rfc3413/context.py
index 130f84c..75c71a6 100644
--- a/pysnmp/entity/rfc3413/context.py
+++ b/pysnmp/entity/rfc3413/context.py
@@ -1,4 +1,6 @@
# SNMP entity context
+from pyasn1.type import univ
+from pyasn1.compat.octets import null
from pysnmp import error
from pysnmp import debug
@@ -11,26 +13,29 @@ class SnmpContext:
self.contextEngineId = contextEngineId
debug.logger & debug.flagIns and debug.logger('SnmpContext: contextEngineId \"%s\"' % repr(contextEngineId))
self.contextNames = {
- '': snmpEngine.msgAndPduDsp.mibInstrumController # Default name
+ null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name
}
def registerContextName(self, contextName, mibInstrum=None):
+ contextName = univ.OctetString(contextName).asOctets()
if contextName in self.contextNames:
raise error.PySnmpError(
'Duplicate contextName %s' % contextName
)
debug.logger & debug.flagIns and debug.logger('registerContextName: registered contextName \"%s\", mibInstrum %s' % (contextName, mibInstrum))
if mibInstrum is None:
- self.contextNames[contextName] = self.contextNames['']
+ self.contextNames[contextName] = self.contextNames[null]
else:
self.contextNames[contextName] = mibInstrum
def unregisterContextName(self, contextName):
+ contextName = univ.OctetString(contextName).asOctets()
if contextName in self.contextNames:
debug.logger & debug.flagIns and debug.logger('unregisterContextName: unregistered contextName \"%s\"' % contextName)
del self.contextNames[contextName]
def getMibInstrum(self, contextName):
+ contextName = univ.OctetString(contextName).asOctets()
if contextName not in self.contextNames:
debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName \"%s\" not registered' % contextName)
raise error.PySnmpError(
diff --git a/pysnmp/entity/rfc3413/mibvar.py b/pysnmp/entity/rfc3413/mibvar.py
index eebff00..08a0b80 100644
--- a/pysnmp/entity/rfc3413/mibvar.py
+++ b/pysnmp/entity/rfc3413/mibvar.py
@@ -1,13 +1,13 @@
# MIB variable pretty printers/parsers
-import types
from pyasn1.type import univ
from pysnmp.smi.error import NoSuchObjectError
# Name
def mibNameToOid(mibView, name):
- if type(name[0]) == types.TupleType:
- modName, symName = apply(lambda x='',y='': (x,y), name[0])
+ if isinstance(name[0], tuple):
+ f = lambda x='',y='': (x,y)
+ modName, symName = f(*name[0])
if modName: # load module if needed
mibView.mibBuilder.loadModules(modName)
else:
@@ -24,17 +24,22 @@ def mibNameToOid(mibView, name):
if hasattr(mibNode, 'createTest'): # table column XXX
modName, symName, _s = mibView.getNodeLocation(oid[:-1])
rowNode, = mibView.mibBuilder.importSymbols(modName, symName)
- return oid, apply(rowNode.getInstIdFromIndices, suffix)
+ return oid, rowNode.getInstIdFromIndices(*suffix)
else: # scalar or incomplete spec
return oid, suffix
- else:
- oid, label, suffix = mibView.getNodeNameByOid(name)
- return oid, suffix
+ elif not isinstance(name, tuple):
+ name = tuple(univ.ObjectIdentifier(name))
+
+ oid, label, suffix = mibView.getNodeNameByOid(name)
+
+ return oid, suffix
__scalarSuffix = (univ.Integer(0),)
def oidToMibName(mibView, oid):
- _oid, label, suffix = mibView.getNodeNameByOid(tuple(oid))
+ if not isinstance(oid, tuple):
+ oid = tuple(univ.ObjectIdentifier(oid))
+ _oid, label, suffix = mibView.getNodeNameByOid(oid)
modName, symName, __suffix = mibView.getNodeLocation(_oid)
mibNode, = mibView.mibBuilder.importSymbols(
modName, symName
diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py
index 8a05f74..fb5599f 100644
--- a/pysnmp/entity/rfc3413/ntforg.py
+++ b/pysnmp/entity/rfc3413/ntforg.py
@@ -1,4 +1,5 @@
import time
+from pyasn1.compat.octets import null
from pysnmp.entity.rfc3413 import config
from pysnmp.proto.proxy import rfc2576
from pysnmp.proto.api import v2c
@@ -27,8 +28,9 @@ class NotificationOriginator:
PDU,
statusInformation,
sendPduHandle,
- (cbFun, cbCtx)
+ cbInfo
):
+ (cbFun, cbCtx) = cbInfo
# 3.3.6d
( origTransportDomain,
origTransportAddress,
@@ -121,7 +123,7 @@ class NotificationOriginator:
additionalVarBinds=None,
cbFun=None,
cbCtx=None,
- contextName=''
+ contextName=null
):
# 3.3
( notifyTag,
@@ -178,9 +180,8 @@ class NotificationOriginator:
# XXX it's still not clear how to instantiate OBJECTS clause
# # Get notification objects names
# for notificationObject in snmpTrapVal.getObjects():
-# mibNode, = apply(
-# contextMibInstrumCtl.mibBuilder.importSymbols,
-# notificationObject
+# mibNode, = contextMibInstrumCtl.mibBuilder.importSymbols(
+# *notificationObject
# )
# try:
# objectInstance = mibNode.getNode(mibNode.name + (0,))
diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py
index e933330..64f1988 100644
--- a/pysnmp/entity/rfc3413/ntfrcv.py
+++ b/pysnmp/entity/rfc3413/ntfrcv.py
@@ -1,3 +1,4 @@
+from pyasn1.compat.octets import null
from pysnmp.proto import rfc3411, error
from pysnmp.proto.api import v1, v2c # backend is always SMIv2 compliant
from pysnmp.proto.proxy import rfc2576
@@ -13,7 +14,7 @@ class NotificationReceiver:
def __init__(self, snmpEngine, cbFun, cbCtx=None):
snmpEngine.msgAndPduDsp.registerContextEngineId(
- '', self.pduTypes, self.processPdu # '' is a wildcard
+ null, self.pduTypes, self.processPdu # '' is a wildcard
)
self.__cbFunVer = 0
self.__cbFun = cbFun
@@ -21,7 +22,7 @@ class NotificationReceiver:
def close(self, snmpEngine):
snmpEngine.msgAndPduDsp.unregisterContextEngineId(
- '', self.pduTypes
+ null, self.pduTypes
)
def processPdu(
@@ -86,8 +87,8 @@ class NotificationReceiver:
stateReference,
statusInformation
)
- except error.StatusInformation, why:
- debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, statusInformation %s' % (stateReference, why))
+ except error.StatusInformation:
+ debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1]))
snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops')
snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1
diff --git a/pysnmp/entity/rfc3413/oneliner/cmdgen.py b/pysnmp/entity/rfc3413/oneliner/cmdgen.py
index b3f2d75..2b86e89 100644
--- a/pysnmp/entity/rfc3413/oneliner/cmdgen.py
+++ b/pysnmp/entity/rfc3413/oneliner/cmdgen.py
@@ -1,11 +1,12 @@
-import socket, string, types
+import socket, sys
from pysnmp.entity import engine, config
from pysnmp.entity.rfc3413 import cmdgen, mibvar
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.proto import errind
from pysnmp.smi import view
from pysnmp import nextid, error
-from pyasn1.type import univ
+from pyasn1.type import univ, base
+from pyasn1.compat.octets import null
# Auth protocol
usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol
@@ -20,13 +21,13 @@ usmAesCfb192Protocol = config.usmAesCfb192Protocol
usmAesCfb256Protocol = config.usmAesCfb256Protocol
usmNoPrivProtocol = config.usmNoPrivProtocol
-nextID = nextid.Integer(0xffffffffL)
+nextID = nextid.Integer(0xffffffff)
class CommunityData:
mpModel = 1 # Default is SMIv2
securityModel = mpModel+1
securityLevel = 'noAuthNoPriv'
- contextName = ''
+ contextName = null
def __init__(self, securityName, communityName, mpModel=None,
contextEngineId=None, contextName=None):
self.securityName = securityName
@@ -50,7 +51,13 @@ class CommunityData:
)
def __hash__(self): return self.__hash
- def __cmp__(self, other): return cmp(self.__cmp, other)
+
+ def __eq__(self, other): return self.__cmp == other
+ def __ne__(self, other): return self.__cmp != other
+ def __lt__(self, other): return self.__cmp < other
+ def __le__(self, other): return self.__cmp <= other
+ def __gt__(self, other): return self.__cmp > other
+ def __ge__(self, other): return self.__cmp >= other
class UsmUserData:
authKey = privKey = None
@@ -59,7 +66,7 @@ class UsmUserData:
securityLevel = 'noAuthNoPriv'
securityModel = 3
mpModel = 2
- contextName = ''
+ contextName = null
def __init__(self, securityName,
authKey=None, privKey=None,
authProtocol=None, privProtocol=None,
@@ -103,7 +110,13 @@ class UsmUserData:
)
def __hash__(self): return self.__hash
- def __cmp__(self, other): return cmp(self.__cmp, other)
+
+ def __eq__(self, other): return self.__cmp == other
+ def __ne__(self, other): return self.__cmp != other
+ def __lt__(self, other): return self.__cmp < other
+ def __le__(self, other): return self.__cmp <= other
+ def __gt__(self, other): return self.__cmp > other
+ def __ge__(self, other): return self.__cmp >= other
class UdpTransportTarget:
transportDomain = udp.domainName
@@ -121,7 +134,13 @@ class UdpTransportTarget:
)
def __hash__(self): return hash(self.transportAddr)
- def __cmp__(self, other): return cmp(self.transportAddr, other)
+
+ def __eq__(self, other): return self.transportAddr == other
+ def __ne__(self, other): return self.transportAddr != other
+ def __lt__(self, other): return self.transportAddr < other
+ def __le__(self, other): return self.transportAddr <= other
+ def __gt__(self, other): return self.transportAddr > other
+ def __ge__(self, other): return self.transportAddr >= other
def openClientMode(self):
self.transport = udp.UdpSocketTransport().openClientMode()
@@ -143,7 +162,7 @@ class AsynCommandGenerator:
def __del__(self): self.uncfgCmdGen()
- def cfgCmdGen(self, authData, transportTarget, tagList=''):
+ def cfgCmdGen(self, authData, transportTarget, tagList=null):
if isinstance(authData, CommunityData):
tagList = '%s %s' % (tagList, authData.securityName)
if authData in self.__knownAuths:
@@ -241,10 +260,15 @@ class AsynCommandGenerator:
)
self.__knownTransportAddrs.clear()
+ if sys.version_info[0] <= 2:
+ intTypes = (int, long)
+ else:
+ intTypes = (int,)
+
def makeReadVarBinds(self, varNames):
varBinds = []
for varName in varNames:
- if type(varName[0]) in (types.IntType, types.LongType):
+ if isinstance(varName[0], self.intTypes):
name = varName
else:
name, oid = mibvar.mibNameToOid(
@@ -256,9 +280,8 @@ class AsynCommandGenerator:
# Async SNMP apps
- def getCmd(
- self, authData, transportTarget, varNames, (cbFun, cbCtx)
- ):
+ def getCmd(self, authData, transportTarget, varNames, cbInfo):
+ (cbFun, cbCtx) = cbInfo
addrName, paramsName = self.cfgCmdGen(
authData, transportTarget
)
@@ -270,9 +293,8 @@ class AsynCommandGenerator:
asyncGetCmd = getCmd
- def setCmd(
- self, authData, transportTarget, varBinds, (cbFun, cbCtx)
- ):
+ def setCmd(self, authData, transportTarget, varBinds, cbInfo):
+ (cbFun, cbCtx) = cbInfo
addrName, paramsName = self.cfgCmdGen(
authData, transportTarget
)
@@ -281,7 +303,7 @@ class AsynCommandGenerator:
name, oid = mibvar.mibNameToOid(
self.mibViewController, varName
)
- if not type(varVal) == types.InstanceType:
+ if not isinstance(varVal, base.AbstractSimpleAsn1Item):
((symName, modName), suffix) = mibvar.oidToMibName(
self.mibViewController, name + oid
)
@@ -301,9 +323,8 @@ class AsynCommandGenerator:
asyncSetCmd = setCmd
- def nextCmd(
- self, authData, transportTarget, varNames, (cbFun, cbCtx)
- ):
+ def nextCmd(self, authData, transportTarget, varNames, cbInfo):
+ (cbFun, cbCtx) = cbInfo
addrName, paramsName = self.cfgCmdGen(
authData, transportTarget
)
@@ -315,10 +336,9 @@ class AsynCommandGenerator:
asyncNextCmd = nextCmd
- def bulkCmd(
- self, authData, transportTarget, nonRepeaters, maxRepetitions,
- varNames, (cbFun, cbCtx)
- ):
+ def bulkCmd(self, authData, transportTarget, nonRepeaters, maxRepetitions,
+ varNames, cbInfo):
+ (cbFun, cbCtx) = cbInfo
addrName, paramsName = self.cfgCmdGen(
authData, transportTarget
)
@@ -388,10 +408,9 @@ class CommandGenerator:
)
def nextCmd(self, authData, transportTarget, *varNames):
- def __cbFun(
- sendRequestHandle, errorIndication, errorStatus, errorIndex,
- varBindTable, (self, varBindHead, varBindTotalTable, appReturn)
- ):
+ def __cbFun(sendRequestHandle, errorIndication,
+ errorStatus, errorIndex, varBindTable, cbCtx):
+ (self, varBindHead, varBindTotalTable, appReturn) = cbCtx
if errorStatus or \
errorIndication and not self.ignoreNonIncreasingOid or \
errorIndication and self.ignoreNonIncreasingOid and \
@@ -453,10 +472,9 @@ class CommandGenerator:
def bulkCmd(self, authData, transportTarget,
nonRepeaters, maxRepetitions, *varNames):
- def __cbFun(
- sendRequestHandle, errorIndication, errorStatus, errorIndex,
- varBindTable, (self, varBindHead, varBindTotalTable, appReturn)
- ):
+ def __cbFun(sendRequestHandle, errorIndication,
+ errorStatus, errorIndex, varBindTable, cbCtx):
+ (self, varBindHead, varBindTotalTable, appReturn) = cbCtx
if errorStatus or \
errorIndication and not self.ignoreNonIncreasingOid or \
errorIndication and self.ignoreNonIncreasingOid and \
diff --git a/pysnmp/entity/rfc3413/oneliner/ntforg.py b/pysnmp/entity/rfc3413/oneliner/ntforg.py
index 76c8c71..835d53d 100644
--- a/pysnmp/entity/rfc3413/oneliner/ntforg.py
+++ b/pysnmp/entity/rfc3413/oneliner/ntforg.py
@@ -1,4 +1,4 @@
-import types, string
+from pyasn1.type import base
from pysnmp.entity import config
from pysnmp.entity.rfc3413 import ntforg, context, mibvar
from pysnmp.entity.rfc3413.oneliner import cmdgen
@@ -83,9 +83,10 @@ class AsynNotificationOriginator(cmdgen.AsynCommandGenerator):
def sendNotification(
self, authData, transportTarget, notifyType,
- notificationType, varBinds=None, (cbFun, cbCtx)=(None, None)
+ notificationType, varBinds=None, cbInfo=(None, None)
):
- tagList = string.replace(str(transportTarget.transportAddr), ' ', '_')
+ (cbFun, cbCtx) = cbInfo
+ tagList = str(transportTarget.transportAddr).replace(' ', '_')
notifyName = self.cfgNtfOrg(authData, transportTarget,
notifyType, tagList)
if notificationType:
@@ -99,7 +100,7 @@ class AsynNotificationOriginator(cmdgen.AsynCommandGenerator):
name, oid = mibvar.mibNameToOid(
self.mibViewController, varName
)
- if not type(varVal) == types.InstanceType:
+ if not isinstance(varVal, base.Asn1ItemBase):
((symName, modName), suffix) = mibvar.oidToMibName(
self.mibViewController, name + oid
)
diff --git a/pysnmp/entity/rfc3413/twisted/cmdgen.py b/pysnmp/entity/rfc3413/twisted/cmdgen.py
index 64cd6a6..aabc8e5 100644
--- a/pysnmp/entity/rfc3413/twisted/cmdgen.py
+++ b/pysnmp/entity/rfc3413/twisted/cmdgen.py
@@ -1,5 +1,6 @@
from twisted.internet import defer
from pysnmp.entity.rfc3413 import cmdgen
+from pyasn1.compat.octets import null
def _cbFun(sendRequestHandle, errorIndication,
errorStatus, errorIndex, varBinds, cbCtx):
@@ -12,7 +13,7 @@ class GetCommandGenerator(cmdgen.GetCommandGenerator):
addrName,
varBinds,
contextEngineId=None,
- contextName=''
+ contextName=null
):
df = defer.Deferred()
cmdgen.GetCommandGenerator.sendReq(
@@ -34,7 +35,7 @@ class SetCommandGenerator(cmdgen.SetCommandGenerator):
addrName,
varBinds,
contextEngineId=None,
- contextName=''
+ contextName=null
):
df = defer.Deferred()
cmdgen.SetCommandGenerator.sendReq(
@@ -68,7 +69,7 @@ class NextCommandGenerator(cmdgen.NextCommandGenerator):
addrName,
varBinds,
contextEngineId=None,
- contextName=''
+ contextName=null
):
df = defer.Deferred()
cmdgen.NextCommandGenerator.sendReq(
@@ -92,7 +93,7 @@ class BulkCommandGenerator(cmdgen.BulkCommandGenerator):
maxRepetitions,
varBinds,
contextEngineId=None,
- contextName=''
+ contextName=null
):
df = defer.Deferred()
cmdgen.BulkCommandGenerator.sendReq(
@@ -105,7 +106,7 @@ class BulkCommandGenerator(cmdgen.BulkCommandGenerator):
_cbFunWithDeferred,
{ 'df': df }, # anonymous dictionary used for cbCtx
contextEngineId=None,
- contextName=''
+ contextName=null
)
return df
diff --git a/pysnmp/entity/rfc3413/twisted/ntforg.py b/pysnmp/entity/rfc3413/twisted/ntforg.py
index e02f2ab..1b92929 100644
--- a/pysnmp/entity/rfc3413/twisted/ntforg.py
+++ b/pysnmp/entity/rfc3413/twisted/ntforg.py
@@ -1,5 +1,6 @@
from twisted.internet import reactor, defer
from pysnmp.entity.rfc3413 import ntforg
+from pyasn1.compat.octets import null
class NotificationOriginator(ntforg.NotificationOriginator):
def sendNotification(
@@ -8,7 +9,7 @@ class NotificationOriginator(ntforg.NotificationOriginator):
notificationTarget,
notificationName,
additionalVarBinds=None,
- contextName=''
+ contextName=null
):
df = defer.Deferred()
ntforg.NotificationOriginator.sendNotification(
@@ -19,7 +20,7 @@ class NotificationOriginator(ntforg.NotificationOriginator):
additionalVarBinds,
None,
df,
- contextName=''
+ contextName=null
)
return df
diff --git a/pysnmp/error.py b/pysnmp/error.py
index 48ab101..509b16b 100644
--- a/pysnmp/error.py
+++ b/pysnmp/error.py
@@ -1 +1 @@
-class PySnmpError(StandardError): pass
+class PySnmpError(Exception): pass
diff --git a/pysnmp/nextid.py b/pysnmp/nextid.py
index 3e60a4f..bc3dc1e 100644
--- a/pysnmp/nextid.py
+++ b/pysnmp/nextid.py
@@ -9,9 +9,9 @@ class Integer:
if increment >= maximum:
increment = maximum
self.__increment = increment
- self.__threshold = increment/2
+ self.__threshold = increment//2
e = random.randrange(self.__maximum - self.__increment)
- self.__bank = range(e, e+self.__increment)
+ self.__bank = list(range(e, e+self.__increment))
def __repr__(self):
return '%s(%d, %d)' % (
diff --git a/pysnmp/proto/acmod/rfc3415.py b/pysnmp/proto/acmod/rfc3415.py
index 103df03..e2801b2 100644
--- a/pysnmp/proto/acmod/rfc3415.py
+++ b/pysnmp/proto/acmod/rfc3415.py
@@ -96,8 +96,8 @@ def isAccessAllowed(
continue
if vacmViewTreeFamilyMask.syntax:
mask = []
- for c in map(None, str(vacmViewTreeFamilyMask.syntax)):
- mask = mask + map(lambda b,c=ord(c): b&c, __powOfTwoSeq)
+ for c in vacmViewTreeFamilyMask.syntax.asNumbers():
+ mask = mask + [ b&c for b in __powOfTwoSeq ]
m = len(mask)-1
idx = l-1
while idx:
diff --git a/pysnmp/proto/api/v1.py b/pysnmp/proto/api/v1.py
index da96a2a..66af103 100644
--- a/pysnmp/proto/api/v1.py
+++ b/pysnmp/proto/api/v1.py
@@ -1,4 +1,3 @@
-import types
from pyasn1.type import univ
from pysnmp.proto import rfc1155, rfc1157, error
from pysnmp import nextid
@@ -27,7 +26,8 @@ TrapPDU = rfc1157.TrapPDU
Message = rfc1157.Message
class VarBindAPI:
- def setOIDVal(self, varBind, (oid, val)):
+ def setOIDVal(self, varBind, oidVal):
+ (oid, val) = oidVal
varBind.setComponentByPosition(0, oid)
if val is None: val = null
varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(), val, 1, verifyConstraints=False)
@@ -91,7 +91,7 @@ class PDUAPI:
varBindList.clear()
idx = 0
for varBind in varBinds:
- if type(varBind) is types.InstanceType:
+ if isinstance(varBind, VarBind):
varBindList.setComponentByPosition(idx, varBind)
else:
varBindList.setComponentByPosition(idx)
@@ -165,7 +165,7 @@ class TrapPDUAPI:
varBindList.clear()
idx = 0
for varBind in varBinds:
- if type(varBind) is types.InstanceType:
+ if isinstance(varBind, VarBind):
varBindList.setComponentByPosition(idx, varBind)
else:
varBindList.setComponentByPosition(idx)
diff --git a/pysnmp/proto/cache.py b/pysnmp/proto/cache.py
index e5a49d3..f4bb6b3 100644
--- a/pysnmp/proto/cache.py
+++ b/pysnmp/proto/cache.py
@@ -24,7 +24,7 @@ class Cache:
self.__cacheRepository[index].update(kwargs)
def expire(self, cbFun, cbCtx):
- for index, cachedParams in self.__cacheRepository.items():
+ for index, cachedParams in list(self.__cacheRepository.items()):
if cbFun:
if cbFun(index, cachedParams, cbCtx):
del self.__cacheRepository[index]
diff --git a/pysnmp/proto/errind.py b/pysnmp/proto/errind.py
index bc9c471..1e41451 100644
--- a/pysnmp/proto/errind.py
+++ b/pysnmp/proto/errind.py
@@ -1,17 +1,19 @@
# SNMPv3 error-indication values.
# Object below could be compared with literals thus are backward-compatible
# with original pysnmperror-indication values.
-from string import lower
class ErrorIndication:
def __init__(self, descr=None):
- self.__value = self.__descr = lower(self.__class__.__name__[0]) + self.__class__.__name__[1:]
+ self.__value = self.__descr = self.__class__.__name__[0].lower() + self.__class__.__name__[1:]
if descr: self.__descr = descr
- def __cmp__(self, other):
- if self is other or isinstance(other, self.__class__):
- return 0
- else:
- return cmp(self.__value, other)
+
+ def __eq__(self, other): return self.__value == other
+ def __ne__(self, other): return self.__value != other
+ def __lt__(self, other): return self.__value < other
+ def __le__(self, other): return self.__value <= other
+ def __gt__(self, other): return self.__value > other
+ def __ge__(self, other): return self.__value >= other
+
def __str__(self): return self.__descr
# SNMP message processing errors
diff --git a/pysnmp/proto/mpmod/cache.py b/pysnmp/proto/mpmod/cache.py
index a116eea..504b139 100644
--- a/pysnmp/proto/mpmod/cache.py
+++ b/pysnmp/proto/mpmod/cache.py
@@ -10,7 +10,7 @@ class Cache:
self.__sendPduHandleIdx = {}
# Message expiration mechanics
self.__expirationQueue = {}
- self.__expirationTimer = 0L
+ self.__expirationTimer = 0
# Server mode cache handling
@@ -89,10 +89,10 @@ class Cache:
if self.__expirationTimer in self.__expirationQueue:
cacheInfo = self.__expirationQueue[self.__expirationTimer]
if 'stateReference' in cacheInfo:
- for stateReference in cacheInfo['stateReference'].keys():
+ for stateReference in cacheInfo['stateReference']:
del self.__stateReferenceIndex[stateReference]
if 'msgId' in cacheInfo:
- for msgId in cacheInfo['msgId'].keys():
+ for msgId in cacheInfo['msgId']:
del self.__msgIdIndex[msgId]
del self.__expirationQueue[self.__expirationTimer]
self.__expirationTimer = self.__expirationTimer + 1
diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py
index aa34603..d374747 100644
--- a/pysnmp/proto/mpmod/rfc2576.py
+++ b/pysnmp/proto/mpmod/rfc2576.py
@@ -1,11 +1,12 @@
# SNMP v1 & v2c message processing models implementation
from pyasn1.codec.ber import decoder
+from pyasn1.type import univ
+from pyasn1.compat.octets import null
+from pyasn1.error import PyAsn1Error
from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel
from pysnmp.proto.secmod import rfc2576
from pysnmp.proto import rfc3411, errind, error
from pysnmp.proto.api import v1, v2c
-from pyasn1.type import univ
-from pyasn1.error import PyAsn1Error
from pysnmp import debug
# Since I have not found a detailed reference to v1MP/v2cMP
@@ -48,7 +49,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.5
if not contextName:
- contextName = ''
+ contextName = null
debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %s contextName %s' % (repr(contextEngineId), contextName))
@@ -95,7 +96,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
if pdu.tagSet in rfc3411.confirmedClassPDUs:
# XXX rfc bug? why stateReference should be created?
self._cache.pushByMsgId(
- long(msgID),
+ int(msgID),
sendPduHandle=sendPduHandle,
msgID=msgID,
snmpEngineID=snmpEngineID,
@@ -161,7 +162,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# rfc3412: 7.1.5
if not contextName:
- contextName = ''
+ contextName = null
# rfc3412: 7.1.6
scopedPDU = ( contextEngineId, contextName, pdu )
@@ -294,7 +295,7 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel):
# 7.2.10a
try:
- cachedReqParams = self._cache.popByMsgId(long(msgID))
+ cachedReqParams = self._cache.popByMsgId(int(msgID))
except error.ProtocolError:
smHandler.releaseStateInformation(securityStateReference)
raise error.StatusInformation(
diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py
index 79bfb23..6bb225f 100644
--- a/pysnmp/proto/mpmod/rfc3412.py
+++ b/pysnmp/proto/mpmod/rfc3412.py
@@ -1,4 +1,5 @@
# SNMP v3 message processing model implementation
+import sys
from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel
from pysnmp.proto.secmod import rfc3414
from pysnmp.proto import rfc1905, rfc3411, api, errind, error
@@ -27,15 +28,15 @@ class ScopedPduData(univ.Choice):
class HeaderData(univ.Sequence):
componentType = namedtype.NamedTypes(
- namedtype.NamedType('msgID', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))),
- namedtype.NamedType('msgMaxSize', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647L))),
+ namedtype.NamedType('msgID', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))),
+ namedtype.NamedType('msgMaxSize', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647))),
namedtype.NamedType('msgFlags', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 1))),
- namedtype.NamedType('msgSecurityModel', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L)))
+ namedtype.NamedType('msgSecurityModel', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647)))
)
class SNMPv3Message(univ.Sequence):
componentType = namedtype.NamedTypes(
- namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))),
+ namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))),
namedtype.NamedType('msgGlobalData', HeaderData()),
namedtype.NamedType('msgSecurityParameters', univ.OctetString()),
namedtype.NamedType('msgData', ScopedPduData())
@@ -68,7 +69,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
AbstractMessageProcessingModel.__init__(self)
self.__engineIDs = {}
self.__engineIDsExpQueue = {}
- self.__expirationTimer = 0L
+ self.__expirationTimer = 0
# 7.1.1a
def prepareOutgoingMessage(
@@ -213,7 +214,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
else:
securityEngineID = peerSnmpEngineData['securityEngineID']
- debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: securityEngineID %s' % securityEngineID)
+ debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: securityEngineID %s' % repr(securityEngineID))
# 7.1.9.b
( securityParameters,
@@ -431,7 +432,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
scopedPDU,
securityStateReference
)
- except error.StatusInformation, statusInformation:
+ except error.StatusInformation:
# 7.1.8.b
raise
@@ -470,7 +471,7 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
headerData = msg.getComponentByPosition(1)
msgVersion = messageProcessingModel = msg.getComponentByPosition(0)
msgID = headerData.getComponentByPosition(0)
- msgFlags = ord(str(headerData.getComponentByPosition(2)))
+ msgFlags, = headerData.getComponentByPosition(2).asNumbers()
maxMessageSize = headerData.getComponentByPosition(1)
securityModel = headerData.getComponentByPosition(3)
securityParameters = msg.getComponentByPosition(2)
@@ -522,7 +523,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel):
msg
)
debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded')
- except error.StatusInformation, statusInformation:
+ except error.StatusInformation:
+ statusInformation = sys.exc_info()[1]
debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM failed, statusInformation %s' % statusInformation)
if 'errorIndication' in statusInformation:
# 7.2.6a
diff --git a/pysnmp/proto/proxy/rfc2576.py b/pysnmp/proto/proxy/rfc2576.py
index e2554fc..470043a 100644
--- a/pysnmp/proto/proxy/rfc2576.py
+++ b/pysnmp/proto/proxy/rfc2576.py
@@ -159,7 +159,7 @@ def v1ToV2(v1Pdu, origV2Pdu=None):
# 4.1.2.1 --> no-op
if pduType not in rfc3411.notificationClassPDUs:
- v2c.apiPDU.setRequestID(v2Pdu, long(v1.apiPDU.getRequestID(v1Pdu)))
+ v2c.apiPDU.setRequestID(v2Pdu, int(v1.apiPDU.getRequestID(v1Pdu)))
v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds)
diff --git a/pysnmp/proto/rfc1155.py b/pysnmp/proto/rfc1155.py
index 08bd591..4ad6d18 100644
--- a/pysnmp/proto/rfc1155.py
+++ b/pysnmp/proto/rfc1155.py
@@ -1,39 +1,7 @@
-import string
from pyasn1.type import univ, tag, constraint, namedtype
from pyasn1.error import PyAsn1Error
from pysnmp.proto import error
-def ipAddressPrettyIn(value):
- if len(value) == 4:
- return value # IP as an octet stream
- try:
- packed = string.split(value, '.')
- except:
- raise error.ProtocolError(
- 'Bad IP address syntax %s' % value
- )
- if len(packed) != 4:
- raise error.ProtocolError(
- 'Bad IP address syntax %s' % value
- )
- try:
- return reduce(
- lambda x, y: x+y,
- map(lambda x: chr(string.atoi(x)), packed)
- )
- except string.atoi_error:
- raise error.ProtocolError(
- 'Bad IP address value %s' % value
- )
-
-def ipAddressPrettyOut(value):
- if value:
- return '%d.%d.%d.%d' % (
- ord(value[0]), ord(value[1]), ord(value[2]), ord(value[3])
- )
- else:
- return ''
-
class IpAddress(univ.OctetString):
tagSet = univ.OctetString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00)
@@ -42,15 +10,30 @@ class IpAddress(univ.OctetString):
4, 4
)
- def prettyIn(self, value): return ipAddressPrettyIn(value)
- def prettyOut(self, value): return ipAddressPrettyOut(value)
+ def prettyIn(self, value):
+ if isinstance(value, str) and len(value) != 4:
+ try:
+ value = [ int(x) for x in value.split('.') ]
+ except:
+ raise error.ProtocolError('Bad IP address syntax %s' % value)
+ if len(value) != 4:
+ raise error.ProtocolError('Bad IP address syntax')
+ return univ.OctetString.prettyIn(self, value)
+
+ def prettyOut(self, value):
+ if value:
+ return '.'.join(
+ [ '%d' % x for x in self.__class__(value).asNumbers() ]
+ )
+ else:
+ return ''
class Counter(univ.Integer):
tagSet = univ.Integer.tagSet.tagImplicitly(
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class NetworkAddress(univ.Choice):
@@ -63,7 +46,7 @@ class Gauge(univ.Integer):
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class TimeTicks(univ.Integer):
@@ -71,7 +54,7 @@ class TimeTicks(univ.Integer):
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class Opaque(univ.OctetString):
diff --git a/pysnmp/proto/rfc1902.py b/pysnmp/proto/rfc1902.py
index ef9e4ff..b12df7a 100644
--- a/pysnmp/proto/rfc1902.py
+++ b/pysnmp/proto/rfc1902.py
@@ -1,16 +1,14 @@
-import types
-import string
from pyasn1.type import univ, tag, constraint, namedtype, namedval
from pysnmp.proto import rfc1155, error
class Integer(univ.Integer):
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- -2147483648L, 2147483647L
+ -2147483648, 2147483647
)
class Integer32(univ.Integer):
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- -2147483648L, 2147483647L
+ -2147483648, 2147483647
)
class OctetString(univ.OctetString):
@@ -41,15 +39,31 @@ class IpAddress(univ.OctetString):
4, 4
)
fixedLength = 4
- def prettyIn(self, value): return rfc1155.ipAddressPrettyIn(value)
- def prettyOut(self, value): return rfc1155.ipAddressPrettyOut(value)
+
+ def prettyIn(self, value):
+ if isinstance(value, str) and len(value) != 4:
+ try:
+ value = [ int(x) for x in value.split('.') ]
+ except:
+ raise error.ProtocolError('Bad IP address syntax %s' % value)
+ if len(value) != 4:
+ raise error.ProtocolError('Bad IP address syntax')
+ return univ.OctetString.prettyIn(self, value)
+
+ def prettyOut(self, value):
+ if value:
+ return '.'.join(
+ [ '%d' % x for x in self.__class__(value).asNumbers() ]
+ )
+ else:
+ return ''
class Counter32(univ.Integer):
tagSet = univ.Integer.tagSet.tagImplicitly(
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class Gauge32(univ.Integer):
@@ -57,7 +71,7 @@ class Gauge32(univ.Integer):
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class Unsigned32(univ.Integer):
@@ -65,7 +79,7 @@ class Unsigned32(univ.Integer):
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class TimeTicks(univ.Integer):
@@ -73,7 +87,7 @@ class TimeTicks(univ.Integer):
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 4294967295L
+ 0, 4294967295
)
class Opaque(univ.OctetString):
@@ -86,7 +100,7 @@ class Counter64(univ.Integer):
tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x06)
)
subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint(
- 0, 18446744073709551615L
+ 0, 18446744073709551615
)
class Bits(univ.OctetString):
@@ -102,8 +116,8 @@ class Bits(univ.OctetString):
)
def prettyIn(self, bits):
- if type(bits) not in (types.TupleType, types.ListType):
- return str(bits) # raw bitstring
+ if not isinstance(bits, (tuple, list)):
+ return univ.OctetString.prettyIn(self, bits) # raw bitstring
octets = []
for bit in bits: # tuple of named bits
v = self.__namedValues.getValue(bit)
@@ -115,14 +129,14 @@ class Bits(univ.OctetString):
if d >= len(octets):
octets.extend([0] * (d - len(octets) + 1))
octets[d] = octets[d] | 0x01 << (7-m)
- return string.join(map(lambda x: chr(x), octets), '')
+ return univ.OctetString.prettyIn(self, octets)
def prettyOut(self, value):
names = []
- octets = tuple(map(None, str(value)))
+ ints = self.__class__(value).asNumbers()
i = 0
- while i < len(octets):
- v = ord(octets[i])
+ while i < len(ints):
+ v = ints[i]
j = 7
while j >= 0:
if v & (0x01<<j):
@@ -134,7 +148,7 @@ class Bits(univ.OctetString):
names.append(name)
j = j - 1
i = i + 1
- return string.join(map(lambda x: str(x), names), ', ')
+ return ', '.join([ str(x) for x in names ])
def clone(self, value=None, tagSet=None, subtypeSpec=None,
namedValues=None):
diff --git a/pysnmp/proto/rfc1905.py b/pysnmp/proto/rfc1905.py
index b44aa5a..e35c6a2 100644
--- a/pysnmp/proto/rfc1905.py
+++ b/pysnmp/proto/rfc1905.py
@@ -2,7 +2,7 @@ from pyasn1.type import univ, tag, constraint, namedtype, namedval
from pysnmp.proto import rfc1902
# Value reference -- max bindings in VarBindList
-max_bindings = rfc1902.Integer(2147483647L)
+max_bindings = rfc1902.Integer(2147483647)
# Take SNMP exception values out of BindValue structure for convenience
diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py
index 3abc26e..3ef339a 100644
--- a/pysnmp/proto/rfc3412.py
+++ b/pysnmp/proto/rfc3412.py
@@ -1,5 +1,6 @@
"""SNMP v3 Message Processing and Dispatching (RFC3412)"""
-import time
+import time, sys
+from pyasn1.compat.octets import null
from pysnmp.smi import builder, instrum
from pysnmp.proto import errind, error, cache
from pysnmp.proto.api import verdec # XXX
@@ -52,7 +53,7 @@ class MsgAndPduDispatcher:
# 4.3.3
for pduType in pduTypes:
- k = (str(contextEngineId), pduType)
+ k = (contextEngineId, pduType)
if k in self.__appsRegistration:
raise error.ProtocolError(
'Duplicate registration %s/%s' % (contextEngineId, pduType)
@@ -71,17 +72,17 @@ class MsgAndPduDispatcher:
contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')
for pduType in pduTypes:
- k = (str(contextEngineId), pduType)
+ k = (contextEngineId, pduType)
if k in self.__appsRegistration:
del self.__appsRegistration[k]
debug.logger & debug.flagDsp and debug.logger('unregisterContextEngineId: contextEngineId %s pduTypes %s' % (repr(contextEngineId), pduTypes))
def getRegisteredApp(self, contextEngineId, pduType):
- k = ( str(contextEngineId), pduType )
+ k = (contextEngineId, pduType)
if k in self.__appsRegistration:
return self.__appsRegistration[k]
- k = ( '', pduType )
+ k = ( null, pduType )
if k in self.__appsRegistration:
return self.__appsRegistration[k] # wildcard
@@ -153,7 +154,7 @@ class MsgAndPduDispatcher:
sendPduHandle
)
debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded')
- except error.StatusInformation, statusInformation:
+ except error.StatusInformation:
# XXX is it still needed here?
# self.releaseStateInformation(snmpEngine, sendPduHandle, messageProcessingModel)
raise
@@ -229,7 +230,7 @@ class MsgAndPduDispatcher:
statusInformation
)
debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded')
- except error.StatusInformation, statusInformation:
+ except error.StatusInformation:
# 4.1.2.3
raise
@@ -265,12 +266,12 @@ class MsgAndPduDispatcher:
# 4.2.1.2
try:
- restOfWholeMsg = '' # XXX fix decoder non-recursive return
+ restOfWholeMsg = null # XXX fix decoder non-recursive return
msgVersion = verdec.decodeMessageVersion(wholeMsg)
except PySnmpError:
snmpInAsn1ParseErrs, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInAsn1ParseErrs')
snmpInAsn1ParseErrs.syntax = snmpInAsn1ParseErrs.syntax + 1
- return '' # n.b the whole buffer gets dropped
+ return null # n.b the whole buffer gets dropped
debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion)
@@ -307,7 +308,8 @@ class MsgAndPduDispatcher:
wholeMsg
)
debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded')
- except error.StatusInformation, statusInformation:
+ except error.StatusInformation:
+ statusInformation = sys.exc_info()[1]
if 'sendPduHandle' in statusInformation:
# Dropped REPORT -- re-run pending reqs queue as some
# of them may be waiting for this REPORT
@@ -364,8 +366,8 @@ class MsgAndPduDispatcher:
stateReference,
statusInformation
)
- except error.StatusInformation, statusInformation:
- debug.logger & debug.flagDsp and debug.logger('receiveMessage: report failed, statusInformation %s' % statusInformation)
+ except error.StatusInformation:
+ debug.logger & debug.flagDsp and debug.logger('receiveMessage: report failed, statusInformation %s' % sys.exc_info()[1])
return restOfWholeMsg
# 4.2.2.1.2.c
diff --git a/pysnmp/proto/secmod/eso/priv/des3.py b/pysnmp/proto/secmod/eso/priv/des3.py
index 6163039..f5a4d88 100644
--- a/pysnmp/proto/secmod/eso/priv/des3.py
+++ b/pysnmp/proto/secmod/eso/priv/des3.py
@@ -1,16 +1,12 @@
# Reeder 3DES-EDE for USM (Internet draft)
# http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt
-import random, string
+import random
from pysnmp.proto.secmod.rfc3414.priv import base
from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha
from pysnmp.proto.secmod.rfc3414 import localkey
from pysnmp.proto import errind, error
from pyasn1.type import univ
-
-try:
- from sys import version_info
-except ImportError:
- version_info = ( 0, 0 ) # a really early version
+from pyasn1.compat.octets import null
try:
from Crypto.Cipher import DES3
@@ -23,10 +19,7 @@ random.seed()
class Des3(base.AbstractEncryptionService):
serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol
- if version_info < (2, 3):
- _localInt = long(random.random()*0xffffffffL)
- else:
- _localInt = random.randrange(0, 0xffffffffL)
+ _localInt = random.randrange(0, 0xffffffff)
def hashPassphrase(self, authProtocol, privKey):
if authProtocol == hmacmd5.HmacMd5.serviceID:
@@ -61,7 +54,7 @@ class Des3(base.AbstractEncryptionService):
des3Key = privKey[:24]
preIV = privKey[24:32]
- securityEngineBoots = long(snmpEngineBoots)
+ securityEngineBoots = int(snmpEngineBoots)
salt = [
securityEngineBoots>>24&0xff,
@@ -73,21 +66,20 @@ class Des3(base.AbstractEncryptionService):
self._localInt>>8&0xff,
self._localInt&0xff
]
- if self._localInt == 0xffffffffL:
+ if self._localInt == 0xffffffff:
self._localInt = 0
else:
self._localInt = self._localInt + 1
# salt not yet hashed XXX
- return des3Key, \
- string.join(map(chr, salt), ''), \
- string.join(map(lambda x,y: chr(x^ord(y)), salt, preIV), '')
-
+ return des3Key.asOctets(), \
+ univ.OctetString(salt).asOctets(), \
+ univ.OctetString(map(lambda x,y:x^y, salt, preIV.asNumbers())).asOctets()
+
def __getDecryptionKey(self, privKey, salt):
- return privKey[:24], string.join(
- map(lambda x,y: chr(ord(x)^ord(y)), salt, privKey[24:32]), ''
- )
+ return privKey[:24].asOctets(), \
+ univ.OctetString(map(lambda x,y:x^y, salt, privKey[24:32].asNumbers())).asOctets()
# 5.1.1.2
def encryptData(self, encryptKey, privParameters, dataToEncrypt):
@@ -99,19 +91,19 @@ class Des3(base.AbstractEncryptionService):
snmpEngineBoots, snmpEngineTime, salt = privParameters
des3Key, salt, iv = self.__getEncryptionKey(
- str(encryptKey), snmpEngineBoots
+ encryptKey, snmpEngineBoots
)
des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv)
privParameters = univ.OctetString(salt)
- plaintext = dataToEncrypt + '\x00' * (8 - len(dataToEncrypt) % 8)
+ plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets()
cipherblock = iv
- ciphertext = ''
+ ciphertext = null
while plaintext:
cipherblock = des3Obj.encrypt(
- string.join(map(lambda x,y: chr(ord(x)^ord(y)), cipherblock, plaintext[:8]), '')
+ univ.OctetString(map(lambda x,y:x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(plaintext[:8]).asNumbers()))
)
ciphertext = ciphertext + cipherblock
plaintext = plaintext[8:]
@@ -131,9 +123,7 @@ class Des3(base.AbstractEncryptionService):
errorIndication=errind.decryptionError
)
- salt = str(salt)
-
- des3Key, iv = self.__getDecryptionKey(str(decryptKey), salt)
+ des3Key, iv = self.__getDecryptionKey(decryptKey, salt)
if len(encryptedData) % 8 != 0:
raise error.StatusInformation(
@@ -142,17 +132,12 @@ class Des3(base.AbstractEncryptionService):
des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv)
- plaintext = ''
- ciphertext = str(encryptedData)
+ plaintext = null
+ ciphertext = encryptedData.asOctets()
cipherblock = iv
while ciphertext:
- plaintext = plaintext + string.join(map(
- lambda x,y: chr(ord(x)^ord(y)),
- cipherblock,
- des3Obj.decrypt(ciphertext[:8])
- ), '')
+ plaintext = plaintext + univ.OctetString(map(lambda x,y: x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(des3Obj.decrypt(ciphertext[:8])).asNumbers())).asOctets()
cipherblock = ciphertext[:8]
ciphertext = ciphertext[8:]
return plaintext
-
diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py
index a14e787..e50d23e 100644
--- a/pysnmp/proto/secmod/rfc2576.py
+++ b/pysnmp/proto/secmod/rfc2576.py
@@ -1,5 +1,4 @@
# SNMP v1 & v2c security models implementation
-import string
from pyasn1.codec.ber import encoder
from pysnmp.proto.secmod import base
from pysnmp.carrier.asynsock.dgram import udp, udp6
@@ -206,7 +205,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
).syntax
if targetAddr not in addrToTagMap:
addrToTagMap[targetAddr] = {}
- for tag in string.split(str(targetAddrTagList)):
+ for tag in targetAddrTagList.asOctets().split():
addrToTagMap[targetAddr][tag] = 1
debug.logger & debug.flagSM and debug.logger('processIncomingMsg: address-to-tag map %s' % addrToTagMap)
@@ -214,7 +213,7 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel):
# XXX snmpTargetAddrTMask matching not implemented
if srcTransport in addrToTagMap:
- for tag in string.split(str(mibNode.syntax)):
+ for tag in mibNode.syntax.asOctets().split():
if tag in addrToTagMap[srcTransport]:
debug.logger & debug.flagSM and debug.logger('processIncomingMsg: tag %s matched transport %s' % (tag, srcTransport))
break
diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
index 54efbef..f12aca3 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py
@@ -2,14 +2,14 @@ try:
from hashlib import md5
except ImportError:
import md5
- md5 = md5.new
-import string
+ 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 = '\x00'*12
-_fortyEightZeros = '\x00'*48
+_twelveZeros = univ.OctetString((0,)*12).asOctets()
+_fortyEightZeros = (0,)*48
# rfc3414: 6.2.4
@@ -30,7 +30,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 = string.find(wholeMsg, _twelveZeros)
+ l = wholeMsg.find(_twelveZeros)
if l == -1:
raise error.ProtocolError('Cant locate digest placeholder')
wholeHead = wholeMsg[:l]
@@ -39,31 +39,31 @@ class HmacMd5(base.AbstractAuthenticationService):
# 6.3.1.1
# 6.3.1.2a
- extendedAuthKey = map(ord, str(authKey) + _fortyEightZeros)
+ extendedAuthKey = authKey.asNumbers() + _fortyEightZeros
# 6.3.1.2b --> noop
# 6.3.1.2c
- k1 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__ipad), ''
+ k1 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__ipad)
)
# 6.3.1.2d --> noop
# 6.3.1.2e
- k2 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__opad), ''
+ k2 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__opad)
)
# 6.3.1.3
- d1 = md5(k1+wholeMsg).digest()
+ d1 = md5(k1.asOctets()+wholeMsg).digest()
# 6.3.1.4
- d2 = md5(k2+d1).digest()
+ d2 = md5(k2.asOctets()+d1).digest()
mac = d2[:12]
# 6.3.1.5 & 6
- return '%s%s%s' % (wholeHead, mac, wholeTail)
+ return wholeHead + mac + wholeTail
# 6.3.2
def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg):
@@ -74,37 +74,35 @@ class HmacMd5(base.AbstractAuthenticationService):
)
# 6.3.2.3
- l = string.find(wholeMsg, str(authParameters))
+ l = wholeMsg.find(authParameters.asOctets())
if l == -1:
raise error.ProtocolError('Cant locate digest in wholeMsg')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l+12:]
- authenticatedWholeMsg = '%s%s%s' % (
- wholeHead, _twelveZeros, wholeTail
- )
+ authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail
# 6.3.2.4a
- extendedAuthKey = map(ord, str(authKey) + _fortyEightZeros)
+ extendedAuthKey = authKey.asNumbers() + _fortyEightZeros
# 6.3.2.4b --> noop
# 6.3.2.4c
- k1 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__ipad), ''
+ k1 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__ipad)
)
# 6.3.2.4d --> noop
# 6.3.2.4e
- k2 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__opad), ''
+ k2 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__opad)
)
# 6.3.2.5a
- d1 = md5(k1+authenticatedWholeMsg).digest()
+ d1 = md5(k1.asOctets()+authenticatedWholeMsg).digest()
# 6.3.2.5b
- d2 = md5(k2+d1).digest()
+ d2 = md5(k2.asOctets()+d1).digest()
# 6.3.2.5c
mac = d2[:12]
diff --git a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
index f813109..37e7d89 100644
--- a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
+++ b/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py
@@ -3,13 +3,13 @@ try:
except ImportError:
import sha
sha1 = sha.new
-import string
+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 = '\x00'*12
-_fortyFourZeros = '\x00'*44
+_twelveZeros = univ.OctetString((0,)*12).asOctets()
+_fortyFourZeros = (0,)*44
# 7.2.4
@@ -31,38 +31,38 @@ 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 = string.find(wholeMsg, _twelveZeros)
+ l = wholeMsg.find(_twelveZeros)
if l == -1:
raise error.ProtocolError('Cant locate digest placeholder')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l+12:]
# 7.3.1.2a
- extendedAuthKey = map(ord, str(authKey) + _fortyFourZeros)
+ extendedAuthKey = authKey.asNumbers() + _fortyFourZeros
# 7.3.1.2b -- noop
# 7.3.1.2c
- k1 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__ipad), ''
+ k1 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__ipad)
)
# 7.3.1.2d -- noop
# 7.3.1.2e
- k2 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__opad), ''
+ k2 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__opad)
)
# 7.3.1.3
- d1 = sha1(k1+wholeMsg).digest()
+ d1 = sha1(k1.asOctets()+wholeMsg).digest()
# 7.3.1.4
- d2 = sha1(k2+d1).digest()
+ d2 = sha1(k2.asOctets()+d1).digest()
mac = d2[:12]
# 7.3.1.5 & 6
- return '%s%s%s' % (wholeHead, mac, wholeTail)
+ return wholeHead + mac + wholeTail
# 7.3.2
def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg):
@@ -73,37 +73,35 @@ class HmacSha(base.AbstractAuthenticationService):
)
# 7.3.2.3
- l = string.find(wholeMsg, str(authParameters))
+ l = wholeMsg.find(authParameters.asOctets())
if l == -1:
raise error.ProtocolError('Cant locate digest in wholeMsg')
wholeHead = wholeMsg[:l]
wholeTail = wholeMsg[l+12:]
- authenticatedWholeMsg = '%s%s%s' % (
- wholeHead, _twelveZeros, wholeTail
- )
+ authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail
# 7.3.2.4a
- extendedAuthKey = map(ord, str(authKey) + _fortyFourZeros)
+ extendedAuthKey = authKey.asNumbers() + _fortyFourZeros
# 7.3.2.4b --> noop
# 7.3.2.4c
- k1 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__ipad), ''
+ k1 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__ipad)
)
# 7.3.2.4d --> noop
# 7.3.2.4e
- k2 = string.join(
- map(lambda x,y: chr(x^y), extendedAuthKey, self.__opad), ''
+ k2 = univ.OctetString(
+ map(lambda x,y: x^y, extendedAuthKey, self.__opad)
)
# 7.3.2.5a
- d1 = sha1(k1+authenticatedWholeMsg).digest()
+ d1 = sha1(k1.asOctets()+authenticatedWholeMsg).digest()
# 7.3.2.5b
- d2 = sha1(k2+d1).digest()
+ d2 = sha1(k2.asOctets()+d1).digest()
# 7.3.2.5c
mac = d2[:12]
diff --git a/pysnmp/proto/secmod/rfc3414/localkey.py b/pysnmp/proto/secmod/rfc3414/localkey.py
index 58876b4..8edcbdf 100644
--- a/pysnmp/proto/secmod/rfc3414/localkey.py
+++ b/pysnmp/proto/secmod/rfc3414/localkey.py
@@ -5,11 +5,13 @@ except ImportError:
import md5, sha
md5 = md5.new
sha1 = sha.new
+from pyasn1.type import univ
# RFC3414: A.2.1
def hashPassphraseMD5(passphrase):
+ passphrase = univ.OctetString(passphrase).asOctets()
md = md5()
- ringBuffer = passphrase * (passphrase and (64/len(passphrase)+1) or 1)
+ ringBuffer = passphrase * (passphrase and (64//len(passphrase)+1) or 1)
ringBufferLen = len(ringBuffer)
count = 0
mark = 0
@@ -27,15 +29,17 @@ def hashPassphraseMD5(passphrase):
return md.digest()
def localizeKeyMD5(passKey, snmpEngineId):
- return md5('%s%s%s' % (passKey, str(snmpEngineId), passKey)).digest()
+ passKey = univ.OctetString(passKey).asOctets()
+ return md5(passKey + snmpEngineId.asOctets()+ passKey).digest()
def passwordToKeyMD5(passphrase, snmpEngineId):
return localizeKeyMD5(hashPassphraseMD5(passphrase), snmpEngineId)
# RFC3414: A.2.2
def hashPassphraseSHA(passphrase):
+ passphrase = univ.OctetString(passphrase).asOctets()
md = sha1()
- ringBuffer = passphrase * (64/len(passphrase)+1)
+ ringBuffer = passphrase * (64//len(passphrase)+1)
ringBufferLen = len(ringBuffer)
count = 0
mark = 0
@@ -53,7 +57,8 @@ def hashPassphraseSHA(passphrase):
return md.digest()
def localizeKeySHA(passKey, snmpEngineId):
- return sha1('%s%s%s' % (passKey, str(snmpEngineId), passKey)).digest()
+ passKey = univ.OctetString(passKey).asOctets()
+ return sha1(passKey + snmpEngineId.asOctets()+ passKey).digest()
def passwordToKeySHA(passphrase, snmpEngineId):
return localizeKeySHA(hashPassphraseSHA(passphrase), snmpEngineId)
diff --git a/pysnmp/proto/secmod/rfc3414/priv/des.py b/pysnmp/proto/secmod/rfc3414/priv/des.py
index 5be1e77..2d72c75 100644
--- a/pysnmp/proto/secmod/rfc3414/priv/des.py
+++ b/pysnmp/proto/secmod/rfc3414/priv/des.py
@@ -1,4 +1,4 @@
-import random, string
+import random
from pysnmp.proto.secmod.rfc3414.priv import base
from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha
from pysnmp.proto.secmod.rfc3414 import localkey
@@ -22,9 +22,9 @@ random.seed()
class Des(base.AbstractEncryptionService):
serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol
if version_info < (2, 3):
- _localInt = long(random.random()*0xffffffffL)
+ _localInt = int(random.random()*0xffffffff)
else:
- _localInt = random.randrange(0, 0xffffffffL)
+ _localInt = random.randrange(0, 0xffffffff)
def hashPassphrase(self, authProtocol, privKey):
if authProtocol == hmacmd5.HmacMd5.serviceID:
@@ -52,7 +52,7 @@ class Des(base.AbstractEncryptionService):
desKey = privKey[:8]
preIV = privKey[8:16]
- securityEngineBoots = long(snmpEngineBoots)
+ securityEngineBoots = int(snmpEngineBoots)
salt = [
securityEngineBoots>>24&0xff,
@@ -64,19 +64,19 @@ class Des(base.AbstractEncryptionService):
self._localInt>>8&0xff,
self._localInt&0xff
]
- if self._localInt == 0xffffffffL:
+ if self._localInt == 0xffffffff:
self._localInt = 0
else:
self._localInt = self._localInt + 1
- return desKey, \
- string.join(map(chr, salt), ''), \
- string.join(map(lambda x,y: chr(x^ord(y)), salt, preIV), '')
+ return desKey.asOctets(), \
+ univ.OctetString(salt).asOctets(), \
+ univ.OctetString(map(lambda x,y:x^y,salt,preIV.asNumbers())).asOctets()
def __getDecryptionKey(self, privKey, salt):
- return privKey[:8], string.join(
- map(lambda x,y: chr(ord(x)^ord(y)), salt, privKey[8:16]), ''
- )
+ return privKey[:8].asOctets(), univ.OctetString(
+ map(lambda x,y:x^y, salt.asNumbers(), privKey[8:16].asNumbers())
+ ).asOctets()
# 8.2.4.1
def encryptData(self, encryptKey, privParameters, dataToEncrypt):
@@ -89,7 +89,7 @@ class Des(base.AbstractEncryptionService):
# 8.3.1.1
desKey, salt, iv = self.__getEncryptionKey(
- str(encryptKey), snmpEngineBoots
+ encryptKey, snmpEngineBoots
)
# 8.3.1.2
@@ -97,7 +97,7 @@ class Des(base.AbstractEncryptionService):
# 8.1.1.2
desObj = DES.new(desKey, DES.MODE_CBC, iv)
- plaintext = dataToEncrypt + '\x00' * (8 - len(dataToEncrypt) % 8)
+ plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets()
ciphertext = desObj.encrypt(plaintext)
# 8.3.1.3 & 4
@@ -118,11 +118,10 @@ class Des(base.AbstractEncryptionService):
errorIndication=errind.decryptionError
)
- # 8.3.2.2
- salt = str(salt)
+ # 8.3.2.2 noop
# 8.3.2.3
- desKey, iv = self.__getDecryptionKey(str(decryptKey), salt)
+ desKey, iv = self.__getDecryptionKey(decryptKey, salt)
# 8.3.2.4 -> 8.1.1.3
if len(encryptedData) % 8 != 0:
@@ -133,4 +132,4 @@ class Des(base.AbstractEncryptionService):
desObj = DES.new(desKey, DES.MODE_CBC, iv)
# 8.3.2.6
- return desObj.decrypt(str(encryptedData))
+ return desObj.decrypt(encryptedData.asOctets())
diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py
index 82b3b7a..7e4f036 100644
--- a/pysnmp/proto/secmod/rfc3414/service.py
+++ b/pysnmp/proto/secmod/rfc3414/service.py
@@ -1,4 +1,5 @@
# SNMP v3 USM model services
+import time, sys
from pysnmp.proto.secmod.base import AbstractSecurityModel
from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha, noauth
from pysnmp.proto.secmod.rfc3414.priv import des, nopriv
@@ -6,19 +7,19 @@ from pysnmp.proto.secmod.rfc3826.priv import aes
from pysnmp.proto.secmod.eso.priv import des3, aes192, aes256
from pysnmp.smi.error import NoSuchInstanceError
from pysnmp.proto import rfc1155, errind, error
+from pysnmp import debug
from pyasn1.type import univ, namedtype, constraint
from pyasn1.codec.ber import encoder, decoder
from pyasn1.error import PyAsn1Error
-from pysnmp import debug
-import time
+from pyasn1.compat.octets import null
# USM security params
class UsmSecurityParameters(rfc1155.TypeCoercionHackMixIn, univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('msgAuthoritativeEngineID', univ.OctetString()),
- namedtype.NamedType('msgAuthoritativeEngineBoots', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))),
- namedtype.NamedType('msgAuthoritativeEngineTime', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))),
+ namedtype.NamedType('msgAuthoritativeEngineBoots', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))),
+ namedtype.NamedType('msgAuthoritativeEngineTime', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))),
namedtype.NamedType('msgUserName', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32))),
namedtype.NamedType('msgAuthenticationParameters', univ.OctetString()),
namedtype.NamedType('msgPrivacyParameters', univ.OctetString())
@@ -44,7 +45,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
AbstractSecurityModel.__init__(self)
self.__timeline = {}
self.__timelineExpQueue = {}
- self.__expirationTimer = 0L
+ self.__expirationTimer = 0
def __getUserInfo(
self, mibInstrumController, securityEngineID, securityName
@@ -253,7 +254,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info')
else:
# empty username used for engineID discovery
- usmUserName = usmUserSecurityName = ''
+ usmUserName = usmUserSecurityName = null
usmUserAuthProtocol = usmUserAuthKeyLocalized = None
usmUserPrivProtocol = usmUserPrivKeyLocalized = None
debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use empty USM data')
@@ -509,7 +510,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# Used for error reporting
contextEngineId = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax
- contextName = ''
+ contextName = null
# 3.2.3
if msgAuthoritativeEngineID not in self.__timeline:
@@ -605,7 +606,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
)
else:
# empty username used for engineID discovery
- usmUserName = usmUserSecurityName = ''
+ usmUserName = usmUserSecurityName = null
usmUserAuthProtocol = usmUserAuthKeyLocalized = None
usmUserPrivProtocol = usmUserPrivKeyLocalized = None
@@ -721,7 +722,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
# 3.2.7a
if msgAuthoritativeEngineID == snmpEngineID:
- if snmpEngineBoots == 2147483647L or \
+ if snmpEngineBoots == 2147483647 or \
snmpEngineBoots != msgAuthoritativeEngineBoots or \
abs(idleTime + int(snmpEngineTime) - \
int(msgAuthoritativeEngineTime)) > 150:
@@ -759,7 +760,7 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
debug.logger & debug.flagSM and debug.logger('processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineID %s' % (msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, repr(msgAuthoritativeEngineID)))
# 3.2.7b.2
- if snmpEngineBoots == 2147483647L or \
+ if snmpEngineBoots == 2147483647 or \
msgAuthoritativeEngineBoots < snmpEngineBoots or \
msgAuthoritativeEngineBoots == snmpEngineBoots and \
abs(idleTime + int(snmpEngineTime) - \
@@ -809,8 +810,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel):
scopedPDU, rest = decoder.decode(
decryptedData, asn1Spec=scopedPduSpec
)
- except PyAsn1Error, why:
- debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoder failed %s' % why)
+ except PyAsn1Error:
+ debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoder failed %s' % sys.exc_info()[0])
raise error.StatusInformation(
errorIndication = errind.decryptionError
)
diff --git a/pysnmp/proto/secmod/rfc3826/priv/aes.py b/pysnmp/proto/secmod/rfc3826/priv/aes.py
index d927577..a669138 100644
--- a/pysnmp/proto/secmod/rfc3826/priv/aes.py
+++ b/pysnmp/proto/secmod/rfc3826/priv/aes.py
@@ -1,4 +1,5 @@
-import random, string
+import random
+from pyasn1.type import univ
from pysnmp.proto.secmod.rfc3414.priv import base
from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha
from pysnmp.proto.secmod.rfc3414 import localkey
@@ -6,11 +7,6 @@ from pyasn1.type import univ
from pysnmp.proto import errind, error
try:
- from sys import version_info
-except ImportError:
- version_info = ( 0, 0 ) # a really early version
-
-try:
from Crypto.Cipher import AES
except ImportError:
AES = None
@@ -24,10 +20,7 @@ random.seed()
class Aes(base.AbstractEncryptionService):
serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol
keySize = 16
- if version_info < (2, 3):
- _localInt = long(random.random()*0xffffffffffffffffL)
- else:
- _localInt = random.randrange(0, 0xffffffffffffffffL)
+ _localInt = random.randrange(0, 0xffffffffffffffff)
# 3.1.2.1
def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime):
salt = [
@@ -41,42 +34,31 @@ class Aes(base.AbstractEncryptionService):
self._localInt&0xff
]
- if self._localInt == 0xffffffffffffffffL:
+ if self._localInt == 0xffffffffffffffff:
self._localInt = 0
else:
self._localInt = self._localInt + 1
- salt = string.join(map(chr, salt), '')
-
- return self.__getDecryptionKey(privKey, snmpEngineBoots,
- snmpEngineTime, salt) + ( salt, )
+ return self.__getDecryptionKey(
+ privKey, snmpEngineBoots, snmpEngineTime, salt
+ ) + ( univ.OctetString(salt).asOctets(), )
def __getDecryptionKey(self, privKey, snmpEngineBoots,
snmpEngineTime, salt):
snmpEngineBoots, snmpEngineTime, salt = (
- long(snmpEngineBoots), long(snmpEngineTime), str(salt)
+ int(snmpEngineBoots), int(snmpEngineTime), salt
)
- iv = [
- snmpEngineBoots>>24&0xff,
- snmpEngineBoots>>16&0xff,
- snmpEngineBoots>>8&0xff,
- snmpEngineBoots&0xff,
- snmpEngineTime>>24&0xff,
- snmpEngineTime>>16&0xff,
- snmpEngineTime>>8&0xff,
- snmpEngineTime&0xff,
- ord(salt[0]),
- ord(salt[1]),
- ord(salt[2]),
- ord(salt[3]),
- ord(salt[4]),
- ord(salt[5]),
- ord(salt[6]),
- ord(salt[7])
- ]
+ iv = [ snmpEngineBoots>>24&0xff,
+ snmpEngineBoots>>16&0xff,
+ snmpEngineBoots>>8&0xff,
+ snmpEngineBoots&0xff,
+ snmpEngineTime>>24&0xff,
+ snmpEngineTime>>16&0xff,
+ snmpEngineTime>>8&0xff,
+ snmpEngineTime&0xff ] + salt
- return privKey[:self.keySize], string.join(map(chr, iv), '')
+ return privKey[:self.keySize].asOctets(), univ.OctetString(iv).asOctets()
def hashPassphrase(self, authProtocol, privKey):
if authProtocol == hmacmd5.HmacMd5.serviceID:
@@ -110,14 +92,14 @@ class Aes(base.AbstractEncryptionService):
# 3.3.1.1
aesKey, iv, salt = self.__getEncryptionKey(
- str(encryptKey), snmpEngineBoots, snmpEngineTime
+ encryptKey, snmpEngineBoots, snmpEngineTime
)
# 3.3.1.3
aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128)
# PyCrypto seems to require padding
- dataToEncrypt = dataToEncrypt + '\0' * (16-len(dataToEncrypt)%16)
+ dataToEncrypt = dataToEncrypt + univ.OctetString((0,) * (16-len(dataToEncrypt)%16)).asOctets()
ciphertext = aesObj.encrypt(dataToEncrypt)
@@ -141,13 +123,13 @@ class Aes(base.AbstractEncryptionService):
# 3.3.2.3
aesKey, iv = self.__getDecryptionKey(
- str(decryptKey), snmpEngineBoots, snmpEngineTime, salt
+ decryptKey, snmpEngineBoots, snmpEngineTime, salt
)
aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128)
# PyCrypto seems to require padding
- encryptedData = encryptedData + '\0' * (16-len(encryptedData)%16)
+ encryptedData = encryptedData + univ.OctetString((0,) * (16-len(encryptedData)%16)).asOctets()
# 3.3.2.4-6
- return aesObj.decrypt(str(encryptedData))
+ return aesObj.decrypt(encryptedData.asOctets())
diff --git a/pysnmp/smi/builder.py b/pysnmp/smi/builder.py
index 0221474..08f26b0 100644
--- a/pysnmp/smi/builder.py
+++ b/pysnmp/smi/builder.py
@@ -1,6 +1,5 @@
# MIB modules loader
-import os, types, string
-import imp, struct, marshal, time
+import os, sys, imp, struct, marshal, time
from pysnmp.smi import error
from pysnmp import debug
@@ -82,11 +81,11 @@ class __AbstractMibSource:
class ZipMibSource(__AbstractMibSource):
def _init(self):
p = __import__(
- self._srcName, globals(),locals(), string.split(self._srcName, '.')
+ self._srcName, globals(),locals(), self._srcName.split('.')
)
if hasattr(p, '__loader__'):
self.__loader = p.__loader__
- self._srcName = string.replace(self._srcName, '.', os.sep)
+ self._srcName = self._srcName.replace('.', os.sep)
return self
else:
return DirMibSource(os.path.split(p.__file__)[0]).init()
@@ -140,20 +139,18 @@ class MibBuilder:
defaultCoreMibs = 'pysnmp.smi.mibs.instances:pysnmp.smi.mibs'
defaultMiscMibs = 'pysnmp_mibs'
def __init__(self):
- self.lastBuildId = self._autoName = 0L
+ self.lastBuildId = self._autoName = 0
sources = []
- for m in string.split(
- os.environ.get('PYSNMP_MIB_PKGS', self.defaultCoreMibs), ':'
- ):
+ for m in os.environ.get('PYSNMP_MIB_PKGS', self.defaultCoreMibs).split(':'):
sources.append(ZipMibSource(m).init())
# Compatibility variable
if 'PYSNMP_MIB_DIR' in os.environ:
os.environ['PYSNMP_MIB_DIRS'] = os.environ['PYSNMP_MIB_DIR']
if 'PYSNMP_MIB_DIRS' in os.environ:
- for m in string.split(os.environ['PYSNMP_MIB_DIRS'], ':'):
+ for m in os.environ['PYSNMP_MIB_DIRS'].split(':'):
sources.append(DirMibSource(m).init())
if self.defaultMiscMibs:
- for m in string.split(self.defaultMiscMibs, ':'):
+ for m in self.defaultMiscMibs.split(':'):
try:
sources.append(ZipMibSource(m).init())
except ImportError:
@@ -161,7 +158,7 @@ class MibBuilder:
self.mibSymbols = {}
self.__modSeen = {}
self.__modPathsSeen = {}
- apply(self.setMibSources, sources)
+ self.setMibSources(*sources)
# MIB modules management
@@ -173,7 +170,7 @@ class MibBuilder:
# Legacy/compatibility methods
def setMibPath(self, *mibPaths):
- apply(self.setMibSources, map(DirMibSource, mibPaths))
+ self.setMibSources(*[ DirMibSource(x) for x in mibPaths ])
def getMibPath(self):
l = []
@@ -189,7 +186,7 @@ class MibBuilder:
for mibSource in self.__mibSources:
for modName in mibSource.listdir():
modNames[modName] = None
- modNames = modNames.keys()
+ modNames = list(modNames.keys())
if not modNames:
raise error.SmiError(
'No MIB module to load at %s' % (self,)
@@ -200,8 +197,8 @@ class MibBuilder:
debug.logger & debug.flagBld and debug.logger('loadModules: trying %s at %s' % (modName, mibSource))
try:
modData, sfx = mibSource.read(modName)
- except IOError, why:
- debug.logger & debug.flagBld and debug.logger('loadModules: read %s from %s failed: %s' % (modName, mibSource, why))
+ except IOError:
+ debug.logger & debug.flagBld and debug.logger('loadModules: read %s from %s failed: %s' % (modName, mibSource, sys.exc_info()[1]))
continue
modPath = mibSource.fullPath(modName, sfx)
@@ -218,10 +215,10 @@ class MibBuilder:
try:
exec(modData, g)
- except StandardError, why:
+ except Exception:
del self.__modPathsSeen[modPath]
raise error.SmiError(
- 'MIB module \"%s\" load error: %s' % (modPath, why)
+ 'MIB module \"%s\" load error: %s' % (modPath, sys.exc_info()[1])
)
self.__modSeen[modName] = modPath
@@ -239,7 +236,7 @@ class MibBuilder:
def unloadModules(self, *modNames):
if not modNames:
- modNames = self.mibSymbols.keys()
+ modNames = list(self.mibSymbols.keys())
for modName in modNames:
if modName not in self.mibSymbols:
raise error.SmiError(
@@ -288,10 +285,15 @@ class MibBuilder:
'Symbol %s already exported at %s' % (symName, modName)
)
- if hasattr(symObj, 'label'):
+ # XXX needs improvement
+ try:
symName = symObj.label or symName # class
- if type(symObj) == types.InstanceType:
+ except AttributeError:
+ pass
+ try:
symName = symObj.getLabel() or symName # class instance
+ except (AttributeError, TypeError):
+ pass
mibSymbols[symName] = symObj
@@ -306,7 +308,7 @@ class MibBuilder:
)
mibSymbols = self.mibSymbols[modName]
if not symNames:
- symNames = mibSymbols.keys()
+ symNames = list(mibSymbols.keys())
for symName in symNames:
if symName not in mibSymbols:
raise error.SmiError(
diff --git a/pysnmp/smi/indices.py b/pysnmp/smi/indices.py
index 8d72e45..95542ab 100644
--- a/pysnmp/smi/indices.py
+++ b/pysnmp/smi/indices.py
@@ -1,9 +1,7 @@
"""Ordered dictionaries classes used for indices"""
-from types import DictType, TupleType
-from string import join, split, atol
from bisect import bisect
-class OrderedDict(DictType):
+class OrderedDict(dict):
def __init__(self, **kwargs):
self.__keys = []
self.__dirty = 1
@@ -36,24 +34,23 @@ class OrderedDict(DictType):
return list(self.__keys)
def values(self):
if self.__dirty: self.__order()
- return map(lambda k, d=self: d[k], self.__keys)
+ return [ self[k] for k in self.__keys ]
def items(self):
if self.__dirty: self.__order()
- return map(lambda k, d=self: (k, d[k]), self.__keys)
- def update(self, d):
- map(lambda (k, v), self=self: self.__setitem__(k, v), d.items())
+ return [ (k, self[k]) for k in self.__keys ]
+ def update(self, d): [ self.__setitem__(k, v) for k,v in d.items() ]
def sortingFun(self, keys): keys.sort()
def __order(self):
self.sortingFun(self.__keys)
d = {}
for k in self.__keys:
d[len(k)] = 1
- l = d.keys()
- l.sort(); l.reverse()
+ l = list(d.keys())
+ l.sort(reverse=True)
self.__keysLens = tuple(l)
self.__dirty = 0
def nextKey(self, key):
- keys = self.keys()
+ keys = list(self.keys())
if key in self:
nextIdx = keys.index(key) + 1
else:
@@ -69,16 +66,14 @@ class OrderedDict(DictType):
class OidOrderedDict(OrderedDict):
def __init__(self, **kwargs):
self.__keysCache = {}
- apply(OrderedDict.__init__, [self], kwargs)
+ OrderedDict.__init__(self, **kwargs)
def __setitem__(self, key, value):
if key not in self.__keysCache:
- if type(key) == TupleType:
+ if isinstance(key, tuple):
self.__keysCache[key] = key
else:
- self.__keysCache[key] = map(
- lambda x: atol(x), filter(None, split(key, '.'))
- )
+ self.__keysCache[key] = [ int(x) for x in key.split('.') if x ]
OrderedDict.__setitem__(self, key, value)
def __delitem__(self, key):
@@ -88,6 +83,4 @@ class OidOrderedDict(OrderedDict):
__delattr__ = __delitem__
def sortingFun(self, keys):
- def f(o1, o2, self=self):
- return cmp(self.__keysCache[o1], self.__keysCache[o2])
- keys.sort(f)
+ keys.sort(key=lambda k, d=self.__keysCache: d[k])
diff --git a/pysnmp/smi/instrum.py b/pysnmp/smi/instrum.py
index 9b076f8..6ce8b14 100644
--- a/pysnmp/smi/instrum.py
+++ b/pysnmp/smi/instrum.py
@@ -1,5 +1,5 @@
# MIB modules management
-from types import InstanceType
+import sys
from pysnmp.smi import error
from pysnmp import debug
@@ -98,13 +98,11 @@ class MibInstrumController:
# Sort by module name to give user a chance to slip-in
# custom MIB modules (that would be sorted out first)
- mibSymbols = self.mibBuilder.mibSymbols.items()
- mibSymbols.sort(lambda x,y: cmp(y[0], x[0]))
+ mibSymbols = list(self.mibBuilder.mibSymbols.items())
+ mibSymbols.sort(key=lambda x: x[0], reverse=True)
for modName, mibMod in mibSymbols:
for symObj in mibMod.values():
- if type(symObj) != InstanceType:
- continue
if isinstance(symObj, MibTable):
tables[symObj.name] = symObj
elif isinstance(symObj, MibTableRow):
@@ -175,7 +173,7 @@ class MibInstrumController:
# MIB instrumentation
- def flipFlopFsm(self, fsmTable, inputNameVals, (acFun, acCtx)):
+ def flipFlopFsm(self, fsmTable, inputNameVals, acInfo):
self.__indexMib()
debug.logger & debug.flagIns and debug.logger('flipFlopFsm: inputNameVals %s' % repr(inputNameVals))
mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso')
@@ -209,11 +207,11 @@ class MibInstrumController:
try:
# Convert to tuple to avoid ObjectName instantiation
# on subscription
- rval = f(tuple(name), val, idx, (acFun, acCtx))
- except error.SmiError, why:
- debug.logger & debug.flagIns and debug.logger('flipFlopFsm: fun %s failed %s for %s=%s' % (f, why, name, repr(val)))
+ rval = f(tuple(name), val, idx, acInfo)
+ except error.SmiError:
+ debug.logger & debug.flagIns and debug.logger('flipFlopFsm: fun %s failed %s for %s=%s' % (f, sys.exc_info()[1], name, repr(val)))
if myErr is None: # Take the first exception
- myErr = why
+ myErr = sys.exc_info()[1]
status = 'err'
break
else:
@@ -225,13 +223,13 @@ class MibInstrumController:
raise myErr
return outputNameVals
- def readVars(self, vars, (acFun, acCtx)=(None, None)):
- return self.flipFlopFsm(self.fsmReadVar, vars, (acFun, acCtx))
- def readNextVars(self, vars, (acFun, acCtx)=(None, None)):
- return self.flipFlopFsm(self.fsmReadNextVar, vars, (acFun, acCtx))
- def writeVars(self, vars, (acFun, acCtx)=(None, None)):
- return self.flipFlopFsm(self.fsmWriteVar, vars, (acFun, acCtx))
+ def readVars(self, vars, acInfo=(None, None)):
+ return self.flipFlopFsm(self.fsmReadVar, vars, acInfo)
+ def readNextVars(self, vars, acInfo=(None, None)):
+ return self.flipFlopFsm(self.fsmReadNextVar, vars, acInfo)
+ def writeVars(self, vars, acInfo=(None, None)):
+ return self.flipFlopFsm(self.fsmWriteVar, vars, acInfo)
# This version of the above method skips "test" phase for performance
- def readVarsFast(self, vars, (acFun, acCtx)=(None, None)):
- return self.flipFlopFsm(self.fsmReadVarFast, vars, (acFun, acCtx))
+ def readVarsFast(self, vars, acInfo=(None, None)):
+ return self.flipFlopFsm(self.fsmReadVarFast, vars, acInfo)
diff --git a/pysnmp/smi/mibs/PYSNMP-MIB.py b/pysnmp/smi/mibs/PYSNMP-MIB.py
index 19b2d31..8f029a8 100644
--- a/pysnmp/smi/mibs/PYSNMP-MIB.py
+++ b/pysnmp/smi/mibs/PYSNMP-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:59 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:22:47 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
diff --git a/pysnmp/smi/mibs/PYSNMP-USM-MIB.py b/pysnmp/smi/mibs/PYSNMP-USM-MIB.py
index 25221c8..b735075 100644
--- a/pysnmp/smi/mibs/PYSNMP-USM-MIB.py
+++ b/pysnmp/smi/mibs/PYSNMP-USM-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-USM-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:59 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:25:33 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -56,7 +56,7 @@ pysnmpUsmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2, 2))
# Augmentions
usmUserEntry, = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry")
usmUserEntry.registerAugmentions(("PYSNMP-USM-MIB", "pysnmpUsmKeyEntry"))
-apply(pysnmpUsmKeyEntry.setIndexNames, usmUserEntry.getIndexNames())
+pysnmpUsmKeyEntry.setIndexNames(*usmUserEntry.getIndexNames())
# Exports
diff --git a/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py b/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py
index b29d357..4569ca3 100644
--- a/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMP-COMMUNITY-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:11 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:26:30 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -47,7 +47,7 @@ snmpTargetAddrExtEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 2, 1))
if mibBuilder.loadTexts: snmpTargetAddrExtEntry.setDescription("Information about a particular mask and mms value.")
snmpTargetAddrTMask = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 2, 1, 1), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255)).clone('')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetAddrTMask.setDescription("The mask value associated with an entry in the\nsnmpTargetAddrTable. The value of this object must\nhave the same length as the corresponding instance of\nsnmpTargetAddrTAddress, or must have length 0. An\nattempt to set it to any other value will result in\nan inconsistentValue error.\n\nThe value of this object allows an entry in the\nsnmpTargetAddrTable to specify multiple addresses.\nThe mask value is used to select which bits of\na transport address must match bits of the corresponding\ninstance of snmpTargetAddrTAddress, in order for the\ntransport address to match a particular entry in the\nsnmpTargetAddrTable. Bits which are 1 in the mask\nvalue indicate bits in the transport address which\nmust match bits in the snmpTargetAddrTAddress value.\n\n\nBits which are 0 in the mask indicate bits in the\ntransport address which need not match. If the\nlength of the mask is 0, the mask should be treated\nas if all its bits were 1 and its length were equal\nto the length of the corresponding value of\nsnmpTargetAddrTable.\n\nThis object may not be modified while the value of the\ncorresponding instance of snmpTargetAddrRowStatus is\nactive(1). An attempt to set this object in this case\nwill result in an inconsistentValue error.")
-snmpTargetAddrMMS = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=constraint.ConstraintsUnion(constraint.ValueRangeConstraint(0,0),constraint.ValueRangeConstraint(484,2147483647L),)).clone(484)).setMaxAccess("readcreate")
+snmpTargetAddrMMS = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=constraint.ConstraintsUnion(constraint.ValueRangeConstraint(0,0),constraint.ValueRangeConstraint(484,2147483647),)).clone(484)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetAddrMMS.setDescription("The maximum message size value associated with an entry\nin the snmpTargetAddrTable.")
snmpTrapAddress = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 3), IpAddress()).setMaxAccess("notifyonly")
if mibBuilder.loadTexts: snmpTrapAddress.setDescription("The value of the agent-addr field of a Trap PDU which\nis forwarded by a proxy forwarder application using\nan SNMP version other than SNMPv1. The value of this\nobject SHOULD contain the value of the agent-addr field\nfrom the original Trap PDU as generated by an SNMPv1\nagent.")
@@ -60,12 +60,21 @@ snmpCommunityMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 2))
# Augmentions
snmpTargetAddrEntry, = mibBuilder.importSymbols("SNMP-TARGET-MIB", "snmpTargetAddrEntry")
snmpTargetAddrEntry.registerAugmentions(("SNMP-COMMUNITY-MIB", "snmpTargetAddrExtEntry"))
-apply(snmpTargetAddrExtEntry.setIndexNames, snmpTargetAddrEntry.getIndexNames())
+snmpTargetAddrExtEntry.setIndexNames(*snmpTargetAddrEntry.getIndexNames())
# Groups
+snmpCommunityGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 18, 2, 2, 1)).setObjects(("SNMP-COMMUNITY-MIB", "snmpCommunitySecurityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityTransportTag"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStorageType"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrMMS"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrTMask"), ("SNMP-COMMUNITY-MIB", "snmpCommunityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextEngineID"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStatus"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextName"), )
+if mibBuilder.loadTexts: snmpCommunityGroup.setDescription("A collection of objects providing for configuration\nof community strings for SNMPv1 (and SNMPv2c) usage.")
snmpProxyTrapForwardGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 18, 2, 2, 3)).setObjects(("SNMP-COMMUNITY-MIB", "snmpTrapAddress"), ("SNMP-COMMUNITY-MIB", "snmpTrapCommunity"), )
-snmpCommunityGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 18, 2, 2, 1)).setObjects(("SNMP-COMMUNITY-MIB", "snmpCommunityStorageType"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrTMask"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextEngineID"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStatus"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextName"), ("SNMP-COMMUNITY-MIB", "snmpCommunitySecurityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityName"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrMMS"), ("SNMP-COMMUNITY-MIB", "snmpCommunityTransportTag"), )
+if mibBuilder.loadTexts: snmpProxyTrapForwardGroup.setDescription("Objects which are used by proxy forwarding applications\nwhen translating traps between SNMP versions. These are\nused to preserve SNMPv1-specific information when\n\n\ntranslating to SNMPv2c or SNMPv3.")
+
+# Compliances
+
+snmpCommunityMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 18, 2, 1, 1)).setObjects(("SNMP-COMMUNITY-MIB", "snmpCommunityGroup"), )
+if mibBuilder.loadTexts: snmpCommunityMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP-COMMUNITY-MIB.")
+snmpProxyTrapForwardCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 18, 2, 1, 2)).setObjects(("SNMP-COMMUNITY-MIB", "snmpProxyTrapForwardGroup"), )
+if mibBuilder.loadTexts: snmpProxyTrapForwardCompliance.setDescription("The compliance statement for SNMP engines which\ncontain a proxy forwarding application which is\ncapable of forwarding SNMPv1 traps using SNMPv2c\nor SNMPv3.")
# Exports
@@ -76,4 +85,7 @@ mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", PYSNMP_MODULE_ID=snmpCommunityMIB
mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityMIB=snmpCommunityMIB, snmpCommunityMIBObjects=snmpCommunityMIBObjects, snmpCommunityTable=snmpCommunityTable, snmpCommunityEntry=snmpCommunityEntry, snmpCommunityIndex=snmpCommunityIndex, snmpCommunityName=snmpCommunityName, snmpCommunitySecurityName=snmpCommunitySecurityName, snmpCommunityContextEngineID=snmpCommunityContextEngineID, snmpCommunityContextName=snmpCommunityContextName, snmpCommunityTransportTag=snmpCommunityTransportTag, snmpCommunityStorageType=snmpCommunityStorageType, snmpCommunityStatus=snmpCommunityStatus, snmpTargetAddrExtTable=snmpTargetAddrExtTable, snmpTargetAddrExtEntry=snmpTargetAddrExtEntry, snmpTargetAddrTMask=snmpTargetAddrTMask, snmpTargetAddrMMS=snmpTargetAddrMMS, snmpTrapAddress=snmpTrapAddress, snmpTrapCommunity=snmpTrapCommunity, snmpCommunityMIBConformance=snmpCommunityMIBConformance, snmpCommunityMIBCompliances=snmpCommunityMIBCompliances, snmpCommunityMIBGroups=snmpCommunityMIBGroups)
# Groups
-mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpProxyTrapForwardGroup=snmpProxyTrapForwardGroup, snmpCommunityGroup=snmpCommunityGroup)
+mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityGroup=snmpCommunityGroup, snmpProxyTrapForwardGroup=snmpProxyTrapForwardGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityMIBCompliance=snmpCommunityMIBCompliance, snmpProxyTrapForwardCompliance=snmpProxyTrapForwardCompliance)
diff --git a/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py b/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py
index 607a1fc..bdca361 100644
--- a/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py
@@ -8,11 +8,10 @@ try:
import os
except ImportError:
pass
-import string
import time
# Imported just in case new ASN.1 types would be created
-from pyasn1.type import constraint, namedval
+from pyasn1.type import univ, constraint, namedval
# Imports
@@ -29,25 +28,23 @@ class SnmpAdminString(TextualConvention, OctetString):
class SnmpEngineID(OctetString, TextualConvention):
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(5,32)
- defaultValue = '\x80\x00\x4f\xb8' + '\x05'
+ defaultValue = [128, 0, 79, 184, 5]
try:
# Attempt to base engine ID on local IP address
- defaultValue = defaultValue + string.join(
- map(lambda x: chr(int(x)),
- string.split(socket.gethostbyname(socket.gethostname()),'.')),
- ''
- )
+ defaultValue = defaultValue + [ int(x) for x in socket.gethostbyname(socket.gethostname()).split('.') ]
except:
pass
try:
# Attempt to base engine ID on PID
- defaultValue = defaultValue + chr(os.getpid() >> 8) + chr(os.getpid() & 0xff)
+ defaultValue = defaultValue + [os.getpid() >> 8, os.getpid() & 0xff]
except:
pass
# ...in any case, use pseudo-random text ID
t = int(time.time())
- defaultValue = defaultValue + chr(t >> 16 & 0xff) + chr(t >> 8 & 0xff) + chr(t & 0xff)
-
+ defaultValue = univ.OctetString(
+ defaultValue + [ t >> 16 & 0xff, t >> 8 & 0xff, t & 0xff]
+ ).asOctets()
+
class SnmpEngineTime(Integer32):
def clone(self, value=None, tagSet=None, subtypeSpec=None):
if value is None and self._value is not None:
@@ -55,14 +52,14 @@ class SnmpEngineTime(Integer32):
return Integer32.clone(self, value, tagSet, subtypeSpec)
class SnmpMessageProcessingModel(Integer32):
- subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,2147483647L)
+ subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,2147483647)
class SnmpSecurityLevel(Integer):
subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(1,3,2,)
namedValues = namedval.NamedValues(("noAuthNoPriv", 1), ("authNoPriv", 2), ("authPriv", 3), )
class SnmpSecurityModel(Integer32):
- subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,2147483647L)
+ subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,2147483647)
# Objects
@@ -79,11 +76,11 @@ snmpFrameworkMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 2))
snmpEngine = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 2, 1))
snmpEngineID = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 1), SnmpEngineID()).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmpEngineID.setDescription("An SNMP engine's administratively-unique identifier.\n\nThis information SHOULD be stored in non-volatile\nstorage so that it remains constant across\nre-initializations of the SNMP engine.")
-snmpEngineBoots = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("readonly")
+snmpEngineBoots = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmpEngineBoots.setDescription("The number of times that the SNMP engine has\n(re-)initialized itself since snmpEngineID\nwas last configured.")
-snmpEngineTime = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 3), SnmpEngineTime().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))).setMaxAccess("readonly").setUnits("seconds")
+snmpEngineTime = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 3), SnmpEngineTime().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly").setUnits("seconds")
if mibBuilder.loadTexts: snmpEngineTime.setDescription("The number of seconds since the value of\nthe snmpEngineBoots object last changed.\nWhen incrementing this object's value would\ncause it to exceed its maximum,\nsnmpEngineBoots is incremented as if a\nre-initialization had occurred, and this\nobject's value consequently reverts to zero.")
-snmpEngineMaxMessageSize = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 4), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647L))).setMaxAccess("readonly")
+snmpEngineMaxMessageSize = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 4), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: snmpEngineMaxMessageSize.setDescription("The maximum length in octets of an SNMP message\nwhich this SNMP engine can send or receive and\nprocess, determined as the minimum of the maximum\nmessage size values supported among all of the\ntransports available to and supported by the engine.")
snmpFrameworkMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3))
snmpFrameworkMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 1))
diff --git a/pysnmp/smi/mibs/SNMP-MPD-MIB.py b/pysnmp/smi/mibs/SNMP-MPD-MIB.py
index 52ee11f..adf5e1d 100644
--- a/pysnmp/smi/mibs/SNMP-MPD-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-MPD-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMP-MPD-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:11 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:30:16 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -35,6 +35,12 @@ snmpMPDMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 2))
# Groups
snmpMPDGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 11, 3, 2, 1)).setObjects(("SNMP-MPD-MIB", "snmpInvalidMsgs"), ("SNMP-MPD-MIB", "snmpUnknownPDUHandlers"), ("SNMP-MPD-MIB", "snmpUnknownSecurityModels"), )
+if mibBuilder.loadTexts: snmpMPDGroup.setDescription("A collection of objects providing for remote\nmonitoring of the SNMP Message Processing and\nDispatching process.")
+
+# Compliances
+
+snmpMPDCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 11, 3, 1, 1)).setObjects(("SNMP-MPD-MIB", "snmpMPDGroup"), )
+if mibBuilder.loadTexts: snmpMPDCompliance.setDescription("The compliance statement for SNMP entities which\nimplement the SNMP-MPD-MIB.")
# Exports
@@ -46,3 +52,6 @@ mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDMIB=snmpMPDMIB, snmpMPDAdmin=snm
# Groups
mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDGroup=snmpMPDGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDCompliance=snmpMPDCompliance)
diff --git a/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py b/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py
index 5669b11..6765df8 100644
--- a/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMP-NOTIFICATION-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:12 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:30:49 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -67,8 +67,19 @@ snmpNotifyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 2))
# Groups
-snmpNotifyFilterGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 2)).setObjects(("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterRowStatus"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileStorType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterMask"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileRowStatus"), )
snmpNotifyGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 1)).setObjects(("SNMP-NOTIFICATION-MIB", "snmpNotifyTag"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyRowStatus"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyType"), )
+if mibBuilder.loadTexts: snmpNotifyGroup.setDescription("A collection of objects for selecting which management\ntargets are used for generating notifications, and the\ntype of notification to be generated for each selected\nmanagement target.")
+snmpNotifyFilterGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 2)).setObjects(("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterRowStatus"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileStorType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterMask"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileRowStatus"), )
+if mibBuilder.loadTexts: snmpNotifyFilterGroup.setDescription("A collection of objects providing remote configuration\nof notification filters.")
+
+# Compliances
+
+snmpNotifyBasicCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), )
+if mibBuilder.loadTexts: snmpNotifyBasicCompliance.setDescription("The compliance statement for minimal SNMP entities which\nimplement only SNMP Unconfirmed-Class notifications and\nread-create operations on only the snmpTargetAddrTable.")
+snmpNotifyBasicFiltersCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 2)).setObjects(("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterGroup"), ("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), )
+if mibBuilder.loadTexts: snmpNotifyBasicFiltersCompliance.setDescription("The compliance statement for SNMP entities which implement\nSNMP Unconfirmed-Class notifications with filtering, and\nread-create operations on all related tables.")
+snmpNotifyFullCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 3)).setObjects(("SNMP-TARGET-MIB", "snmpTargetResponseGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterGroup"), ("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), )
+if mibBuilder.loadTexts: snmpNotifyFullCompliance.setDescription("The compliance statement for SNMP entities which either\nimplement only SNMP Confirmed-Class notifications, or both\nSNMP Unconfirmed-Class and Confirmed-Class notifications,\n\n\n\nplus filtering and read-create operations on all related\ntables.")
# Exports
@@ -79,4 +90,7 @@ mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", PYSNMP_MODULE_ID=snmpNotificat
mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotificationMIB=snmpNotificationMIB, snmpNotifyObjects=snmpNotifyObjects, snmpNotifyTable=snmpNotifyTable, snmpNotifyEntry=snmpNotifyEntry, snmpNotifyName=snmpNotifyName, snmpNotifyTag=snmpNotifyTag, snmpNotifyType=snmpNotifyType, snmpNotifyStorageType=snmpNotifyStorageType, snmpNotifyRowStatus=snmpNotifyRowStatus, snmpNotifyFilterProfileTable=snmpNotifyFilterProfileTable, snmpNotifyFilterProfileEntry=snmpNotifyFilterProfileEntry, snmpNotifyFilterProfileName=snmpNotifyFilterProfileName, snmpNotifyFilterProfileStorType=snmpNotifyFilterProfileStorType, snmpNotifyFilterProfileRowStatus=snmpNotifyFilterProfileRowStatus, snmpNotifyFilterTable=snmpNotifyFilterTable, snmpNotifyFilterEntry=snmpNotifyFilterEntry, snmpNotifyFilterSubtree=snmpNotifyFilterSubtree, snmpNotifyFilterMask=snmpNotifyFilterMask, snmpNotifyFilterType=snmpNotifyFilterType, snmpNotifyFilterStorageType=snmpNotifyFilterStorageType, snmpNotifyFilterRowStatus=snmpNotifyFilterRowStatus, snmpNotifyConformance=snmpNotifyConformance, snmpNotifyCompliances=snmpNotifyCompliances, snmpNotifyGroups=snmpNotifyGroups)
# Groups
-mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotifyFilterGroup=snmpNotifyFilterGroup, snmpNotifyGroup=snmpNotifyGroup)
+mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotifyGroup=snmpNotifyGroup, snmpNotifyFilterGroup=snmpNotifyFilterGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotifyBasicCompliance=snmpNotifyBasicCompliance, snmpNotifyBasicFiltersCompliance=snmpNotifyBasicFiltersCompliance, snmpNotifyFullCompliance=snmpNotifyFullCompliance)
diff --git a/pysnmp/smi/mibs/SNMP-PROXY-MIB.py b/pysnmp/smi/mibs/SNMP-PROXY-MIB.py
new file mode 100644
index 0000000..d96531f
--- /dev/null
+++ b/pysnmp/smi/mibs/SNMP-PROXY-MIB.py
@@ -0,0 +1,74 @@
+# PySNMP SMI module. Autogenerated from smidump -f python SNMP-PROXY-MIB
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:33:26 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
+
+# Imported just in case new ASN.1 types would be created
+from pyasn1.type import constraint, namedval
+
+# Imports
+
+( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
+( SnmpAdminString, SnmpEngineID, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID")
+( SnmpTagValue, snmpTargetBasicGroup, snmpTargetResponseGroup, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetBasicGroup", "snmpTargetResponseGroup")
+( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup")
+( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules")
+( RowStatus, StorageType, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType")
+
+# Objects
+
+snmpProxyMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 14)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",))
+if mibBuilder.loadTexts: snmpProxyMIB.setOrganization("IETF SNMPv3 Working Group")
+if mibBuilder.loadTexts: snmpProxyMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In message body: subscribe snmpv3\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\nPostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nEMail: mundy@tislabs.com\nPhone: +1 301-947-7107\n\n\nCo-Chair: David Harrington\n Enterasys Networks\nPostal: 35 Industrial Way\n P. O. Box 5004\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nPhone: +1 603-337-2614\n\nCo-editor: David B. Levi\n Nortel Networks\nPostal: 3505 Kesterwood Drive\n Knoxville, Tennessee 37918\nEMail: dlevi@nortelnetworks.com\nPhone: +1 865 686 0432\n\nCo-editor: Paul Meyer\n Secure Computing Corporation\nPostal: 2675 Long Lake Road\n Roseville, Minnesota 55113\nEMail: paul_meyer@securecomputing.com\nPhone: +1 651 628 1592\n\nCo-editor: Bob Stewart\n Retired")
+if mibBuilder.loadTexts: snmpProxyMIB.setDescription("This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by a proxy forwarding application.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.")
+snmpProxyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 1))
+snmpProxyTable = MibTable((1, 3, 6, 1, 6, 3, 14, 1, 2))
+if mibBuilder.loadTexts: snmpProxyTable.setDescription("The table of translation parameters used by proxy forwarder\napplications for forwarding SNMP messages.")
+snmpProxyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 14, 1, 2, 1)).setIndexNames((1, "SNMP-PROXY-MIB", "snmpProxyName"))
+if mibBuilder.loadTexts: snmpProxyEntry.setDescription("A set of translation parameters used by a proxy forwarder\napplication for forwarding SNMP messages.\n\nEntries in the snmpProxyTable are created and deleted\nusing the snmpProxyRowStatus object.")
+snmpProxyName = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess")
+if mibBuilder.loadTexts: snmpProxyName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpProxyEntry.")
+snmpProxyType = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 2), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,2,4,3,)).subtype(namedValues=namedval.NamedValues(("read", 1), ("write", 2), ("trap", 3), ("inform", 4), ))).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyType.setDescription("The type of message that may be forwarded using\nthe translation parameters defined by this entry.")
+snmpProxyContextEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 3), SnmpEngineID()).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyContextEngineID.setDescription("The contextEngineID contained in messages that\nmay be forwarded using the translation parameters\ndefined by this entry.")
+snmpProxyContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 4), SnmpAdminString()).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyContextName.setDescription("The contextName contained in messages that may be\nforwarded using the translation parameters defined\nby this entry.\n\nThis object is optional, and if not supported, the\ncontextName contained in a message is ignored when\nselecting an entry in the snmpProxyTable.")
+snmpProxyTargetParamsIn = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 5), SnmpAdminString()).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyTargetParamsIn.setDescription("This object selects an entry in the snmpTargetParamsTable.\nThe selected entry is used to determine which row of the\nsnmpProxyTable to use for forwarding received messages.")
+snmpProxySingleTargetOut = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 6), SnmpAdminString()).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxySingleTargetOut.setDescription("This object selects a management target defined in the\nsnmpTargetAddrTable (in the SNMP-TARGET-MIB). The\nselected target is defined by an entry in the\nsnmpTargetAddrTable whose index value (snmpTargetAddrName)\nis equal to this object.\n\nThis object is only used when selection of a single\ntarget is required (i.e. when forwarding an incoming\nread or write request).")
+snmpProxyMultipleTargetOut = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7), SnmpTagValue()).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyMultipleTargetOut.setDescription("This object selects a set of management targets defined\nin the snmpTargetAddrTable (in the SNMP-TARGET-MIB).\n\nThis object is only used when selection of multiple\ntargets is required (i.e. when forwarding an incoming\nnotification).")
+snmpProxyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyStorageType.setDescription("The storage type of this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.")
+snmpProxyRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate")
+if mibBuilder.loadTexts: snmpProxyRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\n\n\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nThe following objects may not be modified while the\nvalue of this object is active(1):\n - snmpProxyType\n - snmpProxyContextEngineID\n - snmpProxyContextName\n - snmpProxyTargetParamsIn\n - snmpProxySingleTargetOut\n - snmpProxyMultipleTargetOut")
+snmpProxyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3))
+snmpProxyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3, 1))
+snmpProxyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3, 2))
+
+# Augmentions
+
+# Groups
+
+snmpProxyGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 14, 3, 2, 3)).setObjects(("SNMP-PROXY-MIB", "snmpProxyRowStatus"), ("SNMP-PROXY-MIB", "snmpProxyTargetParamsIn"), ("SNMP-PROXY-MIB", "snmpProxyContextName"), ("SNMP-PROXY-MIB", "snmpProxySingleTargetOut"), ("SNMP-PROXY-MIB", "snmpProxyContextEngineID"), ("SNMP-PROXY-MIB", "snmpProxyStorageType"), ("SNMP-PROXY-MIB", "snmpProxyType"), ("SNMP-PROXY-MIB", "snmpProxyMultipleTargetOut"), )
+if mibBuilder.loadTexts: snmpProxyGroup.setDescription("A collection of objects providing remote configuration of\nmanagement target translation parameters for use by\nproxy forwarder applications.")
+
+# Compliances
+
+snmpProxyCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 14, 3, 1, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetResponseGroup"), ("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-PROXY-MIB", "snmpProxyGroup"), )
+if mibBuilder.loadTexts: snmpProxyCompliance.setDescription("The compliance statement for SNMP entities which include\na proxy forwarding application.")
+
+# Exports
+
+# Module identity
+mibBuilder.exportSymbols("SNMP-PROXY-MIB", PYSNMP_MODULE_ID=snmpProxyMIB)
+
+# Objects
+mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyMIB=snmpProxyMIB, snmpProxyObjects=snmpProxyObjects, snmpProxyTable=snmpProxyTable, snmpProxyEntry=snmpProxyEntry, snmpProxyName=snmpProxyName, snmpProxyType=snmpProxyType, snmpProxyContextEngineID=snmpProxyContextEngineID, snmpProxyContextName=snmpProxyContextName, snmpProxyTargetParamsIn=snmpProxyTargetParamsIn, snmpProxySingleTargetOut=snmpProxySingleTargetOut, snmpProxyMultipleTargetOut=snmpProxyMultipleTargetOut, snmpProxyStorageType=snmpProxyStorageType, snmpProxyRowStatus=snmpProxyRowStatus, snmpProxyConformance=snmpProxyConformance, snmpProxyCompliances=snmpProxyCompliances, snmpProxyGroups=snmpProxyGroups)
+
+# Groups
+mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyGroup=snmpProxyGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyCompliance=snmpProxyCompliance)
diff --git a/pysnmp/smi/mibs/SNMP-TARGET-MIB.py b/pysnmp/smi/mibs/SNMP-TARGET-MIB.py
index 543ff3b..9ecf1c3 100644
--- a/pysnmp/smi/mibs/SNMP-TARGET-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-TARGET-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMP-TARGET-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:12 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:33:45 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -18,13 +18,11 @@ from pyasn1.type import constraint, namedval
class SnmpTagList(TextualConvention, OctetString):
displayHint = "255t"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(0,255)
- pass
-
+
class SnmpTagValue(TextualConvention, OctetString):
displayHint = "255t"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(0,255)
- pass
-
+
# Objects
@@ -45,7 +43,7 @@ snmpTargetAddrTDomain = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 2), TDoma
if mibBuilder.loadTexts: snmpTargetAddrTDomain.setDescription("This object indicates the transport type of the address\ncontained in the snmpTargetAddrTAddress object.")
snmpTargetAddrTAddress = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 3), TAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetAddrTAddress.setDescription("This object contains a transport address. The format of\nthis address depends on the value of the\nsnmpTargetAddrTDomain object.")
-snmpTargetAddrTimeout = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 4), TimeInterval().clone(1500)).setMaxAccess("readcreate")
+snmpTargetAddrTimeout = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 4), TimeInterval().clone('1500')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetAddrTimeout.setDescription("This object should reflect the expected maximum round\ntrip time for communicating with the transport address\ndefined by this row. When a message is sent to this\naddress, and a response (if one is expected) is not\nreceived within this time period, an implementation\nmay assume that the response will not be delivered.\n\nNote that the time interval that an application waits\nfor a response may actually be derived from the value\nof this object. The method for deriving the actual time\ninterval is implementation dependent. One such method\nis to derive the expected round trip time based on a\nparticular retransmission algorithm and on the number\nof timeouts which have occurred. The type of message may\nalso be considered when deriving expected round trip\ntimes for retransmissions. For example, if a message is\nbeing sent with a securityLevel that indicates both\n\n\n\nauthentication and privacy, the derived value may be\nincreased to compensate for extra processing time spent\nduring authentication and encryption processing.")
snmpTargetAddrRetryCount = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 255)).clone(3)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetAddrRetryCount.setDescription("This object specifies a default number of retries to be\nattempted when a response is not received for a generated\nmessage. An application may provide its own retry count,\nin which case the value of this object is ignored.")
@@ -65,7 +63,7 @@ snmpTargetParamsName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 1), SnmpAd
if mibBuilder.loadTexts: snmpTargetParamsName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpTargetParamsEntry.")
snmpTargetParamsMPModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 2), SnmpMessageProcessingModel()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetParamsMPModel.setDescription("The Message Processing Model to be used when generating\nSNMP messages using this entry.")
-snmpTargetParamsSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 3), SnmpSecurityModel().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("readcreate")
+snmpTargetParamsSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 3), SnmpSecurityModel().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetParamsSecurityModel.setDescription("The Security Model to be used when generating SNMP\nmessages using this entry. An implementation may\nchoose to return an inconsistentValue error if an\nattempt is made to set this variable to a value\nfor a security model which the implementation does\nnot support.")
snmpTargetParamsSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 4), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: snmpTargetParamsSecurityName.setDescription("The securityName which identifies the Principal on\nwhose behalf SNMP messages will be generated using\nthis entry.")
@@ -87,9 +85,17 @@ snmpTargetGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 2))
# Groups
+snmpTargetBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetAddrTDomain"), ("SNMP-TARGET-MIB", "snmpTargetParamsMPModel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityName"), ("SNMP-TARGET-MIB", "snmpTargetAddrTAddress"), ("SNMP-TARGET-MIB", "snmpTargetSpinLock"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityLevel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityModel"), ("SNMP-TARGET-MIB", "snmpTargetAddrRowStatus"), ("SNMP-TARGET-MIB", "snmpTargetAddrStorageType"), ("SNMP-TARGET-MIB", "snmpTargetAddrParams"), ("SNMP-TARGET-MIB", "snmpTargetParamsStorageType"), ("SNMP-TARGET-MIB", "snmpTargetAddrTagList"), ("SNMP-TARGET-MIB", "snmpTargetParamsRowStatus"), )
+if mibBuilder.loadTexts: snmpTargetBasicGroup.setDescription("A collection of objects providing basic remote\nconfiguration of management targets.")
snmpTargetResponseGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 2)).setObjects(("SNMP-TARGET-MIB", "snmpTargetAddrRetryCount"), ("SNMP-TARGET-MIB", "snmpTargetAddrTimeout"), )
+if mibBuilder.loadTexts: snmpTargetResponseGroup.setDescription("A collection of objects providing remote configuration\nof management targets for applications which generate\nSNMP messages for which a response message would be\nexpected.")
snmpTargetCommandResponderGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 3)).setObjects(("SNMP-TARGET-MIB", "snmpUnavailableContexts"), ("SNMP-TARGET-MIB", "snmpUnknownContexts"), )
-snmpTargetBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetAddrTDomain"), ("SNMP-TARGET-MIB", "snmpTargetAddrParams"), ("SNMP-TARGET-MIB", "snmpTargetParamsRowStatus"), ("SNMP-TARGET-MIB", "snmpTargetParamsMPModel"), ("SNMP-TARGET-MIB", "snmpTargetAddrStorageType"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityName"), ("SNMP-TARGET-MIB", "snmpTargetAddrRowStatus"), ("SNMP-TARGET-MIB", "snmpTargetAddrTAddress"), ("SNMP-TARGET-MIB", "snmpTargetParamsStorageType"), ("SNMP-TARGET-MIB", "snmpTargetAddrTagList"), ("SNMP-TARGET-MIB", "snmpTargetSpinLock"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityLevel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityModel"), )
+if mibBuilder.loadTexts: snmpTargetCommandResponderGroup.setDescription("A collection of objects required for command responder\napplications, used for counting error conditions.")
+
+# Compliances
+
+snmpTargetCommandResponderCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 12, 3, 1, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetCommandResponderGroup"), )
+if mibBuilder.loadTexts: snmpTargetCommandResponderCompliance.setDescription("The compliance statement for SNMP entities which include\na command responder application.")
# Exports
@@ -103,4 +109,7 @@ mibBuilder.exportSymbols("SNMP-TARGET-MIB", SnmpTagList=SnmpTagList, SnmpTagValu
mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetMIB=snmpTargetMIB, snmpTargetObjects=snmpTargetObjects, snmpTargetSpinLock=snmpTargetSpinLock, snmpTargetAddrTable=snmpTargetAddrTable, snmpTargetAddrEntry=snmpTargetAddrEntry, snmpTargetAddrName=snmpTargetAddrName, snmpTargetAddrTDomain=snmpTargetAddrTDomain, snmpTargetAddrTAddress=snmpTargetAddrTAddress, snmpTargetAddrTimeout=snmpTargetAddrTimeout, snmpTargetAddrRetryCount=snmpTargetAddrRetryCount, snmpTargetAddrTagList=snmpTargetAddrTagList, snmpTargetAddrParams=snmpTargetAddrParams, snmpTargetAddrStorageType=snmpTargetAddrStorageType, snmpTargetAddrRowStatus=snmpTargetAddrRowStatus, snmpTargetParamsTable=snmpTargetParamsTable, snmpTargetParamsEntry=snmpTargetParamsEntry, snmpTargetParamsName=snmpTargetParamsName, snmpTargetParamsMPModel=snmpTargetParamsMPModel, snmpTargetParamsSecurityModel=snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName=snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel=snmpTargetParamsSecurityLevel, snmpTargetParamsStorageType=snmpTargetParamsStorageType, snmpTargetParamsRowStatus=snmpTargetParamsRowStatus, snmpUnavailableContexts=snmpUnavailableContexts, snmpUnknownContexts=snmpUnknownContexts, snmpTargetConformance=snmpTargetConformance, snmpTargetCompliances=snmpTargetCompliances, snmpTargetGroups=snmpTargetGroups)
# Groups
-mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetResponseGroup=snmpTargetResponseGroup, snmpTargetCommandResponderGroup=snmpTargetCommandResponderGroup, snmpTargetBasicGroup=snmpTargetBasicGroup)
+mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetBasicGroup=snmpTargetBasicGroup, snmpTargetResponseGroup=snmpTargetResponseGroup, snmpTargetCommandResponderGroup=snmpTargetCommandResponderGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetCommandResponderCompliance=snmpTargetCommandResponderCompliance)
diff --git a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py b/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py
new file mode 100644
index 0000000..05872e3
--- /dev/null
+++ b/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py
@@ -0,0 +1,33 @@
+# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USER-BASED-SM-3DES-MIB
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:37:25 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
+
+# Imported just in case new ASN.1 types would be created
+from pyasn1.type import constraint, namedval
+
+# Imports
+
+( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
+( snmpPrivProtocols, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpPrivProtocols")
+( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "TimeTicks", "snmpModules")
+( AutonomousType, ) = mibBuilder.importSymbols("SNMPv2-TC", "AutonomousType")
+
+# Objects
+
+usm3DESEDEPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 3))
+if mibBuilder.loadTexts: usm3DESEDEPrivProtocol.setDescription("The 3DES-EDE Symmetric Encryption Protocol.")
+snmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 15)).setRevisions(("1999-10-06 00:00",))
+if mibBuilder.loadTexts: snmpUsmMIB.setOrganization("SNMPv3 Working Group")
+if mibBuilder.loadTexts: snmpUsmMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In msg body: subscribe snmpv3\n\nChair: Russ Mundy\n NAI Labs\npostal: 3060 Washington Rd\n Glenwood MD 21738\n USA\nemail: mundy@tislabs.com\nphone: +1-443-259-2307\n\nCo-editor: David Reeder\n NAI Labs\npostal: 3060 Washington Road (Route 97)\n Glenwood, MD 21738\n USA\nemail: dreeder@tislabs.com\nphone: +1-443-259-2348\n\nCo-editor: Olafur Gudmundsson\n NAI Labs\npostal: 3060 Washington Road (Route 97)\n Glenwood, MD 21738\n USA\nemail: ogud@tislabs.com\nphone: +1-443-259-2389")
+if mibBuilder.loadTexts: snmpUsmMIB.setDescription("Extension to the SNMP User-based Security Model\nto support Triple-DES EDE in 'Outside' CBC\n(cipher-block chaining) Mode.")
+
+# Augmentions
+
+# Exports
+
+# Module identity
+mibBuilder.exportSymbols("SNMP-USER-BASED-SM-3DES-MIB", PYSNMP_MODULE_ID=snmpUsmMIB)
+
+# Objects
+mibBuilder.exportSymbols("SNMP-USER-BASED-SM-3DES-MIB", usm3DESEDEPrivProtocol=usm3DESEDEPrivProtocol, snmpUsmMIB=snmpUsmMIB)
+
diff --git a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py b/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py
index 9750bdd..df2831f 100644
--- a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py
@@ -71,21 +71,21 @@ class UsmUserSecurityName(MibTableColumn):
name[len(self.name):]
)
return __usmUserName
- def createTest(self, name, val, idx, (acFun, acCtx)):
+ def createTest(self, name, val, idx, acInfo):
return MibTableColumn.createTest(
- self, name, self.__getUsmUserName(name), idx, (acFun, acCtx)
+ self, name, self.__getUsmUserName(name), idx, acInfo
)
- def createCommit(self, name, val, idx, (acFun, acCtx)):
+ def createCommit(self, name, val, idx, acInfo):
return MibTableColumn.createCommit(
- self, name, self.__getUsmUserName(name), idx, (acFun, acCtx)
+ self, name, self.__getUsmUserName(name), idx, acInfo
)
- def createCleanup(self, name, val, idx, (acFun, acCtx)):
+ def createCleanup(self, name, val, idx, acInfo):
return MibTableColumn.createCleanup(
- self, name, self.__getUsmUserName(name), idx, (acFun, acCtx)
+ self, name, self.__getUsmUserName(name), idx, acInfo
)
- def createUndo(self, name, val, idx, (acFun, acCtx)):
+ def createUndo(self, name, val, idx, acInfo):
return MibTableColumn.createUndo(
- self, name, self.__getUsmUserName(name), idx, (acFun, acCtx)
+ self, name, self.__getUsmUserName(name), idx, acInfo
)
usmUserSecurityName = UsmUserSecurityName((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: usmUserSecurityName.setDescription("A human readable string representing the user in\nSecurity Model independent format.\n\nThe default transformation of the User-based Security\nModel dependent security ID to the securityName and\nvice versa is the identity function so that the\nsecurityName is the same as the userName.")
diff --git a/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py b/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py
index d3317a3..38cffb1 100644
--- a/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USM-AES-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:12 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:36:16 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
diff --git a/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py b/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py
index 90efe64..8e85907 100644
--- a/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py
+++ b/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMP-VIEW-BASED-ACM-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:12 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:40:23 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -30,7 +30,7 @@ vacmSecurityToGroupTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 2))
if mibBuilder.loadTexts: vacmSecurityToGroupTable.setDescription("This table maps a combination of securityModel and\nsecurityName into a groupName which is used to define\nan access control policy for a group of principals.")
vacmSecurityToGroupEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 2, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityModel"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityName"))
if mibBuilder.loadTexts: vacmSecurityToGroupEntry.setDescription("An entry in this table maps the combination of a\nsecurityModel and securityName into a groupName.")
-vacmSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 1), SnmpSecurityModel().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("noaccess")
+vacmSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 1), SnmpSecurityModel().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))).setMaxAccess("noaccess")
if mibBuilder.loadTexts: vacmSecurityModel.setDescription("The Security Model, by which the vacmSecurityName\nreferenced by this entry is provided.\n\n\n\nNote, this object may not take the 'any' (0) value.")
vacmSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess")
if mibBuilder.loadTexts: vacmSecurityName.setDescription("The securityName for the principal, represented in a\nSecurity Model independent format, which is mapped by\nthis entry to a groupName.")
@@ -89,7 +89,13 @@ vacmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 2))
# Groups
-vacmBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 16, 2, 2, 1)).setObjects(("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessNotifyViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewSpinLock"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextMatch"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyMask"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessReadViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmContextName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessWriteViewName"), )
+vacmBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 16, 2, 2, 1)).setObjects(("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextMatch"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessReadViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmContextName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessWriteViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessNotifyViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyMask"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewSpinLock"), )
+if mibBuilder.loadTexts: vacmBasicGroup.setDescription("A collection of objects providing for remote\nconfiguration of an SNMP engine which implements\n\n\n\nthe SNMP View-based Access Control Model.")
+
+# Compliances
+
+vacmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 16, 2, 1, 1)).setObjects(("SNMP-VIEW-BASED-ACM-MIB", "vacmBasicGroup"), )
+if mibBuilder.loadTexts: vacmMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP View-based Access Control Model\nconfiguration MIB.")
# Exports
@@ -101,3 +107,6 @@ mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", snmpVacmMIB=snmpVacmMIB, vac
# Groups
mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmBasicGroup=vacmBasicGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmMIBCompliance=vacmMIBCompliance)
diff --git a/pysnmp/smi/mibs/SNMPv2-CONF.py b/pysnmp/smi/mibs/SNMPv2-CONF.py
index bb2787b..056b9d0 100644
--- a/pysnmp/smi/mibs/SNMPv2-CONF.py
+++ b/pysnmp/smi/mibs/SNMPv2-CONF.py
@@ -16,8 +16,7 @@ class ObjectGroup(MibNode):
OBJECT-GROUP\n\
OBJECTS { %s }\n\
DESCRIPTION \"%s\"\
-' % (reduce(lambda x,y: '%s, %s' % (x[1],y[1]), self.getObjects(), ("","")),
- self.getDescription())
+' % (', '.join([ x for x in self.getObjects() ]), self.getDescription())
class NotificationGroup(MibNode):
def getObjects(self):
@@ -35,8 +34,7 @@ class NotificationGroup(MibNode):
NOTIFICATION-GROUP\n\
NOTIFICATIONS { %s }\n\
DESCRIPTION \"%s\"\
-' % (reduce(lambda x,y: '%s, %s' % (x[1],y[1]), self.getObjects(), ("","")),
- self.getDescription())
+' % (', '.join([ x for x in self.getObjects() ]), self.getDescription())
class ModuleCompliance(MibNode):
def getObjects(self):
@@ -54,8 +52,7 @@ class ModuleCompliance(MibNode):
MODULE-COMPLIANCE\n\
OBJECT { %s } \n\
DESCRIPTION \"%s\"\n\
-' % (reduce(lambda x,y: '%s, %s' % (x[1],y[1]), self.getObjects(), ("","")),
- self.getDescription())
+' % (', '.join([ x for x in self.getObjects() ]), self.getDescription())
class AgentCapabilities(MibNode):
def getDescription(self):
diff --git a/pysnmp/smi/mibs/SNMPv2-MIB.py b/pysnmp/smi/mibs/SNMPv2-MIB.py
index 0aba6c9..28889da 100644
--- a/pysnmp/smi/mibs/SNMPv2-MIB.py
+++ b/pysnmp/smi/mibs/SNMPv2-MIB.py
@@ -1,6 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python SNMPv2-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:12 2009,
-# Python version (2, 4, 4, 'final', 0)
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:38:28 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -35,7 +35,7 @@ sysORTable = MibTable((1, 3, 6, 1, 2, 1, 1, 9))
if mibBuilder.loadTexts: sysORTable.setDescription("The (conceptual) table listing the capabilities of\nthe local SNMP application acting as a command\nresponder with respect to various MIB modules.\nSNMP entities having dynamically-configurable support\nof MIB modules will have a dynamically-varying number\nof conceptual rows.")
sysOREntry = MibTableRow((1, 3, 6, 1, 2, 1, 1, 9, 1)).setIndexNames((0, "SNMPv2-MIB", "sysORIndex"))
if mibBuilder.loadTexts: sysOREntry.setDescription("An entry (conceptual row) in the sysORTable.")
-sysORIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("noaccess")
+sysORIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))).setMaxAccess("noaccess")
if mibBuilder.loadTexts: sysORIndex.setDescription("The auxiliary variable used for identifying instances\nof the columnar objects in the sysORTable.")
sysORID = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sysORID.setDescription("An authoritative identification of a capabilities\nstatement with respect to various MIB modules supported\nby the local SNMP application acting as a command\nresponder.")
@@ -126,20 +126,38 @@ snmpMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 2))
# Notifications
-authenticationFailure = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 5)).setObjects()
-warmStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 2)).setObjects()
coldStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)).setObjects()
+if mibBuilder.loadTexts: coldStart.setDescription("A coldStart trap signifies that the SNMP entity,\nsupporting a notification originator application, is\nreinitializing itself and that its configuration may\nhave been altered.")
+warmStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 2)).setObjects()
+if mibBuilder.loadTexts: warmStart.setDescription("A warmStart trap signifies that the SNMP entity,\nsupporting a notification originator application,\nis reinitializing itself such that its configuration\nis unaltered.")
+authenticationFailure = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 5)).setObjects()
+if mibBuilder.loadTexts: authenticationFailure.setDescription("An authenticationFailure trap signifies that the SNMP\nentity has received a protocol message that is not\nproperly authenticated. While all implementations\nof SNMP entities MAY be capable of generating this\ntrap, the snmpEnableAuthenTraps object indicates\nwhether this trap will be generated.")
# Groups
-snmpGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 8)).setObjects(("SNMPv2-MIB", "snmpEnableAuthenTraps"), ("SNMPv2-MIB", "snmpSilentDrops"), ("SNMPv2-MIB", "snmpInASNParseErrs"), ("SNMPv2-MIB", "snmpInPkts"), ("SNMPv2-MIB", "snmpInBadVersions"), ("SNMPv2-MIB", "snmpProxyDrops"), )
-snmpWarmStartNotificationGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 11)).setObjects(("SNMPv2-MIB", "warmStart"), )
-snmpObsoleteGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 10)).setObjects(("SNMPv2-MIB", "snmpOutNoSuchNames"), ("SNMPv2-MIB", "snmpInReadOnlys"), ("SNMPv2-MIB", "snmpInTotalReqVars"), ("SNMPv2-MIB", "snmpInSetRequests"), ("SNMPv2-MIB", "snmpOutGenErrs"), ("SNMPv2-MIB", "snmpOutGetRequests"), ("SNMPv2-MIB", "snmpOutPkts"), ("SNMPv2-MIB", "snmpOutBadValues"), ("SNMPv2-MIB", "snmpOutTraps"), ("SNMPv2-MIB", "snmpInNoSuchNames"), ("SNMPv2-MIB", "snmpInGetNexts"), ("SNMPv2-MIB", "snmpInGetRequests"), ("SNMPv2-MIB", "snmpOutGetResponses"), ("SNMPv2-MIB", "snmpInGenErrs"), ("SNMPv2-MIB", "snmpInTraps"), ("SNMPv2-MIB", "snmpInTotalSetVars"), ("SNMPv2-MIB", "snmpInGetResponses"), ("SNMPv2-MIB", "snmpOutSetRequests"), ("SNMPv2-MIB", "snmpInBadValues"), ("SNMPv2-MIB", "snmpInTooBigs"), ("SNMPv2-MIB", "snmpOutGetNexts"), ("SNMPv2-MIB", "snmpOutTooBigs"), )
+snmpSetGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 5)).setObjects(("SNMPv2-MIB", "snmpSetSerialNo"), )
+if mibBuilder.loadTexts: snmpSetGroup.setDescription("A collection of objects which allow several cooperating\ncommand generator applications to coordinate their\nuse of the set operation.")
+systemGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 6)).setObjects(("SNMPv2-MIB", "sysName"), ("SNMPv2-MIB", "sysObjectID"), ("SNMPv2-MIB", "sysORID"), ("SNMPv2-MIB", "sysUpTime"), ("SNMPv2-MIB", "sysORDescr"), ("SNMPv2-MIB", "sysContact"), ("SNMPv2-MIB", "sysORLastChange"), ("SNMPv2-MIB", "sysLocation"), ("SNMPv2-MIB", "sysServices"), ("SNMPv2-MIB", "sysDescr"), ("SNMPv2-MIB", "sysORUpTime"), )
+if mibBuilder.loadTexts: systemGroup.setDescription("The system group defines objects which are common to all\nmanaged systems.")
snmpBasicNotificationsGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 7)).setObjects(("SNMPv2-MIB", "authenticationFailure"), ("SNMPv2-MIB", "coldStart"), )
+if mibBuilder.loadTexts: snmpBasicNotificationsGroup.setDescription("The basic notifications implemented by an SNMP entity\nsupporting command responder applications.")
+snmpGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 8)).setObjects(("SNMPv2-MIB", "snmpEnableAuthenTraps"), ("SNMPv2-MIB", "snmpSilentDrops"), ("SNMPv2-MIB", "snmpInASNParseErrs"), ("SNMPv2-MIB", "snmpInPkts"), ("SNMPv2-MIB", "snmpInBadVersions"), ("SNMPv2-MIB", "snmpProxyDrops"), )
+if mibBuilder.loadTexts: snmpGroup.setDescription("A collection of objects providing basic instrumentation\nand control of an SNMP entity.")
snmpCommunityGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 9)).setObjects(("SNMPv2-MIB", "snmpInBadCommunityNames"), ("SNMPv2-MIB", "snmpInBadCommunityUses"), )
-snmpNotificationGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 12)).setObjects(("SNMPv2-MIB", "snmpTrapOID"), ("SNMPv2-MIB", "snmpTrapEnterprise"), )
-systemGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 6)).setObjects(("SNMPv2-MIB", "sysName"), ("SNMPv2-MIB", "sysObjectID"), ("SNMPv2-MIB", "sysORLastChange"), ("SNMPv2-MIB", "sysORID"), ("SNMPv2-MIB", "sysLocation"), ("SNMPv2-MIB", "sysServices"), ("SNMPv2-MIB", "sysUpTime"), ("SNMPv2-MIB", "sysORDescr"), ("SNMPv2-MIB", "sysORUpTime"), ("SNMPv2-MIB", "sysDescr"), ("SNMPv2-MIB", "sysContact"), )
-snmpSetGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 5)).setObjects(("SNMPv2-MIB", "snmpSetSerialNo"), )
+if mibBuilder.loadTexts: snmpCommunityGroup.setDescription("A collection of objects providing basic instrumentation\nof a SNMP entity which supports community-based\nauthentication.")
+snmpObsoleteGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 10)).setObjects(("SNMPv2-MIB", "snmpOutNoSuchNames"), ("SNMPv2-MIB", "snmpInReadOnlys"), ("SNMPv2-MIB", "snmpInTotalReqVars"), ("SNMPv2-MIB", "snmpInSetRequests"), ("SNMPv2-MIB", "snmpOutGenErrs"), ("SNMPv2-MIB", "snmpOutGetRequests"), ("SNMPv2-MIB", "snmpOutPkts"), ("SNMPv2-MIB", "snmpOutBadValues"), ("SNMPv2-MIB", "snmpOutTraps"), ("SNMPv2-MIB", "snmpInNoSuchNames"), ("SNMPv2-MIB", "snmpInGetNexts"), ("SNMPv2-MIB", "snmpInGetRequests"), ("SNMPv2-MIB", "snmpOutGetResponses"), ("SNMPv2-MIB", "snmpInGenErrs"), ("SNMPv2-MIB", "snmpInTraps"), ("SNMPv2-MIB", "snmpInTotalSetVars"), ("SNMPv2-MIB", "snmpInGetResponses"), ("SNMPv2-MIB", "snmpOutSetRequests"), ("SNMPv2-MIB", "snmpInBadValues"), ("SNMPv2-MIB", "snmpInTooBigs"), ("SNMPv2-MIB", "snmpOutGetNexts"), ("SNMPv2-MIB", "snmpOutTooBigs"), )
+if mibBuilder.loadTexts: snmpObsoleteGroup.setDescription("A collection of objects from RFC 1213 made obsolete\nby this MIB module.")
+snmpWarmStartNotificationGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 11)).setObjects(("SNMPv2-MIB", "warmStart"), )
+if mibBuilder.loadTexts: snmpWarmStartNotificationGroup.setDescription("An additional notification for an SNMP entity supporting\ncommand responder applications, if it is able to reinitialize\nitself such that its configuration is unaltered.")
+snmpNotificationGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 12)).setObjects(("SNMPv2-MIB", "snmpTrapOID"), ("SNMPv2-MIB", "snmpTrapEnterprise"), )
+if mibBuilder.loadTexts: snmpNotificationGroup.setDescription("These objects are required for entities\nwhich support notification originator applications.")
+
+# Compliances
+
+snmpBasicCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 1, 2, 1, 2)).setObjects(("SNMPv2-MIB", "snmpGroup"), ("SNMPv2-MIB", "systemGroup"), ("SNMPv2-MIB", "snmpBasicNotificationsGroup"), ("SNMPv2-MIB", "snmpSetGroup"), ("SNMPv2-MIB", "snmpCommunityGroup"), )
+if mibBuilder.loadTexts: snmpBasicCompliance.setDescription("The compliance statement for SNMPv2 entities which\nimplement the SNMPv2 MIB.\n\nThis compliance statement is replaced by\nsnmpBasicComplianceRev2.")
+snmpBasicComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 6, 3, 1, 2, 1, 3)).setObjects(("SNMPv2-MIB", "snmpGroup"), ("SNMPv2-MIB", "snmpWarmStartNotificationGroup"), ("SNMPv2-MIB", "snmpBasicNotificationsGroup"), ("SNMPv2-MIB", "snmpCommunityGroup"), ("SNMPv2-MIB", "systemGroup"), ("SNMPv2-MIB", "snmpSetGroup"), )
+if mibBuilder.loadTexts: snmpBasicComplianceRev2.setDescription("The compliance statement for SNMP entities which\nimplement this MIB module.")
# Exports
@@ -150,7 +168,10 @@ mibBuilder.exportSymbols("SNMPv2-MIB", PYSNMP_MODULE_ID=snmpMIB)
mibBuilder.exportSymbols("SNMPv2-MIB", system=system, sysDescr=sysDescr, sysObjectID=sysObjectID, sysUpTime=sysUpTime, sysContact=sysContact, sysName=sysName, sysLocation=sysLocation, sysServices=sysServices, sysORLastChange=sysORLastChange, sysORTable=sysORTable, sysOREntry=sysOREntry, sysORIndex=sysORIndex, sysORID=sysORID, sysORDescr=sysORDescr, sysORUpTime=sysORUpTime, snmp=snmp, snmpInPkts=snmpInPkts, snmpOutPkts=snmpOutPkts, snmpInBadVersions=snmpInBadVersions, snmpInBadCommunityNames=snmpInBadCommunityNames, snmpInBadCommunityUses=snmpInBadCommunityUses, snmpInASNParseErrs=snmpInASNParseErrs, snmpInTooBigs=snmpInTooBigs, snmpInNoSuchNames=snmpInNoSuchNames, snmpInBadValues=snmpInBadValues, snmpInReadOnlys=snmpInReadOnlys, snmpInGenErrs=snmpInGenErrs, snmpInTotalReqVars=snmpInTotalReqVars, snmpInTotalSetVars=snmpInTotalSetVars, snmpInGetRequests=snmpInGetRequests, snmpInGetNexts=snmpInGetNexts, snmpInSetRequests=snmpInSetRequests, snmpInGetResponses=snmpInGetResponses, snmpInTraps=snmpInTraps, snmpOutTooBigs=snmpOutTooBigs, snmpOutNoSuchNames=snmpOutNoSuchNames, snmpOutBadValues=snmpOutBadValues, snmpOutGenErrs=snmpOutGenErrs, snmpOutGetRequests=snmpOutGetRequests, snmpOutGetNexts=snmpOutGetNexts, snmpOutSetRequests=snmpOutSetRequests, snmpOutGetResponses=snmpOutGetResponses, snmpOutTraps=snmpOutTraps, snmpEnableAuthenTraps=snmpEnableAuthenTraps, snmpSilentDrops=snmpSilentDrops, snmpProxyDrops=snmpProxyDrops, snmpMIB=snmpMIB, snmpMIBObjects=snmpMIBObjects, snmpTrap=snmpTrap, snmpTrapOID=snmpTrapOID, snmpTrapEnterprise=snmpTrapEnterprise, snmpTraps=snmpTraps, snmpSet=snmpSet, snmpSetSerialNo=snmpSetSerialNo, snmpMIBConformance=snmpMIBConformance, snmpMIBCompliances=snmpMIBCompliances, snmpMIBGroups=snmpMIBGroups)
# Notifications
-mibBuilder.exportSymbols("SNMPv2-MIB", authenticationFailure=authenticationFailure, warmStart=warmStart, coldStart=coldStart)
+mibBuilder.exportSymbols("SNMPv2-MIB", coldStart=coldStart, warmStart=warmStart, authenticationFailure=authenticationFailure)
# Groups
-mibBuilder.exportSymbols("SNMPv2-MIB", snmpGroup=snmpGroup, snmpWarmStartNotificationGroup=snmpWarmStartNotificationGroup, snmpObsoleteGroup=snmpObsoleteGroup, snmpBasicNotificationsGroup=snmpBasicNotificationsGroup, snmpCommunityGroup=snmpCommunityGroup, snmpNotificationGroup=snmpNotificationGroup, systemGroup=systemGroup, snmpSetGroup=snmpSetGroup)
+mibBuilder.exportSymbols("SNMPv2-MIB", snmpSetGroup=snmpSetGroup, systemGroup=systemGroup, snmpBasicNotificationsGroup=snmpBasicNotificationsGroup, snmpGroup=snmpGroup, snmpCommunityGroup=snmpCommunityGroup, snmpObsoleteGroup=snmpObsoleteGroup, snmpWarmStartNotificationGroup=snmpWarmStartNotificationGroup, snmpNotificationGroup=snmpNotificationGroup)
+
+# Compliances
+mibBuilder.exportSymbols("SNMPv2-MIB", snmpBasicCompliance=snmpBasicCompliance, snmpBasicComplianceRev2=snmpBasicComplianceRev2)
diff --git a/pysnmp/smi/mibs/SNMPv2-SMI.py b/pysnmp/smi/mibs/SNMPv2-SMI.py
index 9af9477..06a8588 100644
--- a/pysnmp/smi/mibs/SNMPv2-SMI.py
+++ b/pysnmp/smi/mibs/SNMPv2-SMI.py
@@ -1,4 +1,3 @@
-import string
from pysnmp.smi.indices import OidOrderedDict
from pysnmp.smi import exval, error
from pysnmp.proto import rfc1902
@@ -90,7 +89,7 @@ MODULE-IDENTITY\n\
self.getOrganization(),
self.getContactInfo(),
self.getDescription(),
- string.join(map(lambda x: "REVISION \"%s\"\n" % x, self.getRevisions())))
+ ''.join([ "REVISION \"%s\"\n" % x for x in self.getRevisions() ]))
class ObjectIdentity(MibNode):
def getStatus(self):
@@ -150,10 +149,10 @@ NOTIFICATION-TYPE\n\
STATUS %s\n\
DESCRIPTION \"%s\"\n\
%s\
-' % (reduce(lambda x,y: '%s, %s' % (x[1],y[1]), self.getObjects(), ("","")),
+' % (', '.join([ x for x in self.getObjects() ]),
self.getStatus(),
self.getDescription(),
- string.join(map(lambda x: "REVISION \"%s\"\n" % x, self.getRevisions())))
+ ''.join([ "REVISION \"%s\"\n" % x for x in self.getRevisions() ]))
class MibIdentifier(MibNode):
def asn1Print(self):
@@ -166,7 +165,12 @@ class ObjectType(MibNode):
self.syntax = syntax
# XXX
- def __cmp__(self, other): return cmp(self.syntax, other)
+ def __eq__(self, other): return self.syntax == other
+ def __ne__(self, other): return self.syntax != other
+ def __lt__(self, other): return self.syntax < other
+ def __le__(self, other): return self.syntax <= other
+ def __gt__(self, other): return self.syntax > other
+ def __ge__(self, other): return self.syntax >= other
def __repr__(self):
return '%s(%s, %s)' % (
@@ -217,7 +221,7 @@ OBJECT-TYPE\n\
self.getReference())
class MibTree(ObjectType):
- branchVersionId = 0L # increments on tree structure change XXX
+ branchVersionId = 0 # increments on tree structure change XXX
maxAccess = 'not-accessible'
def __init__(self, name, syntax=None):
ObjectType.__init__(self, name, syntax)
@@ -272,8 +276,9 @@ class MibTree(ObjectType):
nextNode = self.getBranch(name, idx)
except error.NoSuchObjectError:
# Start from the beginning
- if self._vars and name <= self._vars.keys()[0]:
- return self._vars[self._vars.keys()[0]]
+ if self._vars: first = list(self._vars.keys())[0]
+ if self._vars and name <= first:
+ return self._vars[first]
else:
# Try following the white rabbit at our level
try:
@@ -293,7 +298,8 @@ class MibTree(ObjectType):
# Read operation
- def readTest(self, name, val, idx, (acFun, acCtx)):
+ def readTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if name == self.name:
if acFun and \
self.maxAccess != 'readonly' and \
@@ -309,7 +315,8 @@ class MibTree(ObjectType):
node.readTest(name, val, idx, (acFun, acCtx))
- def readGet(self, name, val, idx, (acFun, acCtx)):
+ def readGet(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
try:
node = self.getBranch(name, idx)
except error.NoSuchObjectError:
@@ -319,7 +326,8 @@ class MibTree(ObjectType):
# Read next operation is subtree-specific
- def readTestNext(self, name, val, idx, (acFun, acCtx)):
+ def readTestNext(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
nextName = name
while 1: # XXX linear search here
try:
@@ -331,7 +339,8 @@ class MibTree(ObjectType):
except error.NoAccessError:
continue
- def readGetNext(self, name, val, idx, (acFun, acCtx)):
+ def readGetNext(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
nextName = name
while 1:
try:
@@ -347,7 +356,8 @@ class MibTree(ObjectType):
# Write operation
- def writeTest(self, name, val, idx, (acFun, acCtx)):
+ def writeTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if name == self.name:
# Make sure variable is writable
if acFun and \
@@ -359,13 +369,16 @@ class MibTree(ObjectType):
node = self.getBranch(name, idx)
node.writeTest(name, val, idx, (acFun, acCtx))
- def writeCommit(self, name, val, idx, (acFun, acCtx)):
+ def writeCommit(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
self.getBranch(name, idx).writeCommit(name, val, idx, (acFun, acCtx))
- def writeCleanup(self, name, val, idx, (acFun, acCtx)):
+ def writeCleanup(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
self.getBranch(name, idx).writeCleanup(name, val, idx, (acFun, acCtx))
- def writeUndo(self, name, val, idx, (acFun, acCtx)):
+ def writeUndo(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
self.getBranch(name, idx).writeUndo(name, val, idx, (acFun, acCtx))
class MibScalar(MibTree):
@@ -376,7 +389,8 @@ class MibScalar(MibTree):
# Read operation
- def readTest(self, name, val, idx, (acFun, acCtx)):
+ def readTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if name == self.name:
raise error.NoAccessError(idx=idx, name=name)
else:
@@ -391,7 +405,8 @@ class MibScalar(MibTree):
# Two-phase commit implementation
- def writeTest(self, name, val, idx, (acFun, acCtx)):
+ def writeTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if name == self.name:
raise error.NoAccessError(idx=idx, name=name)
else:
@@ -424,11 +439,11 @@ class MibScalarInstance(MibTree):
# Read operation
- def readTest(self, name, val, idx, (acFun, acCtx)):
+ def readTest(self, name, val, idx, acInfo):
if name != self.name:
raise error.NoSuchObjectError(idx=idx, name=name)
- def readGet(self, name, val, idx, (acFun, acCtx)):
+ def readGet(self, name, val, idx, acInfo):
# Return current variable (name, value). This is the only API method
# capable of returning anything!
if name == self.name:
@@ -439,7 +454,7 @@ class MibScalarInstance(MibTree):
# Write operation: two-phase commit
- def writeTest(self, name, val, idx, (acFun, acCtx)):
+ def writeTest(self, name, val, idx, acInfo):
# Make sure write's allowed
if name == self.name:
if hasattr(self.syntax, 'smiWrite'):
@@ -451,19 +466,19 @@ class MibScalarInstance(MibTree):
else:
raise error.NoSuchObjectError(idx=idx, name=name)
- def writeCommit(self, name, val, idx, (acFun, acCtx)):
+ def writeCommit(self, name, val, idx, acInfo):
# Backup original value
if self.__oldSyntax is None:
self.__oldSyntax = self.syntax
# Commit new value
self.syntax = self.__newSyntax
- def writeCleanup(self, name, val, idx, (acFun, acCtx)):
+ def writeCleanup(self, name, val, idx, acInfo):
debug.logger & debug.flagIns and debug.logger('writeCleanup: %s=%s' % (name, repr(val)))
# Drop previous value
self.__newSyntax = self.__oldSyntax = None
- def writeUndo(self, name, val, idx, (acFun, acCtx)):
+ def writeUndo(self, name, val, idx, acInfo):
# Revive previous value
self.syntax = self.__oldSyntax
self.__newSyntax = self.__oldSyntax = None
@@ -472,7 +487,7 @@ class MibScalarInstance(MibTree):
# Create operation
- def createTest(self, name, val, idx, (acFun, acCtx)):
+ def createTest(self, name, val, idx, acInfo):
if name == self.name:
if hasattr(self.syntax, 'smiCreate'):
self.__newSyntax = self.syntax.smiCreate(name, val, idx)
@@ -480,20 +495,23 @@ class MibScalarInstance(MibTree):
self.__newSyntax = self.syntax.clone(val)
else:
raise error.NoSuchObjectError(idx=idx, name=name)
- def createCommit(self, name, val, idx, (acFun, acCtx)):
+ def createCommit(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if val is not None:
self.writeCommit(name, val, idx, (acFun, acCtx))
- def createCleanup(self, name, val, idx, (acFun, acCtx)):
+ def createCleanup(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
debug.logger & debug.flagIns and debug.logger('createCleanup: %s=%s' % (name, repr(val)))
if val is not None:
self.writeCleanup(name, val, idx, (acFun, acCtx))
- def createUndo(self, name, val, idx, (acFun, acCtx)):
+ def createUndo(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if val is not None:
self.writeUndo(name, val, idx, (acFun, acCtx))
# Destroy operation
- def destroyTest(self, name, val, idx, (acFun, acCtx)):
+ def destroyTest(self, name, val, idx, acInfo):
if name == self.name:
if hasattr(self.syntax, 'smiDestroy'):
self.__newSyntax = self.syntax.smiDestoy(name, val)
@@ -501,9 +519,9 @@ class MibScalarInstance(MibTree):
self.__newSyntax = self.syntax.clone(val)
else:
raise error.NoSuchObjectError(idx=idx, name=name)
- def destroyCommit(self, name, val, idx, (acFun, acCtx)): pass
- def destroyCleanup(self, name, val, idx, (acFun, acCtx)): pass
- def destroyUndo(self, name, val, idx, (acFun, acCtx)): pass
+ def destroyCommit(self, name, val, idx, acInfo): pass
+ def destroyCleanup(self, name, val, idx, acInfo): pass
+ def destroyUndo(self, name, val, idx, acInfo): pass
# Conceptual table classes
@@ -572,7 +590,8 @@ class MibTableColumn(MibScalar):
# machine for clarity). Also, it might be a good idea to inidicate
# defaulted cols creation in a clearer way than just a val == None.
- def createTest(self, name, val, idx, (acFun, acCtx)):
+ def createTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Make sure creation allowed, create a new column instance but
# do not replace the old one
if name == self.name:
@@ -594,7 +613,8 @@ class MibTableColumn(MibScalar):
name, val, idx, (acFun, acCtx)
)
- def createCommit(self, name, val, idx, (acFun, acCtx)):
+ def createCommit(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Commit new instance value
if name in self._vars: # XXX
if name in self.__createdInstances:
@@ -607,7 +627,8 @@ class MibTableColumn(MibScalar):
self._vars[name], self.__createdInstances[name] = \
self.__createdInstances[name], self._vars.get(name)
- def createCleanup(self, name, val, idx, (acFun, acCtx)):
+ def createCleanup(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Drop by-value index
self.__valIdx.clear()
@@ -621,7 +642,8 @@ class MibTableColumn(MibScalar):
elif name in self._vars:
self._vars[name].createCleanup(name, val, idx, (acFun, acCtx))
- def createUndo(self, name, val, idx, (acFun, acCtx)):
+ def createUndo(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Set back previous column instance, drop the new one
if name in self.__createdInstances:
self._vars[name] = self.__createdInstances[name]
@@ -640,7 +662,8 @@ class MibTableColumn(MibScalar):
# Column destruction
- def destroyTest(self, name, val, idx, (acFun, acCtx)):
+ def destroyTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Make sure destruction is allowed
if name == self.name:
raise error.NoAccessError(idx=idx, name=name)
@@ -655,7 +678,8 @@ class MibTableColumn(MibScalar):
name, val, idx, (acFun, acCtx)
)
- def destroyCommit(self, name, val, idx, (acFun, acCtx)):
+ def destroyCommit(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Make a copy of column instance and take it off the tree
if name in self._vars:
self._vars[name].destroyCommit(
@@ -664,7 +688,8 @@ class MibTableColumn(MibScalar):
self.__destroyedInstances[name] = self._vars[name]
del self._vars[name]
- def destroyCleanup(self, name, val, idx, (acFun, acCtx)):
+ def destroyCleanup(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Drop by-value index
self.__valIdx.clear()
@@ -676,7 +701,8 @@ class MibTableColumn(MibScalar):
debug.logger & debug.flagIns and debug.logger('destroyCleanup: %s=%s' % (name, repr(val)))
del self.__destroyedInstances[name]
- def destroyUndo(self, name, val, idx, (acFun, acCtx)):
+ def destroyUndo(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Set back column instance
if name in self.__destroyedInstances:
self._vars[name] = self.__destroyedInstances[name]
@@ -687,7 +713,8 @@ class MibTableColumn(MibScalar):
# Set/modify column
- def writeTest(self, name, val, idx, (acFun, acCtx)):
+ def writeTest(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Besides common checks, request row creation on no-instance
try:
# First try the instance
@@ -705,7 +732,8 @@ class MibTableColumn(MibScalar):
debug.logger & debug.flagIns and debug.logger('%s flagged by %s=%s' % (self.__rowOpWanted[name], name, repr(val)))
raise self.__rowOpWanted[name]
- def __delegateWrite(self, subAction, name, val, idx, (acFun, acCtx)):
+ def __delegateWrite(self, subAction, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
if name not in self.__rowOpWanted:
getattr(MibScalar, 'write'+subAction)(
self, name, val, idx, (acFun, acCtx)
@@ -720,14 +748,16 @@ class MibTableColumn(MibScalar):
name, val, idx, (acFun, acCtx)
)
- def writeCommit(self, name, val, idx, (acFun, acCtx)):
+ def writeCommit(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
self.__delegateWrite(
'Commit', name, val, idx, (acFun, acCtx)
)
if name in self.__rowOpWanted:
raise self.__rowOpWanted[name]
- def writeCleanup(self, name, val, idx, (acFun, acCtx)):
+ def writeCleanup(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Drop by-value index
self.__valIdx.clear()
@@ -740,7 +770,8 @@ class MibTableColumn(MibScalar):
debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%s' % (e, name, repr(val)))
raise e
- def writeUndo(self, name, val, idx, (acFun, acCtx)):
+ def writeUndo(self, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
self.__delegateWrite(
'Undo', name, val, idx, (acFun, acCtx)
)
@@ -775,29 +806,21 @@ class MibTableRow(MibTree):
def setFromName(self, obj, value, impliedFlag=None):
if not value:
raise error.SmiError('Short OID for index %s' % repr(obj))
+ value = tuple(value) # possible ObjectIdentifiers
baseTag = obj.getTagSet().getBaseTag()
if baseTag == self.__intBaseTag:
return obj.clone(value[0]), value[1:]
elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()):
- return obj.clone(string.join(map(str, value[:4]), '.')), value[4:]
+ return obj.clone('.'.join([str(x) for x in value[:4]])), value[4:]
elif baseTag == self.__strBaseTag:
# rfc1902, 7.7
if impliedFlag:
- s = ''
- for c in value:
- s = s + chr(c)
- return obj.clone(s), ()
+ return obj.clone(value), ()
elif obj.isFixedLength():
l = obj.getFixedLength()
- s = ''
- for c in value[:l]:
- s = s + chr(c)
- return obj.clone(s), value[l:]
+ return obj.clone(value[:l]), value[l:]
else:
- s = ''
- for c in value[1:value[0]+1]:
- s = s + chr(c)
- return obj.clone(s), value[value[0]+1:]
+ return obj.clone(value[1:value[0]+1]), value[value[0]+1:]
elif baseTag == self.__oidBaseTag:
if impliedFlag:
return obj.clone(value), ()
@@ -805,10 +828,7 @@ class MibTableRow(MibTree):
return obj.clone(value[1:value[0]+1]), value[value[0]+1:]
# rfc2578, 7.1
elif baseTag == self.__bitsBaseTag:
- s = ''
- for c in valuevalue[1:value[0]+1]:
- s = s + chr(c)
- return obj.clone(s), value[value[0]+1:]
+ return obj.clone(value[1:value[0]+1]), value[value[0]+1:]
else:
raise error.SmiError('Unknown value type for index %s' % repr(obj))
@@ -817,15 +837,13 @@ class MibTableRow(MibTree):
if baseTag == self.__intBaseTag:
return (int(obj),)
elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()):
- return tuple(map(ord, obj))
+ return obj.asNumbers()
elif baseTag == self.__strBaseTag:
if impliedFlag or obj.isFixedLength():
initial = ()
else:
initial = (len(obj),)
- for c in str(obj):
- initial = initial + (ord(c),)
- return initial
+ return initial + obj.asNumbers()
elif baseTag == self.__oidBaseTag:
if impliedFlag:
return tuple(obj)
@@ -833,15 +851,14 @@ class MibTableRow(MibTree):
return (len(self.name),) + tuple(obj)
# rfc2578, 7.1
elif baseTag == self.__bitsBaseTag:
- return reduce(
- lambda x,y: x+(y,), map(lambda x: ord(x), obj),(len(obj),)
- )
+ return ( len(obj), ) + obj.asNumbers()
else:
raise error.SmiError('Unknown value type for index %s' % repr(obj))
# Fate sharing mechanics
- def announceManagementEvent(self, action, name, val, idx, (acFun, acCtx)):
+ def announceManagementEvent(self, action, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Convert OID suffix into index vals
instId = name[len(self.name)+1:]
baseIndices = []
@@ -866,9 +883,8 @@ class MibTableRow(MibTree):
action, baseIndices, val, idx, (acFun, acCtx)
)
- def receiveManagementEvent(
- self, action, baseIndices, val, idx, (acFun, acCtx)
- ):
+ def receiveManagementEvent(self, action, baseIndices, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# The default implementation supports one-to-one rows dependency
newSuffix = ()
# Resolve indices intersection
@@ -901,7 +917,8 @@ class MibTableRow(MibTree):
return self.indexNames
def __manageColumns(self, action, excludeName, nameSuffix,
- val, idx, (acFun, acCtx)):
+ val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Build a map of index names and values for automatic initialization
indexVals = {}; instId = nameSuffix
for impliedFlag, modName, symName in self.indexNames:
@@ -921,13 +938,14 @@ class MibTableRow(MibTree):
(acFun, acCtx))
debug.logger & debug.flagIns and debug.logger('__manageColumns: action %s name %s suffix %s %svalue %s' % (action, name, nameSuffix, name in indexVals and "index " or "", repr(indexVals.get(name, val))))
- def __delegate(self, subAction, name, val, idx, (acFun, acCtx)):
+ def __delegate(self, subAction, name, val, idx, acInfo):
+ (acFun, acCtx) = acInfo
# Relay operation request to column, expect row operation request.
try:
getattr(self.getBranch(name, idx), 'write'+subAction)(
name, val, idx, (acFun, acCtx)
)
- except error.RowCreationWanted, why:
+ except error.RowCreationWanted:
self.__manageColumns(
'create'+subAction, name[:len(self.name)+1],
name[len(self.name)+1:], None, idx, (acFun, acCtx)
@@ -935,7 +953,7 @@ class MibTableRow(MibTree):
self.announceManagementEvent(
'create'+subAction, name, None, idx, (acFun, acCtx)
)
- except error.RowDestructionWanted, why:
+ except error.RowDestructionWanted:
self.__manageColumns(
'destroy'+subAction, name[:len(self.name)+1],
name[len(self.name)+1:], None, idx, (acFun, acCtx)
@@ -944,14 +962,14 @@ class MibTableRow(MibTree):
'destroy'+subAction, name, None, idx, (acFun,acCtx)
)
- def writeTest(self, name, val, idx, (acFun, acCtx)):
- self.__delegate('Test', name, val, idx, (acFun, acCtx))
- def writeCommit(self, name, val, idx, (acFun, acCtx)):
- self.__delegate('Commit', name, val, idx, (acFun, acCtx))
- def writeCleanup(self, name, val, idx, (acFun, acCtx)):
- self.__delegate('Cleanup', name, val, idx, (acFun, acCtx))
- def writeUndo(self, name, val, idx, (acFun, acCtx)):
- self.__delegate('Undo', name, val, idx, (acFun, acCtx))
+ def writeTest(self, name, val, idx, acInfo):
+ self.__delegate('Test', name, val, idx, acInfo)
+ def writeCommit(self, name, val, idx, acInfo):
+ self.__delegate('Commit', name, val, idx, acInfo)
+ def writeCleanup(self, name, val, idx, acInfo):
+ self.__delegate('Cleanup', name, val, idx, acInfo)
+ def writeUndo(self, name, val, idx, acInfo):
+ self.__delegate('Undo', name, val, idx, acInfo)
# Table row management
@@ -1001,18 +1019,16 @@ class MibTableRow(MibTree):
def getInstNameByIndex(self, colId, *indices):
"""Build column instance name from components"""
- return self.name + (colId,) + apply(
- self.getInstIdFromIndices, indices
- )
+ return self.name + (colId,) + self.getInstIdFromIndices(*indices)
def getInstNamesByIndex(self, *indices):
"""Build column instance names from indices"""
instNames = []
for columnName in self._vars.keys():
instNames.append(
- apply(self.getInstNameByIndex,
- (columnName[-1],) + indices)
+ self.getInstNameByIndex(*(columnName[-1],) + indices)
)
+
return tuple(instNames)
class MibTable(MibTree):
diff --git a/pysnmp/smi/mibs/SNMPv2-TC.py b/pysnmp/smi/mibs/SNMPv2-TC.py
index a662aa1..b775535 100644
--- a/pysnmp/smi/mibs/SNMPv2-TC.py
+++ b/pysnmp/smi/mibs/SNMPv2-TC.py
@@ -1,4 +1,4 @@
-from string import split, digits
+import sys
from pysnmp.smi import error
from pyasn1.type import constraint, namedval
from pysnmp import debug
@@ -37,15 +37,16 @@ class TextualConvention:
self.__counter32.isSuperTypeOf(self) or
self.__counter64.isSuperTypeOf(self)
):
- t, f = apply(lambda t, f=0: (t, f), split(self.displayHint, '-'))
+ _ = lambda t, f=0: (t, f)
+ t, f = _(*self.displayHint.split('-'))
if t == 'x':
return '0x%x' % value
elif t == 'd':
try:
return '%.*f' % (int(f), float(value)/pow(10, int(f)))
- except StandardError, why:
+ except Exception:
raise error.SmiError(
- 'float num evaluation error: %s' % why
+ 'float num evaluation error: %s' % sys.exc_info()[1]
)
elif t == 'o':
return '0%o' % value
@@ -54,31 +55,31 @@ class TextualConvention:
while v:
r.insert(0, '%d' % (v&0x01))
v = v>>1
- return join(r, '')
+ return ''.join(r)
else:
raise error.SmiError(
'Unsupported numeric type spec: %s' % t
)
elif self.displayHint and self.__octetString.isSuperTypeOf(self):
r = ''
- v = str(value)
+ v = self.__class__(value).asNumbers()
d = self.displayHint
while v and d:
# 1
if d[0] == '*':
- repeatIndicator = repeatCount = int(v[0])
+ repeatIndicator = repeatCount = v[0]
d = d[1:]; v = v[1:]
else:
repeatCount = 1; repeatIndicator = None
# 2
octetLength = ''
- while d and d[0] in digits:
+ while d and d[0] in '0123456789':
octetLength = octetLength + d[0]
d = d[1:]
try:
octetLength = int(octetLength)
- except StandardError, why:
+ except Exception:
raise error.SmiError(
'Bad octet length: %s' % octetLength
)
@@ -91,7 +92,7 @@ class TextualConvention:
d = d[1:]
# 4
- if d and d[0] not in digits and d[0] != '*':
+ if d and d[0] not in '0123456789' and d[0] != '*':
displaySep = d[0]
d = d[1:]
else:
@@ -109,18 +110,18 @@ class TextualConvention:
repeatCount = repeatCount - 1
# 't' stands for UTF-8, does it need any special support?
if displayFormat == 'a' or displayFormat == 't':
- r = r + v[:octetLength]
+ r = r + ''.join([ chr(x) for x in v[:octetLength] ])
elif displayFormat in ('x', 'd', 'o'):
- n = 0L; vv = v[:octetLength]
+ n = 0; vv = v[:octetLength]
while vv:
n = n << 8
try:
- n = n | ord(vv[0])
+ n = n | vv[0]
vv = vv[1:]
- except StandardError, why:
+ except Exception:
raise error.SmiError(
'Display format eval failure: %s: %s'
- % (vv, why)
+ % (vv, sys.exc_info()[1])
)
if displayFormat == 'x':
r = r + '%02x' % n
@@ -155,9 +156,9 @@ class TextualConvention:
# elif self.bits:
# try:
# return self.bits[value]
-# except StandardError, why:
+# except Exception:
# raise error.SmiError(
-# 'Enumeratin resolution failure for %s: %s' % (self, why)
+# 'Enumeratin resolution failure for %s: %s' % (self, sys.exc_info()[1])
# )
# XXX
@@ -182,7 +183,7 @@ class TruthValue(Integer, TextualConvention):
namedValues = namedval.NamedValues(('true', 1), ('false', 2))
class TestAndIncr(Integer, TextualConvention):
- subtypeSpec = Integer.subtypeSpec+constraint.ValueRangeConstraint(0, 2147483647L)
+ subtypeSpec = Integer.subtypeSpec+constraint.ValueRangeConstraint(0, 2147483647)
defaultValue = 0
def smiWrite(self, name, value, idx):
if value != self:
@@ -209,7 +210,7 @@ class RowStatus(Integer, TextualConvention):
)
# Known row states
stNotExists, stActive, stNotInService, stNotReady, \
- stCreateAndGo, stCreateAndWait, stDestroy = range(7)
+ stCreateAndGo, stCreateAndWait, stDestroy = list(range(7))
# States transition matrix (see RFC-1903)
stateMatrix = {
# (new-state, current-state) -> (error, new-state)
@@ -316,7 +317,7 @@ class RowStatus(Integer, TextualConvention):
class TimeStamp(TimeTicks, TextualConvention): pass
class TimeInterval(Integer, TextualConvention):
- subtypeSpec = Integer.subtypeSpec+constraint.ValueRangeConstraint(0, 2147483647L)
+ subtypeSpec = Integer.subtypeSpec+constraint.ValueRangeConstraint(0, 2147483647)
class DateAndTime(TextualConvention, OctetString):
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(8, 11)
diff --git a/pysnmp/smi/mibs/SNMPv2-TM.py b/pysnmp/smi/mibs/SNMPv2-TM.py
index 226314a..8a5dada 100644
--- a/pysnmp/smi/mibs/SNMPv2-TM.py
+++ b/pysnmp/smi/mibs/SNMPv2-TM.py
@@ -1,4 +1,3 @@
-import types, string
from pyasn1.type import constraint
OctetString, = mibBuilder.importSymbols('ASN1', 'OctetString')
@@ -18,18 +17,18 @@ class SnmpUDPAddress(TextualConvention, OctetString):
displayHint = "1d.1d.1d.1d/2d"
def prettyIn(self, value):
- if type(value) == types.TupleType:
+ if isinstance(value, tuple):
# Wild hack -- need to implement TextualConvention.prettyIn
- return reduce(lambda x,y: x+y, map(lambda x: chr(string.atoi(x)), string.split(value[0], '.'))) + chr((value[1] >> 8) & 0xff) + chr((value[1] & 0xff))
- else:
- return OctetString.prettyIn(self, value)
+ value = [ int(x) for x in value[0].split('.') ] + \
+ [ (value[1] >> 8) & 0xff, value[1] & 0xff ]
+ return OctetString.prettyIn(self, value)
# Socket address syntax coercion
def __getitem__(self, i):
if not hasattr(self, '__tuple_value'):
+ ints = self.asNumbers()
self.__tuple_value = (
- '%s.%s.%s.%s' % (ord(self._value[0]), ord(self._value[1]),ord(self._value[2]),ord(self._value[3])),
- ord(self._value[4]) << 8 | ord(self._value[5])
+ '.'.join(['%d' % x for x in ints[:4]]), ints[4] << 8 | ints[5]
)
return self.__tuple_value[i]
diff --git a/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py b/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py
index 5168085..2f09075 100644
--- a/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py
+++ b/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py
@@ -1,9 +1,6 @@
# PySNMP SMI module. Autogenerated from smidump -f python TRANSPORT-ADDRESS-MIB
-# by libsmi2pysnmp-0.0.9-alpha at Thu Mar 26 20:58:12 2009,
-# Python version (2, 4, 4, 'final', 0)
-
-import socket
-import types
+# by libsmi2pysnmp-0.1.1 at Sun Nov 6 01:40:56 2011,
+# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imported just in case new ASN.1 types would be created
from pyasn1.type import constraint, namedval
@@ -18,46 +15,44 @@ from pyasn1.type import constraint, namedval
class TransportAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(0,255)
- pass
-
+
class TransportAddressDns(TextualConvention, OctetString):
displayHint = "1a"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(1,255)
- pass
-
+
class TransportAddressIPv4(TextualConvention, OctetString):
displayHint = "1d.1d.1d.1d:2d"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(6,6)
fixedLength = 6
def prettyIn(self, value):
- if type(value) == types.TupleType:
- return reduce(lambda x,y: x+y, map(lambda x: chr(string.atoi(x)), string.split(value[0], '.'))) + chr((value[1] >> 8) & 0xff) + chr((value[1] & 0xff))
- else:
- return OctetString.prettyIn(self, value)
+ if isinstance(value, tuple):
+ # Wild hack -- need to implement TextualConvention.prettyIn
+ value = [ int(x) for x in value[0].split('.') ] + \
+ [ (value[1] >> 8) & 0xff, value[1] & 0xff ]
+ return OctetString.prettyIn(self, value)
# Socket address syntax coercion
def __getitem__(self, i):
if not hasattr(self, '__tuple_value'):
+ ints = self.asNumbers()
self.__tuple_value = (
- string.join(map(lambda x: str(ord(x)), self._value[:4]), '.'),
- ord(self._value[4:5]) << 8 | ord(self._value[5:6])
+ '.'.join(['%d' % x for x in ints[:4]]), ints[4] << 8 | ints[5]
)
return self.__tuple_value[i]
-
+
class TransportAddressIPv4z(TextualConvention, OctetString):
displayHint = "1d.1d.1d.1d%4d:2d"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(10,10)
fixedLength = 10
- pass
-
+
class TransportAddressIPv6(TextualConvention, OctetString):
displayHint = "0a[2x:2x:2x:2x:2x:2x:2x:2x]0a:2d"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(18,18)
fixedLength = 18
def prettyIn(self, value):
- if type(value) == types.TupleType:
+ if isinstance(value, tuple):
return socket.inet_pton(socket.AF_INET6, value[0]) + chr((value[1] >> 8) & 0xff) + chr((value[1] & 0xff))
else:
return OctetString.prettyIn(self, value)
@@ -71,23 +66,20 @@ class TransportAddressIPv6(TextualConvention, OctetString):
0,
0)
return self.__tuple_value[i]
-
+
class TransportAddressIPv6z(TextualConvention, OctetString):
displayHint = "0a[2x:2x:2x:2x:2x:2x:2x:2x%4d]0a:2d"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(22,22)
fixedLength = 22
- pass
-
+
class TransportAddressLocal(TextualConvention, OctetString):
displayHint = "1a"
subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(1,255)
- pass
-
+
class TransportAddressType(Integer):
- subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(12,9,14,2,7,1,8,0,11,15,16,3,4,10,6,5,13,)
+ subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(12,9,14,2,7,8,0,11,1,15,16,3,4,10,6,5,13,)
namedValues = namedval.NamedValues(("unknown", 0), ("udpIpv4", 1), ("sctpIpv6", 10), ("sctpIpv4z", 11), ("sctpIpv6z", 12), ("local", 13), ("udpDns", 14), ("tcpDns", 15), ("sctpDns", 16), ("udpIpv6", 2), ("udpIpv4z", 3), ("udpIpv6z", 4), ("tcpIpv4", 5), ("tcpIpv6", 6), ("tcpIpv4z", 7), ("tcpIpv6z", 8), ("sctpIpv4", 9), )
- pass
-
+
class TransportDomain(ObjectIdentifier):
pass
diff --git a/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py b/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
index 66326c5..ea7f20f 100644
--- a/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
+++ b/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
@@ -98,7 +98,7 @@ class SysUpTime(TimeTicks):
def clone(self, **kwargs):
if 'value' not in kwargs:
kwargs['value'] = int((time()-self.createdAt)*100)
- return apply(TimeTicks.clone, [self], kwargs)
+ return TimeTicks.clone(self, **kwargs)
__sysUpTime = MibScalarInstance(sysUpTime.name, (0,), SysUpTime(0))
__sysContact = MibScalarInstance(sysContact.name, (0,), sysContact.syntax.clone(''))
diff --git a/pysnmp/smi/view.py b/pysnmp/smi/view.py
index fcdd716..e7afd2b 100644
--- a/pysnmp/smi/view.py
+++ b/pysnmp/smi/view.py
@@ -1,11 +1,19 @@
# MIB modules management
-from types import ClassType, InstanceType, TupleType
+import sys
from pysnmp.smi.indices import OrderedDict, OidOrderedDict
from pysnmp.smi import error
from pysnmp import debug
__all__ = [ 'MibViewController' ]
+if sys.version_info[0] <= 2:
+ import types
+ classTypes = (types.ClassType, type)
+ instanceTypes = (types.InstanceType, object)
+else:
+ classTypes = (type,)
+ instanceTypes = (object,)
+
class MibViewController:
def __init__(self, mibBuilder):
self.mibBuilder = mibBuilder
@@ -34,26 +42,17 @@ class MibViewController:
# This is potentionally ambiguous mapping. Sort modules in
# ascending age for resolution
- def __sortFun(x, y, s=self.mibBuilder.mibSymbols):
+ def __sortFun(x, s=self.mibBuilder.mibSymbols):
if "PYSNMP_MODULE_ID" in s[x]:
- m1 = s[x]["PYSNMP_MODULE_ID"]
- else:
- m1 = None
- if "PYSNMP_MODULE_ID" in s[y]:
- m2 = s[y]["PYSNMP_MODULE_ID"]
+ m = s[x]["PYSNMP_MODULE_ID"]
+ r = m.getRevisions()
+ if r:
+ return r[0]
else:
- m2 = None
- r1 = r2 = "1970-01-01 00:00"
- if m1:
- r = m1.getRevisions()
- if r: r1 = r[0]
- if m2:
- r = m2.getRevisions()
- if r: r2 = r[0]
- return cmp(r1, r2)
+ return "1970-01-01 00:00"
- modNames = self.mibBuilder.mibSymbols.keys()
- modNames.sort(__sortFun)
+ modNames = list(self.mibBuilder.mibSymbols.keys())
+ modNames.sort(key=__sortFun)
# Index modules names
for modName in [ '' ] + modNames:
@@ -74,7 +73,7 @@ class MibViewController:
for n, v in self.mibBuilder.mibSymbols[modName].items():
if n == "PYSNMP_MODULE_ID": # do not index this special symbol
continue
- if type(v) == ClassType:
+ if isinstance(v, classTypes):
if n in mibMod['typeToModIdx']:
raise error.SmiError(
'Duplicate SMI type %s::%s, has %s' % \
@@ -82,7 +81,7 @@ class MibViewController:
)
globMibMod['typeToModIdx'][n] = modName
mibMod['typeToModIdx'][n] = modName
- elif type(v) == InstanceType:
+ elif isinstance(v, instanceTypes):
if isinstance(v, MibScalarInstance):
continue
if n in mibMod['varToNameIdx']:
@@ -175,7 +174,7 @@ class MibViewController:
nodeName[:-1], oidToLabelIdx, labelToOidIdx
)
suffix = suffix + nodeName[-1:]
- resLabel = label + suffix
+ resLabel = label + tuple([ str(x) for x in suffix ])
if resLabel in labelToOidIdx:
return labelToOidIdx[resLabel], resLabel, ()
resOid = oid + suffix
diff --git a/setup.py b/setup.py
index c729e2b..0a18919 100644
--- a/setup.py
+++ b/setup.py
@@ -1,41 +1,52 @@
#!/usr/bin/env python
import sys
-import string
def howto_install_setuptools():
- print """Error: You need setuptools Python package!
+ print("""Error: You need setuptools Python package!
It's very easy to install it, just type (as root on Linux):
wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py
-"""
+""")
try:
from setuptools import setup
params = {
- 'install_requires': [ 'pyasn1>=0.0.13', 'pycrypto' ],
+ 'install_requires': [ 'pyasn1>=0.0.14', 'pycrypto>=2.3' ],
'zip_safe': True
}
except ImportError:
for arg in sys.argv:
- if string.find(arg, 'egg') != -1:
+ if arg.find('egg') != -1:
howto_install_setuptools()
sys.exit(1)
from distutils.core import setup
- if sys.version_info > (2, 2):
- params = {
- 'requires': [ 'pyasn1(>=0.0.13)', 'pycrypto' ]
+ params = {
+ 'requires': [ 'pyasn1(>=0.0.14)', 'pycrypto(>=2.3)' ]
}
- else:
- params = {}
params.update( {
'name': 'pysnmp',
- 'version': '4.1.16d',
+ 'version': '4.2.1',
'description': 'SNMP framework',
'author': 'Ilya Etingof',
'author_email': 'ilya@glas.net',
'url': 'http://sourceforge.net/projects/pysnmp/',
+ 'classifiers': [
+ 'Development Status :: 5 - Production/Stable',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: Information Technology',
+ 'Intended Audience :: Telecommunications Industry',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 3',
+ 'Topic :: Security',
+ 'Topic :: Communications',
+ 'Topic :: System :: Monitoring',
+ 'Topic :: System :: Networking :: Monitoring',
+ 'Topic :: Software Development :: Libraries :: Python Modules',
+ 'License :: OSI Approved :: BSD License'
+ ],
'license': 'BSD',
'packages': [ 'pysnmp',
'pysnmp.smi',
@@ -66,5 +77,4 @@ params.update( {
'scripts': [ 'tools/libsmi2pysnmp', 'tools/build-pysnmp-mib' ]
} )
-apply(setup, (), params)
-
+setup(**params)
diff --git a/tools/libsmi2pysnmp b/tools/libsmi2pysnmp
index 6e6f55e..22b2dc7 100644
--- a/tools/libsmi2pysnmp
+++ b/tools/libsmi2pysnmp
@@ -1,15 +1,12 @@
#!/usr/bin/env python
# Walk libsmi-generated tree of MIB symbols and build pysnmp.smi
# compliant module
-from exceptions import StandardError
-from string import split, join, replace, find, atol, atoi
-from types import StringType, DictType
import sys, time
-version = '0.0.10-beta'
+version = '0.1.1'
genTextLoader = 1
-class Error(StandardError): pass
+class Error(Exception): pass
if len(sys.argv) > 1:
if sys.argv[1] == '--no-text':
@@ -42,10 +39,8 @@ g = {}
try:
eval(codeObj, g)
-except StandardError, why:
- raise Error(
- 'MIB module load error: %s' % why
- )
+except Exception:
+ raise Error('MIB module load error: %s' % (sys.exc_info[1],))
mib = g['MIB']
@@ -68,90 +63,70 @@ __symsTable = {
}
def symTrans(symbol):
- if __symsTable.has_key(symbol):
+ if symbol in __symsTable:
return __symsTable[symbol]
return symbol,
def transOpers(symbol):
- return replace(symbol, '-', '_')
+ return symbol.replace('-', '_')
def addLabelForSymbol(symbol):
- if find(symbol, '-') != -1:
+ if symbol.find('-') != -1:
return '.setLabel(\"%s\")' % symbol
return ''
-__oidToTuple = lambda x: str(tuple(map(lambda y: int(y), split(x, '.'))))
+__oidToTuple = lambda x: str(tuple([ int(y) for y in x.split('.') ]))
def __reprIntVal(value):
try:
- intVal = atoi(value)
+ return int(value)
except ValueError:
- try:
- intVal = atol(value)
- except ValueError:
- return repr(value)
- if -2147483647 < intVal < 2147483647:
- return repr(intVal)
- else:
- return repr(long(intVal))
+ return repr(value)
def __genDefVal(baseType, symDef):
if baseType == 'OctetString':
if symDef['default'][:2] == '0x':
- defVal = ''
- for i in range(2, len(symDef['default']), 2):
- defVal = defVal + chr(
- atoi(symDef['default'][i:i+2], 16)
- )
+ return '%s' % repr(symDef['default'][2:]), True
else:
- defVal = symDef['default']
- return '%s' % repr(defVal)
+ return '%s' % repr(symDef['default']), False
elif baseType == 'Integer':
- return '%s' % __reprIntVal(symDef['default'])
- elif baseType == 'Integer32':
- return '%s' % __reprIntVal(symDef['default'])
+ return '%s' % __reprIntVal(symDef['default']), False
+ elif baseType in ('Integer32', 'Unsigned32'):
+ return '%s' % __reprIntVal(symDef['default']), False
elif baseType == 'ObjectIdentifier':
- return '%s' % __oidToTuple(symDef['default'])
+ return '%s' % __oidToTuple(symDef['default']), False
elif baseType == 'IpAddress':
defVal = ''
for i in range(2, len(symDef['default']), 2):
if defVal: defVal = defVal + '.'
defVal = defVal + str(
- atoi(symDef['default'][i:i+2], 16)
+ int(symDef['default'][i:i+2], 16)
)
- return '\"%s\"' % defVal
+ return '\"%s\"' % defVal, False
elif baseType == 'Bits':
defVal = '('
- for bit in split(replace(
- replace(replace(symDef['default'], ',', ''), '(', ''), ')', ''
- )):
+ for bit in symDef['default'].replace(',', '').replace('(', '').replace(')', '').split():
defVal = defVal + '\"%s\",' % bit
defVal = defVal + ')'
- return defVal
+ return defVal, False
elif baseType == 'Enumeration':
- if symDef['syntax']['type'].has_key(symDef['default']):
+ if symDef['default'] in symDef['syntax']['type']:
return '%s' % \
- symDef['syntax']['type'][symDef['default']]['number']
+ symDef['syntax']['type'][symDef['default']]['number'], False
else:
- return '\"%s\"' % symDef['default']
+ return '\"%s\"' % symDef['default'], False
else:
sys.stderr.write('WARNING: guessing DEFVAL type \'%s\' for %s\n' %
(symDef['default'], baseType))
if symDef['default'][:2] == '0x':
- defVal = ''
- for i in range(2, len(symDef['default']), 2):
- defVal = defVal + chr(
- atoi(symDef['default'][i:i+2], 16)
- )
+ return '%s' % repr(symDef['default'][2:]), True
else:
defVal = symDef['default']
try:
- atol(defVal)
+ int(defVal)
except ValueError:
pass
- else:
- return defVal
- return '%s' % repr(defVal)
+ return '%s' % repr(defVal), False
# Ugly kludge against smidump bug which does not distinguish
# size/range constraints
@@ -163,29 +138,29 @@ __buggySmiTypes = {
'NetworkAddress': 'IpAddress' # this is up to smidump, but it does not care
}
-def __genTypeDef((symName, symDef), classMode=0):
+def __genTypeDef(symName, symDef, classMode=0):
r = ''
if classMode:
typeDef = symDef
identFiller = ' '; identValue = 0
else:
typeDef = symDef['syntax']['type']
- if typeDef.has_key('name'):
+ if 'name' in typeDef:
baseType = typeDef['name']
- if typeDef.has_key('basetype'):
+ if 'basetype' in typeDef:
baseType = typeDef['basetype']
- if typeDef.has_key('parent module'):
+ if 'parent module' in typeDef:
parentType = typeDef['parent module']['type']
else:
parentType = baseType
# Ugly hack to overcome smidump bug in smiv1->smiv2 convertion
- if __buggySmiTypes.has_key(baseType):
+ if baseType in __buggySmiTypes:
baseType = __buggySmiTypes[baseType]
- if __buggySmiTypes.has_key(parentType):
+ if parentType in __buggySmiTypes:
parentType = __buggySmiTypes[parentType]
if classMode:
r = r + 'class %s(' % symName
- if typeDef.has_key('format'):
+ if 'format' in typeDef:
r = r + '%s, ' % symTrans('TEXTUAL-CONVENTION')[0]
identValue = identValue + 1
if baseType in ('Enumeration', 'Bits'):
@@ -193,7 +168,8 @@ def __genTypeDef((symName, symDef), classMode=0):
parentType = 'Integer'
if classMode:
r = r + '%s):\n' % parentType
- r = r + identFiller*identValue
+ r = r + identFiller*identValue
+ _r = r
else:
r = r + ', %s()' % parentType
if baseType == 'Enumeration':
@@ -207,8 +183,8 @@ def __genTypeDef((symName, symDef), classMode=0):
r = r + 'constraint.SingleValueConstraint('
cnt = 1
for e, v in typeDef.items():
- if type(v) == DictType and v.has_key('nodetype') \
- and v['nodetype'] == 'namednumber':
+ if isinstance(v, dict) and 'nodetype' in v and \
+ v['nodetype'] == 'namednumber':
r = r + '%s,' % v['number']
if cnt % 127 == 0:
r = r + '), constraint.SingleValueConstraint('
@@ -224,12 +200,12 @@ def __genTypeDef((symName, symDef), classMode=0):
r = r + 'namedValues = namedval.NamedValues('
else:
r = r + '.subtype(namedValues=namedval.NamedValues('
- typedesc = typeDef.items()
- typedesc.sort(lambda x,y: cmp(x[1],y[1]))
+ typedesc = list(typeDef.items())
+ typedesc.sort(key=lambda x: str(x[1]))
cnt = 1
for e, v in typedesc:
- if type(v) == DictType and v.has_key('nodetype') \
- and v['nodetype'] == 'namednumber':
+ if isinstance(v, dict) and 'nodetype' in v and \
+ v['nodetype'] == 'namednumber':
r = r + '(\"%s\", %s), ' % (e, v['number'])
if cnt % 127 == 0:
r = r + ') + namedval.NamedValues('
@@ -243,24 +219,25 @@ def __genTypeDef((symName, symDef), classMode=0):
if classMode:
r = r + '%s):\n' % parentType
r = r + identFiller*identValue
+ _r = r
else:
r = r + ', %s()' % parentType
if classMode:
- if typeDef.has_key('format'):
+ if 'format' in typeDef:
r = r + 'displayHint = \"%s\"\n' % typeDef['format']
r = r + identFiller*identValue
- if __kludgyStringTypes.has_key(baseType):
+ if baseType in __kludgyStringTypes:
__subtypeSpec = 'constraint.ValueSizeConstraint'
else:
__subtypeSpec = 'constraint.ValueRangeConstraint'
single_range = 0
- if typeDef.has_key('range'):
+ if 'range' in typeDef:
single_range = 1
# ATTENTION: libsmi-0.4.5 does not support "ranges". Use libsmi
# SVN version or an older patch from Randy Couey:
# http://www.glas.net/~ilya/download/tools/pysnmp/libsmi-0.4.5-perl_python_range_union.patch
- if typeDef.has_key('ranges'):
+ if 'ranges' in typeDef:
# if more than one size/range is given, then we need to
# create a ContraintsUnion to hold all of them.
if len(typeDef['ranges']) > 1:
@@ -281,27 +258,33 @@ def __genTypeDef((symName, symDef), classMode=0):
if classMode:
r = r + 'subtypeSpec = %s.subtypeSpec+%s(%s,%s)\n' % (parentType, __subtypeSpec, __reprIntVal(typeDef['range']['min']), __reprIntVal(typeDef['range']['max']))
r = r + identFiller*identValue
- if __kludgyStringTypes.has_key(baseType) and \
+ if baseType in __kludgyStringTypes and \
typeDef['range']['min'] == typeDef['range']['max']:
r = r + 'fixedLength = %s\n' % typeDef['range']['min']
r = r + identFiller*identValue
else:
r = r + '.subtype(subtypeSpec=%s(%s, %s))' % (__subtypeSpec, __reprIntVal(typeDef['range']['min']), __reprIntVal(typeDef['range']['max']))
- if __kludgyStringTypes.has_key(baseType) and \
+ if baseType in __kludgyStringTypes and \
typeDef['range']['min'] == typeDef['range']['max']:
r = r + '.setFixedLength(%s)' % typeDef['range']['min']
- if symDef.has_key('default') and not symDef.has_key('basetype'):
- defVal = __genDefVal(baseType, symDef)
- if classMode:
- if defVal is not None:
- r = r + 'defaultValue = %s\n' % defVal
- else:
- if defVal is not None:
- r = r + '.clone(%s)' % defVal
+ if 'default' in symDef and 'basetype' not in symDef:
+ defVal, inHex = __genDefVal(baseType, symDef)
+ if defVal is not None:
+ if classMode:
+ if inHex:
+ r = r + 'defaultHexValue = %s\n' % defVal
+ else:
+ r = r + 'defaultValue = %s\n' % defVal
+ else:
+ if inHex:
+ r = r + '.clone(hexValue=%s)' % defVal
+ else:
+ r = r + '.clone(%s)' % defVal
if classMode:
- r = r + 'pass\n\n'
-
+ if r == _r:
+ r = r + 'pass\n'
+ r = r + '\n'
return r
out.write(
@@ -327,14 +310,15 @@ for imp in (
{ 'module': 'SNMPv2-SMI', 'name': 'TimeTicks' }, # bug in some IETF MIB
{ 'module': 'SNMPv2-SMI', 'name': 'MibIdentifier' }, # OBJECT IDENTIFIER
) + mib.get('imports', ()):
- if not imports.has_key(imp['module']):
+ if imp['module'] not in imports:
imports[imp['module']] = []
if not imp['module']:
sys.stderr.write('WARNING: empty MIB module name seen in smidump output at %s\n' % dstModName)
imports[imp['module']].append(imp['name'])
-map(lambda x:x.sort(), imports.values())
-modNames = imports.keys(); modNames.sort()
+[ x.sort() for x in imports.values() ]
+
+modNames = list(imports.keys()); modNames.sort()
for modName in modNames:
out.write('( ')
for symName in imports[modName]:
@@ -346,27 +330,24 @@ for modName in modNames:
out.write(', \"%s\"' % s)
out.write(')\n')
-if mib.has_key('typedefs'):
- typedefs = mib['typedefs'].items(); typedefs.sort()
+if 'typedefs' in mib:
+ typedefs = list(mib['typedefs'].items()); typedefs.sort()
else:
typedefs = ()
if typedefs:
out.write('\n# Types\n\n')
for symName, symDef in typedefs:
- out.write('%s' % __genTypeDef((symName, symDef), 1))
+ out.write('%s' % __genTypeDef(symName, symDef, 1))
-if mib.has_key(dstModName) and mib[dstModName].has_key('identity node'):
+if dstModName in mib and 'identity node' in mib[dstModName]:
moduleIdentityNode = mib[dstModName]['identity node']
else:
moduleIdentityNode = ''
-if mib.has_key('nodes'):
- nodes = mib['nodes'].items()
- __oid2num = lambda o: map(lambda x: atol(x), split(o, '.'))
- nodes.sort(lambda x,y,f=__oid2num: cmp(
- f(x[1].get('oid')), f(y[1].get('oid'))
- ))
+if 'nodes' in mib:
+ nodes = list(mib['nodes'].items())
+ nodes.sort(key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ])
else:
nodes = ()
@@ -378,33 +359,33 @@ if nodes:
out.write('%s = ' % transOpers(symName))
if symName == moduleIdentityNode:
out.write('ModuleIdentity(%s)' % __oidToTuple(symDef['oid']))
- if mib.has_key(dstModName):
+ if dstModName in mib:
m = mib[dstModName]
- if m.has_key("revisions"):
+ if 'revisions' in m:
out.write('.setRevisions((')
for r in m["revisions"]:
out.write('\"%s\",' % r["date"])
out.write('))')
out.write('%s' % addLabelForSymbol(symName))
if genTextLoader:
- if m.has_key('organization'):
- out.write('\nif mibBuilder.loadTexts: %s.setOrganization("%s")' % (transOpers(symName), replace(m['organization'], '\n', '\\n')))
- if m.has_key('contact'):
- out.write('\nif mibBuilder.loadTexts: %s.setContactInfo("%s")' % (transOpers(symName), replace(m['contact'], '\n', '\\n')))
- if m.has_key('description'):
- out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), replace(m['description'], '\n', '\\n')))
+ if 'organization' in m:
+ out.write('\nif mibBuilder.loadTexts: %s.setOrganization("%s")' % (transOpers(symName), m['organization'].replace('\n', '\\n')))
+ if 'contact' in m:
+ out.write('\nif mibBuilder.loadTexts: %s.setContactInfo("%s")' % (transOpers(symName), m['contact'].replace('\n', '\\n')))
+ if 'description' in m:
+ out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), m['description'].replace('\n', '\\n')))
out.write('\n')
continue
- elif symDef.has_key("description"):
+ elif 'description' in symDef:
out.write('ObjectIdentity(%s)' % __oidToTuple(symDef['oid']))
else:
out.write('MibIdentifier(%s)' % __oidToTuple(symDef['oid']))
elif symDef['nodetype'] == 'scalar':
out.write('%s = ' % transOpers(symName))
out.write('MibScalar(%s' % __oidToTuple(symDef['oid']))
- out.write('%s)' % __genTypeDef((symName, symDef)))
+ out.write('%s)' % __genTypeDef(symName, symDef))
out.write('.setMaxAccess(\"%s\")' % symDef['access'])
- if symDef.has_key('units'):
+ if 'units' in symDef:
out.write('.setUnits(\"%s\")' % symDef['units'])
elif symDef['nodetype'] == 'table':
out.write('%s = ' % transOpers(symName))
@@ -413,12 +394,12 @@ if nodes:
out.write('%s = ' % transOpers(symName))
# determine if row creation is permitted, and store
# status for later inspection by column nodes.
- if symDef.has_key('create'):
+ if 'create' in symDef:
row_create[symDef['oid']] = symDef['create']
else:
row_create[symDef['oid']] = 'false'
out.write('MibTableRow(%s)' % __oidToTuple(symDef['oid']))
- if symDef['linkage'] and type(symDef['linkage'][0]) == StringType:
+ if symDef['linkage'] and isinstance(symDef['linkage'][0], str):
out.write('.setIndexNames(')
cnt = 0
for idx in symDef['linkage']:
@@ -438,8 +419,8 @@ if nodes:
else:
modName = dstModName
if idx == symDef['linkage'][-1] and \
- symDef.has_key("implied") and \
- symDef["implied"] == "true":
+ 'implied' in symDef and \
+ symDef['implied'] == 'true':
impliedFlag = 1
else:
impliedFlag = 0
@@ -451,11 +432,11 @@ if nodes:
elif symDef['nodetype'] == 'column':
out.write('%s = ' % transOpers(symName))
out.write('MibTableColumn(%s' % __oidToTuple(symDef['oid']))
- out.write('%s)' % __genTypeDef((symName, symDef)))
+ out.write('%s)' % __genTypeDef(symName, symDef))
# smidump does not tag columns as read-create.
# we must check the parent row object to determine if column is
# createable
- parent = join(split(symDef['oid'], '.')[:-1], '.')
+ parent = '.'.join(symDef['oid'].split('.')[:-1])
if row_create[parent] == 'true' and symDef['access']=='readwrite':
out.write('.setMaxAccess(\"%s\")' % 'readcreate')
else:
@@ -470,15 +451,15 @@ if nodes:
out.write('%s' % addLabelForSymbol(symName))
if genTextLoader:
- if symDef.has_key("description"):
- out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), replace(symDef['description'], '\n', '\\n')))
+ if 'description' in symDef:
+ out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n')))
out.write('\n')
out.write('\n# Augmentions\n')
for symName, symDef in mib['nodes'].items():
if symDef['nodetype'] == 'row':
- if symDef['linkage'] and type(symDef['linkage'][0]) == DictType:
+ if symDef['linkage'] and isinstance(symDef['linkage'][0], dict):
for idx in symDef['linkage']:
for m, indices in idx.items():
if m != dstModName:
@@ -491,17 +472,15 @@ if nodes:
'%s.registerAugmentions((\"%s\", \"%s\"))\n' % (
indices['relatedNode'], dstModName, symName
))
- out.write(
- 'apply(%s.setIndexNames, %s.getIndexNames())\n' % (
+ out.write('%s.setIndexNames(*%s.getIndexNames())\n' % (
symName, transOpers(indices['relatedNode'])
))
-if mib.has_key('notifications'):
- notifications = mib['notifications'].items()
- __oid2num = lambda o: map(lambda x: atol(x), split(o, '.'))
- notifications.sort(lambda x,y,f=__oid2num: cmp(
- f(x[1].get('oid')), f(y[1].get('oid'))
- ))
+if 'notifications' in mib:
+ notifications = list(mib['notifications'].items())
+ notifications.sort(
+ key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ]
+ )
else:
notifications = ()
@@ -517,16 +496,13 @@ if notifications:
out.write(')')
out.write('%s' % addLabelForSymbol(symName))
if genTextLoader:
- if symDef.has_key("description"):
- out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), replace(symDef['description'], '\n', '\\n')))
+ if 'description' in symDef:
+ out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n')))
out.write('\n')
-if mib.has_key('groups'):
- groups = mib['groups'].items()
- __oid2num = lambda o: map(lambda x: atol(x), split(o, '.'))
- groups.sort(lambda x,y,f=__oid2num: cmp(
- f(x[1].get('oid')), f(y[1].get('oid'))
- ))
+if 'groups' in mib:
+ groups = list(mib['groups'].items())
+ groups.sort(key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ])
else:
groups = ()
@@ -535,7 +511,7 @@ if groups:
for symName, symDef in groups:
out.write('%s = ' % transOpers(symName))
if symDef['nodetype'] == 'group':
- if find(symName, 'otification') < 0: # hackerish
+ if symName.find('otification') < 0: # hackerish
out.write('ObjectGroup(')
else:
out.write('NotificationGroup(')
@@ -546,16 +522,15 @@ if groups:
out.write(')')
out.write('%s' % addLabelForSymbol(symName))
if genTextLoader:
- if symDef.has_key("description"):
- out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), replace(symDef['description'], '\n', '\\n')))
+ if 'description' in symDef:
+ out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n')))
out.write('\n')
-if mib.has_key('compliances'):
- compliances = mib['compliances'].items()
- __oid2num = lambda o: map(lambda x: atol(x), split(o, '.'))
- compliances.sort(lambda x,y,f=__oid2num: cmp(
- f(x[1].get('oid')), f(y[1].get('oid'))
- ))
+if 'compliances' in mib:
+ compliances = list(mib['compliances'].items())
+ compliances.sort(
+ key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ]
+ )
else:
compliances = ()
@@ -566,7 +541,7 @@ if compliances:
if symDef['nodetype'] == 'compliance':
out.write('ModuleCompliance(')
out.write('%s)' % __oidToTuple(symDef['oid']))
- if symDef.has_key('requires'):
+ if 'requires' in symDef:
out.write('.setObjects(')
for objName, objDef in symDef['requires'].items():
# XXX nodetype not stored
@@ -575,8 +550,8 @@ if compliances:
# XXX refinements not stored
out.write('%s' % addLabelForSymbol(symName))
if genTextLoader:
- if symDef.has_key("description"):
- out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), replace(symDef['description'], '\n', '\\n')))
+ if 'description' in symDef:
+ out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n')))
out.write('\n')
out.write('\n# Exports\n\n')
@@ -590,7 +565,7 @@ if moduleIdentityNode:
if typedefs:
out.write('# Types\n')
out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName)
- idx = 1L
+ idx = 1
for symName, symObj in typedefs:
if idx % 127 == 0:
out.write(')\n')
@@ -602,7 +577,7 @@ if typedefs:
if nodes:
out.write('# Objects\n')
out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName)
- idx = 1L
+ idx = 1
for symName, symObj in nodes:
if idx % 127 == 0:
out.write(')\n')
@@ -614,7 +589,7 @@ if nodes:
if notifications:
out.write('# Notifications\n')
out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName)
- idx = 1L
+ idx = 1
for symName, symObj in notifications:
if idx % 127 == 0:
out.write(')\n')
@@ -626,7 +601,7 @@ if notifications:
if groups:
out.write('# Groups\n')
out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName)
- idx = 1L
+ idx = 1
for symName, symObj in groups:
if idx % 127 == 0:
out.write(')\n')
@@ -638,7 +613,7 @@ if groups:
if compliances:
out.write('# Compliances\n')
out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName)
- idx = 1L
+ idx = 1
for symName, symObj in compliances:
if idx % 127 == 0:
out.write(')\n')