diff -Nru python-pysnmp4-4.1.9a/CHANGES python-pysnmp4-4.2.2/CHANGES --- python-pysnmp4-4.1.9a/CHANGES 2007-11-26 12:29:48.000000000 +0000 +++ python-pysnmp4-4.2.2/CHANGES 2012-04-20 19:33:11.000000000 +0000 @@ -1,3 +1,310 @@ +Revision 4.2.2 +-------------- + +- Oneliner CommandGenerator can now limit the number of SNMP table + rows returned by nextCmd()/bulkCmd() methods. +- Oneliner CommunityData configuration object can now be initialized + with community name only, security name will be chosen automatically. +- Oneliner LCD configuration routines reworked towards clarity. The + side-effect of this change is that repetitive oneliner call with the same + securityName and different configuration options will only honor + the first settings. Previous implementation would override older settings. +- Transport dispatcher now provides its own time expressed in + fractions of second. SNMP engine uses this notion of time for + handling requests timeout to make packet flow time bound + to async I/O core operations rather than to real time. +- The libsmi2pysnmp tool improved to handle incomplete SMI v1->v2 + conversion performed by smidump. The remaining core SMIv1 modules + excluded from the core MIB set. +- The pyasn1 constraint and enumeration objects put into ASN1-* + MIB modules what appears to be more in-line with SMI. Existing + MIB modules as well as libsmi2pysnmp tool corrected accordingly. +- The MibBuilder.importSymbols() now takes optional kwargs and + push them into MIB modules globals(). This is to facilitate + passing user infomation, such as DB connection handler, to MIB + module namespace so it could be used by ManagedObjects implementations. +- When running on Python3, SMI will re-raise exceptions with the original + traceback for easier diagnostics. +- Out of PYTHONPATH MIB paths now supported. +- Added pyasn1 decoder failures diagnistics in debug mode. +- Fix to non-MT-safe class attributes at SNMPv3 MP & SEC modules. +- Fix to ContextName handling in bytes form whilst running Python3. Data + mismatch error would return otherwise. +- Fix to SNMPv3 MP peer engine ID discovery not to learn and use + user-specified ContextEngineId. +- Fix to socket.error processing at Py3 on Windows. +- Fix to oneliner GETNEXT/GETBULK implementation to properly support + ignoreNonIncreasingOIDs option. +- Fix to setEndOfMibError()/setNoSuchInstanceError() at v1 PDU not to + loose errorIndex. +- Fix to api.v2c.getVarBindTable() to ignore possible non-rectangular GETBULK + response tables. +- Fix to oneliner getnext/getbulk response table rectangulation procedure + to gracefully handle an empty column condition. +- Fix to legacy MibBuilder.getMibPath() to prevent it from missing + .egg-based components in path. +- Fix to oneliner configuration routine that used to implicitly + tag SNMPv1/v2c auth and transport LCD rows what resulted in + huge delays when processing incoming messages with large number + of peers configured. +- Fix to UDP6 transport handling at rfc2576 security module. +- Fix to SnmpEngineID value autogeneration (used to fail on Mac). +- SNMPv2-SMI.ObjectType.__repr__() fixed to do a repr() on its components. +- All SNMPv2-SMI.MibNode-based objects, once exported to a mibBuilder, will + carry an embedded label symbol. +- Exlicit repr() calls replaced with '%r' +- Fix to error processing at GETNEXT & GETBULK apps response handlers. +- Fix to libsmi2pysnmp to make it supporting long (256+) list of function + params. +- Fix to libsmi2pysnmp to support inheritance of MIB types. + +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 +---------------- + +- Fix to SNMPv1 Trap PDU agentAddress setter shortcut method. + +Revision 4.1.16c +---------------- + +- Missing module import fixed in privacy subsystem + +Revision 4.1.16b +---------------- + +- Oneliner CommandGenerator can now optionally ignore non-increasing OIDs. +- Default CommandResponder now skips non-compliant (Counter64) values + when responding to a v1 Manager. +- Fix to state information handling at CommandResponder app. +- Fix to Twisted reactor shutdown condition. +- Fix to distutils dependencies syntax. + +Revision 4.1.16a +---------------- + +- Extended Security Options (3DESEDE, AES192, AES256) privacy + protocols implemented. +- The error-indication codes moved from literals to objects for reliability + and clarity +- Fix to v1.TrapPDUAPI.getVarBinds() to address PDU component at the right + position. +- Fix to rfc1902.Bits initialization from named bits sequence. +- Fix to MIB builder by-extension module filtering code to cope with .pyw + files. +- Internal caches structure improved. +- Sync versions of oneliner apps split off async implementation for clarity. +- Randomize initial in various numeric sequences. +- MsgAndPduDsp expectResponse parameters passing reworked. +- GetNext/GetBulk response processing logic moved to getNextVarBinds() +- Changes towards performance improvement: + + all dict.has_key() & dict.get() invocations replaced with modern syntax + (this breaks compatibility with Python 2.1 and older). + + introduce the MibInstrumControlle.readVarsFast() method (which skips + the "testing" phase of MIB value readin) for dealing with internal + configuration (LCD). + + default debug.logger is now just a zero value instead of an object + what saves big on frequent calls + + SNMPv2-SMI columnar indices <-> index values convertion code optimized. + + pre-compute and re-use some of ASN.1 structures. + + avoid setting PDU defaults to save on unnecessary initialization. + + skip ASN.1 types verification where possible. + + at oneliner Command Generator, avoid looking up pure OID arguments + at MIB as it's pointless but takes time. + + cache MIB columnar objects instance ID <-> symbolic index representation + mapping + +Revision 4.1.15a +---------------- + +- SNMP Proxy example added. +- End-of-MIB condition detection reworked what caused backward + incompatibility at v1arch GETNEXT API. Previous pysnmp versions + used value = None in var-binds as returned by getVarBindTable() + API method. This version uses rfc1905 exception values (v2c/v3) + or pyasn1 Null (v1). + Built-in GETNEXT/GETBULK apps now do not require user to track + end-of-mib conditions anymore -- this is now done automatically. +- CommandResponder API now supports async mode of operation. +- SNMP exception values now exported from rfc1905 module, and made + pretty printable. +- Lexicographic walking mode is now supported at oneliner CommandGenerator. +- ContextEngineId&ContextName parameters passing implemented at + v3arch oneliner API. +- Multiple instances of the same transport domain now supported. +- Initial snmpEngineId value generation improved not to accidentally + collide within an administrative domain. +- MibTableColumn instances now build value-to-column-instance map + to speedup by-value search. +- SNMPv2-CONF::AgentCapabilities macro implemented. +- The libsmi2pysnmp tool handles some more MACROs. +- Void access control module implemented to let apps disabling [default] VACM. +- Allow standard SNMP apps to choose access control method to use. +- Twisted-based CommandResponder example added. +- Fix/rework of Twisted GETNEXT/BULK CommandGenerator callback API to + make it simpler and uniform with other CommandGenerators +- Fix to SNMPv3 security module to store peer SNMP engine timeline + only if taken from an authenticated message. Prior to this fix + SNMP engine was not been protected from spoofing. +- Fix to $SMIPATH initialization at build-pysnmp-mib. +- Fix to maxSizeResponseScopedPDU calculation. +- Fix to Next/Bulk CommandGenerators to catch a non-increasing OID + error condition (what prevents looping). +- Fix to Opaque value tagging at rfc1155.Opaque type. +- Fix to handle (fail gracefully) zero-length user password. +- Fix to SNMP error propagation at Twisted driver (SF tracker ID #3054505). +- Fix to Agent-role snmpEngineId discovery procedure that allows + authenticated ReportPDU generation. +- Fix to SNMPv1 PDU handling at CommandResponder & NotificationReceiver + apps. +- Fix to CommandResponder app to skip Counter64 SMI values when responding + to SNMPv1 Manager. +- Fix to protocol translator code (rfc2576) to handle Counter64 type + in v2c-to-v1 PDU translation. +- Fix to non-response var-binds translation in rfc2576.v2ToV1(). +- Fix to wrong exceptions used in pysnmp/entity modules. +- Fix to noauth/nopriv security module so that it would not crash SNMP + engine if called accidentally. +- Fix to CommandResponder not to return out-of-range errorIndex along + with genErr +- Fix to GETBULK CommandResponder to do a by-column MIB walk, not by-raw. +- Fix to getVarBindTable() API function logic. +- Fix to example Manager scripts to use errorIndex when available. +- Fix to dummy encryptData()/decryptData() API +- Fix to oneliner GETBULK table collection code to make it stripping + uneven rows off table tail. + +Revision 4.1.14a +---------------- + +- Fix to maxSizeResponseScopedPDU calculation at USM security module: now + more precise and robust against screwed values on input. +- Fix to MIB loading logic that used to load same-name modules at + disticts search paths on each loadModules() call. +- Fix to AsynsockDispatcher.runDispatcher() to make use of optional + non-default select() timeout value. +- AbstractTransportDispatcher now allows user application registering + multiple timer callbacks each with dedicated call period. +- Asynsock mainloop default idle period reduced to 0.5 sec for better + timer resolution. +- Fix to SNMPv1->SNMPv2c error status handling at proxy module. This + defect may have caused an infinite loop on a multiple var-bind + SNMPv1 GetNext operation. +- Fix to contextName processing at config.addV1System -- typo rendered + passed contextName not committed into LCD. +- Fix to unknown ContextName exception handling at CommandResponder App. +- config.addVacmUser() now accepts an optional contextName what makes + it usable for configuring multiple contextName-bound bases of Managed + Objects to SnmpEngine. +- MP pending states cache management re-worked so that SNMP engine will + now handle an unlimited number of pending request/responses. +- Fix to SNMP discovery procedure: include ContentName in SNMP discovery + messaging. +- Many fixes to AES crypto code that makes it actually working. +- Fix to SNMPv2-SMI createUndo operations. +- Fix to INFORM sending error handling at oneliner. +- Fix to mismatched response PDU handling at CommandGenerator application. +- Debug category 'app' (for Application) added to facilitate + Standard SNMP Applications debugging. +- The retryCount semantic of CommandGenerator application changed to include + sole retries and do not include initial request. Thus, retryCount=1 will + now send up to two packets, not just one as it used to be. +- Debugging printout now escapes non-printable characters. + +Revision 4.1.13a +---------------- + +- UDP over IPv6 transport implemented. +- Fix to MIB tree walking code that used to fail on table columns where + indices have identical leading parts. +- SNMPv1/v2c snmpCommunityTransportTag-based imcoming message filtering + implemented (rfc2576). + +Revision 4.1.12a +---------------- + +- API versioning retired (pysnmp.v4 -> pysnmp). +- MIB loading mechanics re-designed to allow ZIP import. +- MIB loader supports code objects (py[co]) +- Installer now uses setuptools for package management whenever available. +- The libsmi2pysnmp tool improved to build constraints of more than + 256 items (Python has a limit on the number of function params). +- Missing SNMPTrap PDU API implemented at proto.api.v2c, RFC2576 proxy + code reworked. +- Fix to sysUpTime OID at SNMPv2 TRAP PDU. + +Revision 4.1.11a +---------------- + +- Twisted integration implemented. +- Attempt to use hashlib whenever available. +- Fix to oneliner Manager code on < Python 2.4. +- Let NotificationReceiver and CommandResponder Apps browsing request details + (transport information at the moment) at SNMP engine. +- Fix to config.addV1System() to allow multiple systems to co-exist in LCD. +- Fix to wrongly succeeding user-parameters-by-community-name searching code + in rfc2576 processIncomingMsg() method. +- Do sanity checking on PYSNMP_MODULE_ID, Groups and Notifications in + libsmi2pysnmp (SF bug #2122489). +- Fix to oneliner Notification Originator that sometimes used to send multiple + requests at once. +- Oneliners LCD names generation code reworked to avoid accidental clashes. +- Fix and re-work of sysUpTime value management in LCD. +- Fix to pending inform request data caching in mpmod/rfc2576.py -- previous + code led to cache data corruption on multple outstanding requests. +- In SMI configuration wrapper functions, catch access to non-configured + entries and raise an exception. +- Allow multuple callback timer functions in all transport dispatchers. +- Fix to libsmi2pysnmp code to preserve more underscored object names and + to guess the right type between indistinguishable ObjectGroup & + NotificationGroup +- Fix to MibScalarInstance value setting logic - previous code failed + when modifying the same OID multiple times within a single SET operation. +- Minor usability improvements to tools/build-pysnmp-mib. +- Made MIB objects unexport feature operational. + +Revision 4.1.10a +---------------- + +- Internal MIB indexing method __indexMib() unmangled to facilitate + setting up mutex there for sharing MIB stuff between threads. +- Fixed broken IpAddress value handling in SET operation. +- Broken MibBuilder.unloadModules() method now works. +- Use getLabel() SMI object method when building MIB tree (in builder.py) + in addition to direct attribute access for clearer object protocol. +- The MIB building tools updated to match significantly improved + smidump tool (libsmi version > 0.4.5). +- Made libsmi2pysnmp tool optionally building MIB text fields into pysnmp + MIB code (enabled by default) and MibBuilder conditionally loading them + up (disabled by default). +- SnmpEngine and MsgAndPduDispatcher constructors now optionally + take msgAndPduDspr and mibInstrumController class instances + respectively to facilitate these objects sharing within a process. +- Unique integers, for various parts of the system, are now generated + by a nextid.py module. This fixes possible issues with duplicate + request IDs and handlers. +- Built-in MIBs re-generated to include text fields. + Revision 4.1.9a --------------- @@ -53,11 +360,11 @@ to make sure these automatic entries won't interfere or exceed constraints on keys values. - Made use of notificationType parameter of the sendNotification method - in NotificationGenerator applications. This parameter used to be + in NotificationOriginator applications. This parameter used to be ignored in the past. Note, that previously used (and ignored) syntax has been changed in an incompatible way. - Allow plain Python values in setCmd() and sendNotification() - methods in CommandGenerator and NotificationGenerator applications + methods in CommandGenerator and NotificationOriginator applications respectively. - Multi-target oneliner API-based example script added. - Ignore more socket errors in datagram-type async socket code. diff -Nru python-pysnmp4-4.1.9a/debian/changelog python-pysnmp4-4.2.2/debian/changelog --- python-pysnmp4-4.1.9a/debian/changelog 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/changelog 2012-05-21 10:28:55.000000000 +0000 @@ -1,9 +1,39 @@ -python-pysnmp4 (4.1.9a-2ubuntu1) natty; urgency=low +python-pysnmp4 (4.2.2-1) unstable; urgency=low - * Merge from Debian unstable. (LP: #703445) Remaining changes: - - fix the python Deprecation Warnings for md5 and sha + * Team upload. + + [ Deepak Tripathi ] + * Bumped Standard version to 3.8.4 (No changes). + * debian/control + + added myself to uploaders. + + added ${misc:Depends} because debhelper required now. + + removed python-dev and added python. + + added python-twisted as Depends. + + added python-setuptools as BD. + * debian/copyright + + added debian's copyright information. + + formated and updated copy information. + * debian/ + + added python-pysnmp4-doc.doc-base because package has some + html,pdf files. + * debian/source + + switch to dpkg-source 3.0 (quilt) format. + * debian/libsmi2pysnmp.1 + + removed hyphen-used-as-minus-sign. + + [ Arnaud Fontaine ] + * New upstream release. Closes: #620229, #585321. + + API versioning has been retired since 4.1.12a and pysnmp version 2 + is not supported nor available anymore, so drop python-pysnmp-common. + * debian/control: + + Remove myself from Maintainer as Jan Lübbe is now the maintainer. + + Bump Standards-Version to 3.9.3. No changes needed. + * Switch from deprecated python-support to dh_python2. + * Switch debian/copyright to machine-readable format. + * Add debian/source/options to fix double build issue because of + .egg-info by ignoring it. - -- Micah Gersten Sat, 15 Jan 2011 19:56:12 -0600 + -- Arnaud Fontaine Mon, 21 May 2012 15:07:04 +0900 python-pysnmp4 (4.1.9a-2) unstable; urgency=medium @@ -21,28 +51,6 @@ -- Jakub Wilk Wed, 12 Jan 2011 00:11:54 +0100 -python-pysnmp4 (4.1.9a-1ubuntu2) maverick; urgency=low - - * debian/rules: - + move the __init__.py removal to the binary-post-install target - as it needs to be done after pyshared is populated which is now - after binary-install (LP: #610570, #612317) - - -- Fabien Tassin Wed, 04 Aug 2010 20:08:12 +0200 - -python-pysnmp4 (4.1.9a-1ubuntu1) maverick; urgency=low - - * debian/control, debian/rules: - + add quilt so we have a patch system - * debian/patches/01-fix-py-deprecation-warnings.patch, - debian/patches/series - + fix the python Deprecation Warnings for md5 and sha (LP: #610570) - * debian/rules: - + remove $(cdbs_python_support_path), it's no longer defined (since cdbs - 0.4.56) and makes the package uninstallable because of duplicated files - - -- Fabien Tassin Mon, 26 Jul 2010 08:10:47 +0200 - python-pysnmp4 (4.1.9a-1) unstable; urgency=low [ Arnaud Fontaine ] @@ -92,7 +100,7 @@ - Add DEB_PYTHON_SYSTEM=pysupport. - Clean debian/rules. + debian/control.in - - Clean Build-Depends and Depends, cdbs handles that + - Clean Build-Depends and Depends, cdbs handles that automatically now. - XB-Python-Version and Provides for binary package. + debian/postinst && debian/prerm: @@ -105,4 +113,3 @@ * Initial release. Closes: #263417. -- Jan Luebbe Thu, 1 Jun 2006 16:39:10 +0200 - diff -Nru python-pysnmp4-4.1.9a/debian/control python-pysnmp4-4.2.2/debian/control --- python-pysnmp4-4.1.9a/debian/control 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/control 2012-05-21 10:23:29.000000000 +0000 @@ -1,17 +1,18 @@ Source: python-pysnmp4 Section: python Priority: optional -Maintainer: Ubuntu Developers -XSBC-Original-Maintainer: Arnaud Fontaine -Uploaders: Jan Luebbe , Debian Python Modules Team -Standards-Version: 3.7.3 +Maintainer: Jan Lübbe +Uploaders: Debian Python Modules Team , + Deepak Tripathi +Standards-Version: 3.9.3 Build-Depends: debhelper (>= 5.0.37.2), - cdbs (>= 0.4.42), - python-dev (>= 2.3.5-7), - python-support (>= 0.3) + cdbs (>= 0.4.90~), + python-all (>= 2.6.6-3~), + python-setuptools Homepage: http://pysnmp.sourceforge.net/ -Vcs-Svn: svn://svn.debian.org/python-modules/packages/python-pysnmp4/branches/4.1.9a/ -Vcs-Browser: http://svn.debian.org/viewsvn/python-modules/packages/python-pysnmp4/branches/4.1.9a/ +X-Python-Version: >= 2.4 +Vcs-Svn: svn://svn.debian.org/python-modules/packages/python-pysnmp4/trunk/ +Vcs-Browser: http://svn.debian.org/viewsvn/python-modules/packages/python-pysnmp4/trunk/ Package: python-pysnmp4 Architecture: all @@ -19,9 +20,18 @@ libsmi2ldbl, libsmi2-common, python-pyasn1, - python-pysnmp-common (>= 4.1.9a-2~) -Recommends: python-crypto, python-pysnmp4-mibs, python-pysnmp4-apps -Suggests: python-pysnmp4-doc + ${misc:Depends} +Recommends: python-crypto, + python-pysnmp4-mibs, + python-pysnmp4-apps, + python-twisted +Suggests: python-pysnmp4-doc, doc-base +Conflicts: python-pysnmp2, + python-pysnmp-common +Replaces: python-pysnmp2, + python-pysnmp-common +Provides: python-pysnmp2, + python-pysnmp-common Description: Python SNMP library for agents and managers (unstable branch) This is a Python implementation of SNMP v.1/v.2c/v.3 engine. Its general functionality is to assemble/disassemble SNMP messages @@ -36,6 +46,7 @@ Package: python-pysnmp4-doc Section: doc Architecture: all +Depends: ${misc:Depends} Description: Python SNMP library for agents and managers (unstable branch) This is a Python implementation of SNMP v.1/v.2c/v.3 engine. Its general functionality is to assemble/disassemble SNMP messages @@ -48,23 +59,3 @@ PySNMP 4.x is the unstable branch. . This package contains the documentation for PySNMP. - -Package: python-pysnmp-common -Architecture: all -Depends: ${python:Depends} -Breaks: python-pysnmp2 (<< 2.0.9-3~), python-pysnmp4 (<< 4.1.9a-2~) -Replaces: python-pysnmp2 (<< 2.0.9-3~) -Recommends: python-pysnmp4 -XB-Python-Version: ${python:Versions} -Description: Python SNMP library for agents and managers (version selection module) - This is a Python implementation of SNMP v.1/v.2c/v.3 engine (SNMP v.3 - is only supported by pysnmp4). Its general functionality is to - assemble/disassemble SNMP messages from/into given SNMP Object IDs - along with associated values. PySNMP also provides a few transport - methods specific to TCP/IP networking. - . - PySNMP is written entirely in Python and is self-sufficient in terms - that it does not rely on any third party tool (it isn't a wrapper). - . - This package contains a Python module that allows users of PySNMP to - select the API version. diff -Nru python-pysnmp4-4.1.9a/debian/copyright python-pysnmp4-4.2.2/debian/copyright --- python-pysnmp4-4.1.9a/debian/copyright 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/copyright 2012-05-21 12:08:45.000000000 +0000 @@ -1,41 +1,62 @@ -This package was debianized by Arnaud Fontaine on -Fri, 21 Apr 2006 08:07:03 +0200. - -It was downloaded from http://pysnmp.sourceforge.net/download.html - -Author: Ilya Etingof - -Copyright: 1999-2006, Ilya Etingof , all rights reserved. - - THIS SOFTWARE IS NOT FAULT TOLERANT AND SHOULD NOT BE USED IN ANY - SITUATION ENDANGERING HUMAN LIFE OR PROPERTY. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - * The name of the authors may not be used to endorse or promote - products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - OF THE POSSIBILITY OF SUCH DAMAGE. +Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: pysnmp +Upstream-Contact: Ilya Etingof +Source: http://pysnmp.sourceforge.net/download.html + +Files: * +Copyright: 1999-2012, Ilya Etingof , all rights reserved. +License: BSD-3-clause + THIS SOFTWARE IS NOT FAULT TOLERANT AND SHOULD NOT BE USED IN ANY SITUATION + ENDANGERING HUMAN LIFE OR PROPERTY. + . + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + . + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + . + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + . + * The name of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + . + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Files: pysnmp/carrier/twisted/dispatch.py + pysnmp/carrier/twisted/base.py +Copyright: 2008 Truelite Srl +License: GPL-2 + +Files: debian/* +Copyright: 2006-2012 Jan Lübbe + 2006-2012 Arnaud Fontaine + 2010-2012 Deepak Tripathi +License: GPL-2 + +License: GPL-2 + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License as published by the Free Software + Foundation, version 2 of the License. + . + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + details. + . + You should have received a copy of the GNU General Public License along with + this package; if not, write to the Free Software Foundation, Inc., 51 + Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + . + On Debian systems, the full text of the GNU General Public License version 2 + can be found in the file `/usr/share/common-licenses/GPL-2'. diff -Nru python-pysnmp4-4.1.9a/debian/libsmi2pysnmp.1 python-pysnmp4-4.2.2/debian/libsmi2pysnmp.1 --- python-pysnmp4-4.1.9a/debian/libsmi2pysnmp.1 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/libsmi2pysnmp.1 2012-05-21 06:48:30.000000000 +0000 @@ -8,7 +8,7 @@ .SH "DESCRIPTION" .LP libsmi2pysnmp is used to convert MIB definitions to a form usable by PySNMP. To convert a single MIB use it like this: -smidump -f python | libsmi2pysnmp > +smidump \-f python | libsmi2pysnmp > .SH "AUTHORS" .LP Ilya Etingof diff -Nru python-pysnmp4-4.1.9a/debian/patches/fix-libsmi2pysnmp-with-python-less-than-2.7.patch python-pysnmp4-4.2.2/debian/patches/fix-libsmi2pysnmp-with-python-less-than-2.7.patch --- python-pysnmp4-4.1.9a/debian/patches/fix-libsmi2pysnmp-with-python-less-than-2.7.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/patches/fix-libsmi2pysnmp-with-python-less-than-2.7.patch 2012-05-21 07:33:27.000000000 +0000 @@ -0,0 +1,21 @@ +Description: Fix to libsmi2pysnmp tool to make it working again in Python < 2.7 +Forwarded: not-needed +Author: Ilya Etingof +Applied-Upstream: 4.2.3rc1 + +--- pysnmp-4.2.2/tools/libsmi2pysnmp 2012-04-03 01:22:12.000000000 +0900 ++++ pysnmp-4.2.3rc1/tools/libsmi2pysnmp 2012-04-27 19:59:45.000000000 +0900 +@@ -357,11 +357,11 @@ + while len(typedefs_left): + delayed = [] + for t in typedefs_left: +- if t[1]['parent module']['name'] in { \ ++ if t[1]['parent module']['name'] in ( \ + # implicitly imported MIBs + 'SNMPv2-TC', + 'SNMPv2-SMI' +- } or t[1]['parent module']['type'] in typedefs_seen: ++ ) or t[1]['parent module']['type'] in typedefs_seen: + typedefs_seen.add(t[0]) + typedefs.append(t) + continue diff -Nru python-pysnmp4-4.1.9a/debian/patches/series python-pysnmp4-4.2.2/debian/patches/series --- python-pysnmp4-4.1.9a/debian/patches/series 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/patches/series 2012-05-21 07:33:27.000000000 +0000 @@ -0,0 +1 @@ +fix-libsmi2pysnmp-with-python-less-than-2.7.patch diff -Nru python-pysnmp4-4.1.9a/debian/pycompat python-pysnmp4-4.2.2/debian/pycompat --- python-pysnmp4-4.1.9a/debian/pycompat 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/pycompat 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -2 diff -Nru python-pysnmp4-4.1.9a/debian/python-pysnmp4-doc.doc-base python-pysnmp4-4.2.2/debian/python-pysnmp4-doc.doc-base --- python-pysnmp4-4.1.9a/debian/python-pysnmp4-doc.doc-base 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/python-pysnmp4-doc.doc-base 2012-05-21 05:41:52.000000000 +0000 @@ -0,0 +1,9 @@ +Document: python-pysnmp4-doc +Title: python-pysnmp4 notes +Author: Ilya Etingof +Abstract: This manual describes pysnmp4 tools for Python and how to use it. +Section: Programming + +Format: HTML +Index: /usr/share/doc/python-pysnmp4-doc/pysnmp-tutorial.html +Files: /usr/share/doc/python-pysnmp4-doc/*.html diff -Nru python-pysnmp4-4.1.9a/debian/python-pysnmp4-doc.install python-pysnmp4-4.2.2/debian/python-pysnmp4-doc.install --- python-pysnmp4-4.1.9a/debian/python-pysnmp4-doc.install 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/python-pysnmp4-doc.install 2012-05-21 07:33:27.000000000 +0000 @@ -1,3 +1,4 @@ -docs/*.{html,gif} usr/share/doc/python-pysnmp4-doc/ +docs/*.html usr/share/doc/python-pysnmp4-doc/ +docs/*.gif usr/share/doc/python-pysnmp4-doc/ docs/mibs/*.txt usr/share/doc/python-pysnmp4-doc/ diff -Nru python-pysnmp4-4.1.9a/debian/python-pysnmp4.NEWS python-pysnmp4-4.2.2/debian/python-pysnmp4.NEWS --- python-pysnmp4-4.1.9a/debian/python-pysnmp4.NEWS 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/python-pysnmp4.NEWS 2012-05-21 10:25:59.000000000 +0000 @@ -0,0 +1,7 @@ +python-pysnmp4 (4.2.2-1) unstable; urgency=low + + Version 2 of pysnmp API, previously available in python-pysnmp2, is now + deprecated and not supported upstream anymore. Please consider updating your + code to version 4 of pysnmp API. + + -- Arnaud Fontaine Mon, 21 May 2012 19:24:19 +0900 diff -Nru python-pysnmp4-4.1.9a/debian/python-pysnmp-common.dirs python-pysnmp4-4.2.2/debian/python-pysnmp-common.dirs --- python-pysnmp4-4.1.9a/debian/python-pysnmp-common.dirs 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/python-pysnmp-common.dirs 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -usr/share/python-support/python-pysnmp-common/pysnmp/ diff -Nru python-pysnmp4-4.1.9a/debian/python-pysnmp-common.install python-pysnmp4-4.2.2/debian/python-pysnmp-common.install --- python-pysnmp4-4.1.9a/debian/python-pysnmp-common.install 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/python-pysnmp-common.install 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -pysnmp/__init__.py usr/share/python-support/python-pysnmp-common/pysnmp/ diff -Nru python-pysnmp4-4.1.9a/debian/pyversions python-pysnmp4-4.2.2/debian/pyversions --- python-pysnmp4-4.1.9a/debian/pyversions 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/pyversions 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -2.3- diff -Nru python-pysnmp4-4.1.9a/debian/README.Debian python-pysnmp4-4.2.2/debian/README.Debian --- python-pysnmp4-4.1.9a/debian/README.Debian 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/README.Debian 2012-05-21 10:21:26.000000000 +0000 @@ -1,20 +1,5 @@ ----- Documentation ---- The documentation and examples for this package is in python-pysnmp4-doc. When you install that package, you can find the documentation and examples in /usr/share/doc/python-pysnmp4-doc. - ----- API Versions ---- -If more than one pysnmp version is installed, it is possible to choose -a version by setting the PYSNMP_API_VERSION environment variable. - -You need to set the environment variable before importing pysnmp. -If you need pysnmp2, use this code: - - import os - os.environ['PYSNMP_API_VERSION'] = 'v2' - import pysnmp - -If you need another version, replace v2 with the correct one. - diff -Nru python-pysnmp4-4.1.9a/debian/rules python-pysnmp4-4.2.2/debian/rules --- python-pysnmp4-4.1.9a/debian/rules 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/rules 2012-05-21 10:20:48.000000000 +0000 @@ -1,19 +1,11 @@ #!/usr/bin/make -f # -*- mode: makefile; coding: utf-8 -*- -DEB_PYTHON_SYSTEM=pysupport - include /usr/share/cdbs/1/rules/debhelper.mk include /usr/share/cdbs/1/class/python-distutils.mk # Don't compress .py files DEB_COMPRESS_EXCLUDE := .py +DEB_PYTHON_INSTALL_ARGS_ALL += --install-layout=deb DEB_DESTDIR=debian/python-pysnmp4 - -binary-install/python-pysnmp4:: - rm -f debian/python-pysnmp4/usr/lib/python$(cdbs_python_current_version)/*-packages/pysnmp/__init__.py - -binary-install/python-pysnmp-common:: - dh_pysupport -ppython-pysnmp-common - dh_python -ppython-pysnmp-common diff -Nru python-pysnmp4-4.1.9a/debian/source/format python-pysnmp4-4.2.2/debian/source/format --- python-pysnmp4-4.1.9a/debian/source/format 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/source/format 2012-05-24 04:49:25.000000000 +0000 @@ -0,0 +1 @@ +3.0 (quilt) diff -Nru python-pysnmp4-4.1.9a/debian/source/options python-pysnmp4-4.2.2/debian/source/options --- python-pysnmp4-4.1.9a/debian/source/options 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/debian/source/options 2012-05-21 07:33:27.000000000 +0000 @@ -0,0 +1 @@ +extend-diff-ignore = "\.egg-info" diff -Nru python-pysnmp4-4.1.9a/docs/mibs/PYSNMP-COMMUNITY-MIB.txt python-pysnmp4-4.2.2/docs/mibs/PYSNMP-COMMUNITY-MIB.txt --- python-pysnmp4-4.1.9a/docs/mibs/PYSNMP-COMMUNITY-MIB.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/docs/mibs/PYSNMP-COMMUNITY-MIB.txt 2011-12-25 19:26:06.000000000 +0000 @@ -0,0 +1,237 @@ +PYSNMP-COMMUNITY-MIB DEFINITIONS ::= BEGIN + +IMPORTS + MODULE-IDENTITY, + OBJECT-TYPE + FROM SNMPv2-SMI + StorageType + FROM SNMPv2-TC + SnmpAdminString, + SnmpEngineID + FROM SNMP-FRAMEWORK-MIB + SnmpTagValue + FROM SNMP-TARGET-MIB + pysnmpModuleIDs + FROM PYSNMP-MIB; + +pysnmpCommunityMIB MODULE-IDENTITY + LAST-UPDATED "201112250000Z" -- 25 Dec 2011, midnight + ORGANIZATION "The PySNMP project" + CONTACT-INFO "E-mail: ilya@glas.net + Subscribe: pysnmp-users-request@lists.sourceforge.net" + DESCRIPTION + "This MIB module defines additional indices to facilitate + fast SNMP-COMMUNITY-MIB objects retrieval." + REVISION "201112250000Z" -- 25 Dec 2011, midnight + DESCRIPTION "The Initial Revision" + ::= { pysnmpModuleIDs 2 } + +-- Administrative assignments **************************************** + +pysnmpCommunityMIBObjects OBJECT IDENTIFIER ::= { pysnmpCommunityMIB 1 } +pysnmpCommunityMIBConformance OBJECT IDENTIFIER ::= { pysnmpCommunityMIB 2 } + +-- +-- The pysnmpOutboundCommunityTable contains a database of SNMPv1/v2c security +-- names indexed by SNMP community names. +-- This table may be consulted by pysnmp security module whilst processing +-- SNMPv1/v2c message. +-- + +pysnmpOutboundCommunityTable OBJECT-TYPE + SYNTAX SEQUENCE OF PysnmpOutboundCommunityEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "Table of SNMP-COMMUNITY-MIB's snmpSecurityName's indexed by + snmpCommunityName" + ::= { pysnmpCommunityMIBObjects 1 } + +pysnmpOutboundCommunityEntry OBJECT-TYPE + SYNTAX PysnmpOutboundCommunityEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "Information about a particular Community-to-Security entry." + INDEX { IMPLIED pysnmpOutboundCommunityName, pysnmpOutboundCommunityContextEngineID, pysnmpOutboundCommunityContextName, pysnmpOutboundCommunityTransportTag } + ::= { pysnmpOutboundCommunityTable 1 } + +PysnmpOutboundCommunityEntry ::= SEQUENCE { + pysnmpOutboundCommunityName OCTET STRING, + pysnmpOutboundCommunitySecurityName SnmpAdminString, + pysnmpOutboundCommunityContextEngineID SnmpEngineID, + pysnmpOutboundCommunityContextName SnmpAdminString, + pysnmpOutboundCommunityTransportTag SnmpTagValue, + pysnmpOutboundCommunityRowID OBJECT IDENTIFIER, + pysnmpOutboundCommunityStorageType StorageType +} + +pysnmpOutboundCommunityName OBJECT-TYPE + SYNTAX OCTET STRING + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityName used in INDEX" + ::= { pysnmpOutboundCommunityEntry 1 } + +pysnmpOutboundCommunitySecurityName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunitySecurityName used in INDEX" + ::= { pysnmpOutboundCommunityEntry 2 } + +pysnmpOutboundCommunityContextEngineID OBJECT-TYPE + SYNTAX SnmpEngineID + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextEngineID + used in INDEX" + ::= { pysnmpOutboundCommunityEntry 3 } + +pysnmpOutboundCommunityContextName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextName used in INDEX" + ::= { pysnmpOutboundCommunityEntry 4 } + +pysnmpOutboundCommunityTransportTag OBJECT-TYPE + SYNTAX SnmpTagValue + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityTransportTag used in INDEX" + ::= { pysnmpOutboundCommunityEntry 5 } + +pysnmpOutboundCommunityRowID OBJECT-TYPE + SYNTAX OBJECT IDENTIFIER + MAX-ACCESS read-write + STATUS current + DESCRIPTION + "SNMP-COMMUNITY-MIB::snmpCommunityTable object instance ID" + ::= { pysnmpOutboundCommunityEntry 6 } + +pysnmpOutboundCommunityStorageType OBJECT-TYPE + SYNTAX StorageType + MAX-ACCESS read-create + STATUS current + DESCRIPTION + "The storage type for this conceptual row in the + snmpCommunityTable. Conceptual rows having the value + 'permanent' need not allow write-access to any + columnar object in the row." + ::= { pysnmpOutboundCommunityEntry 7 } + +-- +-- The pysnmpCommunityInboundTable contains a database of SNMPv1/v2c security +-- names indexed by SNMP community names. +-- This table may be consulted by pysnmp security module whilst processing +-- SNMPv1/v2c message. +-- + +pysnmpInboundCommunityTable OBJECT-TYPE + SYNTAX SEQUENCE OF PysnmpInboundCommunityEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "Table of SNMP-COMMUNITY-MIB's snmpSecurityName's indexed by + snmpCommunityName" + ::= { pysnmpCommunityMIBObjects 2 } + +pysnmpInboundCommunityEntry OBJECT-TYPE + SYNTAX PysnmpInboundCommunityEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "Information about a particular Community-to-Security entry." + INDEX { IMPLIED pysnmpInboundCommunityName, pysnmpInboundCommunityTransportTag } + ::= { pysnmpInboundCommunityTable 1 } + +PysnmpInboundCommunityEntry ::= SEQUENCE { + pysnmpInboundCommunityName OCTET STRING, + pysnmpInboundCommunitySecurityName SnmpAdminString, + pysnmpInboundCommunityContextEngineID SnmpEngineID, + pysnmpInboundCommunityContextName SnmpAdminString, + pysnmpInboundCommunityTransportTag SnmpTagValue, + pysnmpInboundCommunityRowID OBJECT IDENTIFIER, + pysnmpInboundCommunityStorageType StorageType +} + +pysnmpInboundCommunityName OBJECT-TYPE + SYNTAX OCTET STRING + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityName used in INDEX" + ::= { pysnmpInboundCommunityEntry 1 } + +pysnmpInboundCommunitySecurityName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunitySecurityName used in INDEX" + ::= { pysnmpInboundCommunityEntry 2 } + +pysnmpInboundCommunityContextEngineID OBJECT-TYPE + SYNTAX SnmpEngineID + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextEngineID + used in INDEX" + ::= { pysnmpInboundCommunityEntry 3 } + +pysnmpInboundCommunityContextName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextName used in INDEX" + ::= { pysnmpInboundCommunityEntry 4 } + +pysnmpInboundCommunityTransportTag OBJECT-TYPE + SYNTAX SnmpTagValue + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "A copy of SNMP-COMMUNITY-MIB::snmpCommunityTransportTag used in INDEX" + ::= { pysnmpInboundCommunityEntry 5 } + +pysnmpInboundCommunityRowID OBJECT-TYPE + SYNTAX OBJECT IDENTIFIER + MAX-ACCESS read-write + STATUS current + DESCRIPTION + "SNMP-COMMUNITY-MIB::snmpCommunityTable object instance ID" + ::= { pysnmpInboundCommunityEntry 6 } + +pysnmpInboundCommunityStorageType OBJECT-TYPE + SYNTAX StorageType + MAX-ACCESS read-create + STATUS current + DESCRIPTION + "The storage type for this conceptual row in the + snmpCommunityTable. Conceptual rows having the value + 'permanent' need not allow write-access to any + columnar object in the row." + ::= { pysnmpInboundCommunityEntry 7 } + + +-- +-- The pysnmpUsmKeysTable contains a database of COMMUNITY users' localized +-- keys. +-- + +-- Conformance Information ******************************************* + +pysnmpCommunityMIBCompliances OBJECT IDENTIFIER + ::= { pysnmpCommunityMIBConformance 1 } +pysnmpCommunityMIBGroups OBJECT IDENTIFIER + ::= { pysnmpCommunityMIBConformance 2 } + +END diff -Nru python-pysnmp4-4.1.9a/docs/mibs/PYSNMP-PROXY-MIB.txt python-pysnmp4-4.2.2/docs/mibs/PYSNMP-PROXY-MIB.txt --- python-pysnmp4-4.1.9a/docs/mibs/PYSNMP-PROXY-MIB.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/docs/mibs/PYSNMP-PROXY-MIB.txt 2012-04-03 20:50:58.000000000 +0000 @@ -0,0 +1,117 @@ +PYSNMP-PROXY-MIB DEFINITIONS ::= BEGIN + +IMPORTS + MODULE-IDENTITY, + OBJECT-TYPE + FROM SNMPv2-SMI + SnmpAdminString + FROM SNMP-FRAMEWORK-MIB + TDomain, + TAddress, + RowStatus + FROM SNMPv2-TC + pysnmpModuleIDs + FROM PYSNMP-MIB; + +pysnmpProxyMIB MODULE-IDENTITY + LAST-UPDATED "201204040000Z" -- 04 April 2012, midnight + ORGANIZATION "The PySNMP project" + CONTACT-INFO "E-mail: ilya@glas.net + Subscribe: pysnmp-users-request@lists.sourceforge.net" + DESCRIPTION + "This MIB module defines implementation specific objects + that facilitate LCD lookup by RFC2576 procedures at PySNMP." + REVISION "201204040000Z" -- 04 April 2012, midnight + DESCRIPTION "The Initial Revision" + ::= { pysnmpModuleIDs 5 } + +-- Administrative assignments **************************************** + +pysnmpProxyMIBObjects OBJECT IDENTIFIER ::= { pysnmpProxyMIB 1 } +pysnmpProxyMIBConformance OBJECT IDENTIFIER ::= { pysnmpProxyMIB 2 } + +-- +-- The pysnmpProxySecurityNameTable contains a database of USM users passphrases +-- used for key localization. This table may be consulted during SNMP engine-ID +-- autodiscovery procedure. +-- + +pysnmpProxySecurityNameTable OBJECT-TYPE + SYNTAX SEQUENCE OF PysnmpProxySecurityNameEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "The table of USM users passphrases configured in the SNMP + engine's Local Configuration Datastore (LCD)." + ::= { pysnmpProxyMIBObjects 1 } + +pysnmpProxySecurityNameEntry OBJECT-TYPE + SYNTAX PysnmpProxySecurityNameEntry + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "Information about a particular USM user credentials." + INDEX { pysnmpProxyCommunityName, pysnmpProxyTransportDomain, pysnmpProxyTransportAddress } + ::= { pysnmpProxySecurityNameTable 1 } + +PysnmpProxySecurityNameEntry ::= SEQUENCE { + pysnmpProxyCommunityName OCTET STRING, + pysnmpProxyTransportDomain TDomain, + pysnmpProxyTransportAddress TAddress, + pysnmpProxySecurityName SnmpAdminString, + pysnmpProxySecurityNameStatus RowStatus +} + +pysnmpProxyCommunityName OBJECT-TYPE + SYNTAX OCTET STRING (SIZE(0..256)) + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "The username string for which a row in this table + represents a configuration." + ::= { pysnmpProxySecurityNameEntry 1 } + +pysnmpProxyTransportDomain OBJECT-TYPE + SYNTAX TDomain + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "The username string for which a row in this table + represents a configuration." + ::= { pysnmpProxySecurityNameEntry 2 } + +pysnmpProxyTransportAddress OBJECT-TYPE + SYNTAX TAddress + MAX-ACCESS not-accessible + STATUS current + DESCRIPTION + "The username string for which a row in this table + represents a configuration." + ::= { pysnmpProxySecurityNameEntry 3 } + +pysnmpProxySecurityName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The username string for which a row in this table + represents a configuration." + ::= { pysnmpProxySecurityNameEntry 4 } + +pysnmpProxySecurityNameStatus OBJECT-TYPE + SYNTAX RowStatus + MAX-ACCESS read-create + STATUS current + DESCRIPTION + "Table status" + ::= { pysnmpProxySecurityNameEntry 5 } + + +-- Conformance Information ******************************************* + +pysnmpProxyMIBCompliances OBJECT IDENTIFIER + ::= { pysnmpProxyMIBConformance 1 } +pysnmpProxyMIBGroups OBJECT IDENTIFIER + ::= { pysnmpProxyMIBConformance 2 } + +END diff -Nru python-pysnmp4-4.1.9a/docs/pysnmp-tutorial.html python-pysnmp4-4.2.2/docs/pysnmp-tutorial.html --- python-pysnmp4-4.1.9a/docs/pysnmp-tutorial.html 2007-11-28 12:06:05.000000000 +0000 +++ python-pysnmp4-4.2.2/docs/pysnmp-tutorial.html 2012-02-14 11:56:56.000000000 +0000 @@ -6,12 +6,12 @@ -
+

PySNMP tutorial

-by Ilya Etingof, Nov 2007 +by Ilya Etingof, 2007-2012

Table of contents

    @@ -27,12 +27,12 @@
  • 2.1.1 Synchronous Applications
  • 2.1.2 Asynchronous Applications
  • 2.1.3 Security configuration
      @@ -88,7 +88,7 @@

      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 Protocol.

      @@ -108,8 +108,8 @@ management software would be Performance.

      -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: Low resource consumption.

      @@ -132,7 +132,7 @@

      -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 @@

      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.

      @@ -486,7 +486,7 @@

      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 @@ specific request types.

      - +
      getCmd( authData, @@ -596,8 +596,8 @@ SNMP Security Parameters object, transportTarget is a SNMP Transport Configuration object -and *varNames are Managed Objects names -(ASN.1 OIDs). +and *varNames is a sequence of +Managed Objects names.

      @@ -615,18 +615,18 @@

      The pair of errorStatus and errorIndex -variables determines SNMP PDU-level error. If errorStatus -evaluates to true, this indicates SNMP PDU error caused by Managed Object -at position errorIndex-1 in varBinds. +variables determines SNMP PDU-level error. These are instances of pyasn1 +Integer class. +If errorStatus evaluates to true, this indicates SNMP PDU +error caused by Managed Object at position errorIndex-1 +in varBinds. Doing errorStatus.prettyPrint() would return an explanatory text error message.

      -The varBinds 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 Object Name and -Object Value. +The varBinds is a tuple of Managed Objects. Those found in response are bound by position to +Managed Object names passed in request.

      @@ -641,14 +641,17 @@ >>> 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))]
@@ -667,13 +670,15 @@

The authData and transportTarget parameters -have he same semantics as in getCmd method. +have he same semantics as in getCmd +method.

-The *varBinds input parameter is a tuple of Managed -Objects to be applied at Agent. The syntax of *varBinds -is the same as in getCmd. +The *varBinds input parameter is a sequence of +Managed Objects to be applied at Agent. The syntax of +*varBinds is the same as in +getCmd method.

@@ -687,7 +692,7 @@

The errorIndication, errorStatus and errorIndex parameters have the same meaning as in -getCmd method. +getCmd method.

@@ -706,11 +711,11 @@ ... 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)
@@ -732,7 +737,7 @@

Input parameters to the nextCmd method are the same as to -getCmd. +getCmd.

@@ -746,7 +751,7 @@

The errorIndication, errorStatus and errorIndex parameters have the same meaning as in -getCmd method. +getCmd method.

@@ -761,8 +766,21 @@ be a prefix for Object Names returned in response (as a side note, the same method in Applications API would return varBinds as held in a single response, and regardless of the prefix property). +

+ +

+It's also possible to modify the above behaviour so that the +varBindTable 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 lexicographicMode +attribute of the CommandGenerator class instance +to True. +

+ +

Properties of the varBinds parameter is the same as in -getCmd method. +getCmd method.

@@ -775,19 +793,20 @@
 >>> from pysnmp.entity.rfc3413.oneliner import cmdgen
->>> errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().nextCmd(
+>>> errorIndication, errorStatus, errorIndex, varBindTable = cmdgen.CommandGenerator().nextCmd(
 ... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),
 ... 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 +860,7 @@
 

The errorIndication, errorStatus, errorIndex and varBindTable parameters have -the same meaning as in getCmd method. +the same meaning as in getCmd method.

@@ -854,20 +873,21 @@
 >>> from pysnmp.entity.rfc3413.oneliner import cmdgen
->>> errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().bulkCmd(
+>>> errorIndication, errorStatus, errorIndex, varBindTable = cmdgen.CommandGenerator().bulkCmd(
 ... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),
 ... cmdgen.UdpTransportTarget(('localhost', 161)),
 ... 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 +932,8 @@
 
 

The authData and transportTarget parameters -have the same semantics as in CommandGenerator.getCmd method. +have the same semantics as in getCmd +method.

@@ -938,13 +959,13 @@ The *varBinds input parameter is a tuple of Managed Objects to be passed over to Manager along with Notification. The syntax of *varBinds is the same as in -CommandGenerator.getCmd. +getCmd

The sendNotification method returns an errorIndication parameter which has the same meaning as -in CommandGenerator.getCmd. +in getCmd method.

@@ -965,9 +986,9 @@ ... (('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
@@ -1054,7 +1075,7 @@

The errorIndication, errorStatus, errorIndex and varBinds parameters -have the same meaning as in CommandGenerator.getCmd +have the same meaning as in getCmd method.

@@ -1068,7 +1089,7 @@

The authData, transportTarget and varNames parameters have the same meaning as in -CommandGenerator.getCmd +getCmd method.

@@ -1098,7 +1119,7 @@

The authData and transportTarget parameters have the same meaning as in -CommandGenerator.setCmd method. +CommandGenerator.getCmd method.

@@ -1223,11 +1244,11 @@ >>> 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 +1257,14 @@ ... 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 >>>

@@ -1370,9 +1392,9 @@ >>> 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 +1405,7 @@ ... ('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 +1472,33 @@

Optional authProtocol parameter may be used to specify -non-default hash function algorithm. Possible values include -usmHMACMD5AuthProtocol, -usmHMACSHAAuthProtocol and -usmNoAuthProtocol. These symbols are defined in -pysnmp.entity.rfc3413.oneliner.cmdgen module. +non-default hash function algorithm. Possible values include:

+
    +
  • usmHMACMD5AuthProtocol -- MD5-based authentication protocol +
  • usmHMACSHAAuthProtocol -- SHA-based authentication protocol +
  • usmNoAuthProtocol -- no authentication to use +

Optional privProtocol parameter may be used to specify -non-default ciphering algorithm. Possible values include -usmDESPrivProtocol, -usmAesCfb128Protocol, and -usmNoPrivProtocol. +non-default ciphering algorithm. Possible values include:

+

+

    +
  • usmDESPrivProtocol -- DES-based encryption protocol +
  • usmAesCfb128Protocol -- AES128-based encryption protocol (RFC3826) +
  • usm3DESEDEPrivProtocol -- triple DES-based encryption protocol (Extended Security Options) +
  • usmAesCfb192Protocol -- AES192-based encryption protocol (Extended Security Options) +
  • usmAesCfb256Protocol -- AES256-based encryption protocol (Extended Security Options) +
  • usmNoPrivProtocol -- no encryption to use +
+ +

+All these symbols are defined in +pysnmp.entity.rfc3413.oneliner.cmdgen module. +

+ @@ -1539,62 +1574,34 @@

-In PySNMP programming context, -Managed Object term (also called Variable-Binding 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 Managed Object +instance is represented by a pair of Name and Value collectively called +a Variable-Binding.

-Managed Objects Names and Values are ASN.1 types. -Both Names and Values are derived from -PyASN1 classes. These are defined in -pysnmp.proto.rfc1902 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.

-Managed Object Name is a tuple or tuple-like -Object Identifier class instance. +Managed Object Name is an instance of ObjectName class, +which is derived from PyASN1 +ObjectIdentifier. +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.

-
-
class ObjectIdentifier( -objectIdentifier -)
-
-

-Create an ASN.1 Object Identifier object. The -objectIdentifier 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"). -

- -

-Instances of this class mimic basic properties of Python tuple. Sub-OIDs -of an OID translate into tuple components. -

- -

-For more information on ObjectIdentifier class properties, -refer to PyASN1 documentation. -

-
-
-

-It's PySNMP the design decision to always use SMIv2 -definitions for Managed Objects regardless of SNMP protocol version being -used. -

- -

Managed Object Instance Value is an instance of some PyASN1 class or its SNMP-specific derivative. The latter case reflects SNMP-specific ASN.1 sub-type. The list of Managed Object -Instance Value classes follows. +Instance Value classes follow.

@@ -1606,7 +1613,8 @@

Create a SMIv2 Integer object. The value 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 Integer.

@@ -1624,6 +1632,22 @@ + +
+
class OctetIdentifier( +value +)
+
+

+Create a SMIv2 OctetIdentifier object. +The value +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 OctetIdentifier. +

+
+
+
class OctetString( @@ -1633,7 +1657,8 @@

Create a SMIv2 OctetString object. The value 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 OctetString.

@@ -1647,7 +1672,8 @@

Create a SMIv2 IpAddress object. The value 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 OctetString.

@@ -1744,12 +1770,21 @@

Create a SMIv2 Bits object. The value 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 OctetString. +

+It's PySNMP design decision to always use SMIv2 +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). +

+ +

For more information on SNMP Managed Value objects properties, refer to their base classes in PyASN1 documentation. @@ -2015,7 +2050,8 @@
-myManagedObject = MibScalar((1, 3, 6, 1, 4, 1, 20408, 2, 1), OctetString()).setMaxAccess("readonly")
+myManagedObject = MibScalar((1, 3, 6, 1, 4, 1, 20408, 2, 1),
+                            OctetString()).setMaxAccess("readonly")
 
@@ -2029,7 +2065,8 @@
-myManagedObjectInstance = MibScalarInstance(myManagedObject.getName() + (0,), myManagedObject.getSyntax().clone('my string'))
+myManagedObjectInstance = MibScalarInstance(myManagedObject.getName() + (0,), 
+    myManagedObject.getSyntax().clone('my string'))
 
@@ -2053,7 +2090,8 @@
-myTableValueInstance = MibScalarInstance(myTableValue.getName() + (1,), myTableValue.getSyntax().clone('my value'))
+myTableValueInstance = MibScalarInstance(myTableValue.getName() + (1,), 
+    myTableValue.getSyntax().clone('my value'))
 
@@ -2221,9 +2259,9 @@ >>> >>> # 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('') >>> @@ -2334,11 +2372,11 @@ >>> 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) ()

@@ -2408,11 +2446,11 @@ >>> 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,)
@@ -3105,7 +3143,7 @@

-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!

diff -Nru python-pysnmp4-4.1.9a/examples/smi/backend.py python-pysnmp4-4.2.2/examples/smi/backend.py --- python-pysnmp4-4.1.9a/examples/smi/backend.py 2007-03-25 20:43:27.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/smi/backend.py 2011-11-07 07:50:44.000000000 +0000 @@ -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 + print(oid, val.prettyPrint()) -print 'Unloading MIB modules...', +print('Unloading MIB modules...'), mibBuilder.unloadModules() -print 'done' +print('done') diff -Nru python-pysnmp4-4.1.9a/examples/smi/instrum.py python-pysnmp4-4.2.2/examples/smi/instrum.py --- python-pysnmp4-4.1.9a/examples/smi/instrum.py 2006-05-21 11:30:17.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/smi/instrum.py 2011-11-07 07:50:44.000000000 +0000 @@ -41,10 +41,10 @@ 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 + print(oid, val.prettyPrint()) diff -Nru python-pysnmp4-4.1.9a/examples/smi/view.py python-pysnmp4-4.2.2/examples/smi/view.py --- python-pysnmp4-4.1.9a/examples/smi/view.py 2005-10-26 21:14:36.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/smi/view.py 2011-11-07 07:50:44.000000000 +0000 @@ -1,61 +1,73 @@ # SNMP manager-side MIB management from pysnmp.smi import builder, view, error -print 'Loading MIB modules...', -mibBuilder = builder.MibBuilder().loadModules( +# Create MIB loader/builder +mibBuilder = builder.MibBuilder() + +# Optionally set an alternative path to compiled MIBs +#print('Setting MIB sources...') +#mibSources = mibBuilder.getMibSources() + ( +# builder.DirMibSource('/opt/pysnmp_mibs'), +# ) +#mibBuilder.setMibSources(*mibSources) +#print(mibBuilder.getMibSources()) +#print('done') + +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 -Nru python-pysnmp4-4.1.9a/examples/v1arch/agent/cmdrsp.py python-pysnmp4-4.2.2/examples/v1arch/agent/cmdrsp.py --- python-pysnmp4-4.1.9a/examples/v1arch/agent/cmdrsp.py 2006-05-21 11:33:05.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/agent/cmdrsp.py 2011-11-07 07:50:44.000000000 +0000 @@ -7,16 +7,26 @@ 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 at %s' % __file__ + 'PySNMP example command responder' ) 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 @@ -33,10 +43,10 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): while wholeMsg: msgVer = api.decodeMessageVersion(wholeMsg) - if api.protoModules.has_key(msgVer): + 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(), @@ -66,7 +76,7 @@ ) elif reqPDU.isSameTypeWith(pMod.GetRequestPDU()): for oid, val in pMod.apiPDU.getVarBinds(reqPDU): - if mibInstrIdx.has_key(oid): + if oid in mibInstrIdx: varBinds.append((oid, mibInstrIdx[oid](msgVer))) else: # No such instance diff -Nru python-pysnmp4-4.1.9a/examples/v1arch/agent/ntforg.py python-pysnmp4-4.2.2/examples/v1arch/agent/ntforg.py --- python-pysnmp4-4.1.9a/examples/v1arch/agent/ntforg.py 2005-11-04 20:39:44.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/agent/ntforg.py 2009-12-01 18:42:07.000000000 +0000 @@ -5,7 +5,7 @@ from pysnmp.proto import api # Protocol version to use -verID = api.protoVersion1 +verID = api.protoVersion2c pMod = api.protoModules[verID] # Build PDU diff -Nru python-pysnmp4-4.1.9a/examples/v1arch/manager/bulkgen.py python-pysnmp4-4.2.2/examples/v1arch/manager/bulkgen.py --- python-pysnmp4-4.1.9a/examples/v1arch/manager/bulkgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/manager/bulkgen.py 2011-11-06 20:37:10.000000000 +0000 @@ -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 -Nru python-pysnmp4-4.1.9a/examples/v1arch/manager/getgen.py python-pysnmp4-4.2.2/examples/v1arch/manager/getgen.py --- python-pysnmp4-4.1.9a/examples/v1arch/manager/getgen.py 2006-04-24 16:35:10.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/manager/getgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -24,7 +24,7 @@ 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 @@ # 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 -Nru python-pysnmp4-4.1.9a/examples/v1arch/manager/nextgen.py python-pysnmp4-4.2.2/examples/v1arch/manager/nextgen.py --- python-pysnmp4-4.1.9a/examples/v1arch/manager/nextgen.py 2006-04-24 16:35:10.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/manager/nextgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -7,6 +7,7 @@ # Protocol version to use pMod = api.protoModules[api.protoVersion1] +#pMod = api.protoModules[api.protoVersion2c] # SNMP table header headVars = [ pMod.ObjectIdentifier((1,3,6)) ] @@ -14,9 +15,7 @@ # 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() @@ -28,7 +27,7 @@ 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): @@ -40,27 +39,26 @@ # 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: - if val is None: - continue - 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 val is not None: + if not isinstance(val, pMod.Null): break else: transportDispatcher.jobFinished(1) # 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( @@ -68,7 +66,7 @@ ) global startedAt if time() - startedAt > 3: - raise 'Request timed out' + raise Exception('Request timed out') startedAt = time() return wholeMsg diff -Nru python-pysnmp4-4.1.9a/examples/v1arch/manager/ntfrcv.py python-pysnmp4-4.2.2/examples/v1arch/manager/ntfrcv.py --- python-pysnmp4-4.1.9a/examples/v1arch/manager/ntfrcv.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/manager/ntfrcv.py 2011-11-07 07:50:44.000000000 +0000 @@ -7,41 +7,47 @@ def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): while wholeMsg: msgVer = int(api.decodeMessageVersion(wholeMsg)) - if api.protoModules.has_key(msgVer): + 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 -Nru python-pysnmp4-4.1.9a/examples/v1arch/manager/setgen.py python-pysnmp4-4.2.2/examples/v1arch/manager/setgen.py --- python-pysnmp4-4.1.9a/examples/v1arch/manager/setgen.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v1arch/manager/setgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -26,7 +26,7 @@ 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 @@ # 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/agent/cmdrsp.py python-pysnmp4-4.2.2/examples/v3arch/agent/cmdrsp.py --- python-pysnmp4-4.1.9a/examples/v3arch/agent/cmdrsp.py 2007-07-09 13:39:47.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/agent/cmdrsp.py 2011-01-17 00:14:55.000000000 +0000 @@ -1,7 +1,8 @@ # Command Responder from pysnmp.entity import engine, config -from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import cmdrsp, context +from pysnmp.carrier.asynsock.dgram import udp +#from pysnmp.carrier.asynsock.dgram import udp6 from pysnmp import debug # Optionally enable stdout debugging @@ -11,13 +12,20 @@ # to socket transport dispatcher snmpEngine = engine.SnmpEngine() -# Setup transport endpoint +# Setup UDP over IPv4 transport endpoint config.addSocketTransport( snmpEngine, udp.domainName, - udp.UdpSocketTransport().openServerMode(('127.0.0.1', 161)) + udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) +# Setup UDP over IPv6 transport endpoint +#config.addSocketTransport( +# snmpEngine, +# udp6.domainName, +# udp6.Udp6Transport().openServerMode(('::1', 161)) +# ) + # Create and put on-line my managed object sysDescr, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr') MibScalarInstance, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') @@ -33,7 +41,11 @@ config.addV3User( snmpEngine, 'test-user', config.usmHMACMD5AuthProtocol, 'authkey1', +# config.usmHMACSHAAuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' +# config.usm3DESEDEPrivProtocol, 'privkey1' +# config.usmAesCfb192Protocol, 'privkey1' +# config.usmAesCfb256Protocol, 'privkey1' # config.usmAesCfb128Protocol, 'privkey1' ) diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/agent/ntforg.py python-pysnmp4-4.2.2/examples/v3arch/agent/ntforg.py --- python-pysnmp4-4.1.9a/examples/v3arch/agent/ntforg.py 2007-05-28 16:15:36.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/agent/ntforg.py 2011-11-07 07:50:44.000000000 +0000 @@ -51,11 +51,11 @@ # SNMP context snmpContext = context.SnmpContext(snmpEngine) -def cbFun(snmpEngine, errorIndication, cbCtx): +def cbFun(sendRequestHandle, errorIndication, cbCtx): if errorIndication: - print errorIndication + print(errorIndication) -errorIndication = ntforg.NotificationOriginator(snmpContext).sendNotification( +ntforg.NotificationOriginator(snmpContext).sendNotification( snmpEngine, # Notification targets 'myNotifyName', @@ -66,7 +66,4 @@ cbFun ) -if errorIndication: - print errorIndication -else: - snmpEngine.transportDispatcher.runDispatcher() +snmpEngine.transportDispatcher.runDispatcher() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/manager/bulkgen.py python-pysnmp4-4.2.2/examples/v3arch/manager/bulkgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/manager/bulkgen.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/manager/bulkgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -35,22 +35,18 @@ def cbFun(sendRequesthandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: - print errorIndication - return + print(errorIndication) + return # stop on error if errorStatus: - print errorStatus.prettyPrint() - return + 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: - if val is None: - print oid.prettyPrint() - else: - print '%s = %s' % (oid.prettyPrint(), val.prettyPrint()) - for oid, val in varBindTable[-1]: - if val is not None: - break - else: - return # stop on end-of-table + print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return 1 # continue walking cmdgen.BulkCommandGenerator().sendReq( diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/manager/getgen.py python-pysnmp4-4.2.2/examples/v3arch/manager/getgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/manager/getgen.py 2007-07-09 13:39:47.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/manager/getgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -49,9 +49,9 @@ 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/manager/nextgen.py python-pysnmp4-4.2.2/examples/v3arch/manager/nextgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/manager/nextgen.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/manager/nextgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -35,22 +35,20 @@ def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: - print errorIndication - return - if errorStatus: - print errorStatus.prettyPrint() + 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' % ( + errorStatus.prettyPrint(), + errorIndex and varBindTable[-1][int(errorIndex)-1] or '?' + ) + ) + return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: - if val is None: - print oid.prettyPrint() - else: - print '%s = %s' % (oid.prettyPrint(), val.prettyPrint()) - for oid, val in varBindTable[-1]: - if val is not None: - break - else: - return # stop on end-of-table + print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return 1 # continue walking cmdgen.NextCommandGenerator().sendReq( diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/manager/ntfrcv.py python-pysnmp4-4.2.2/examples/v3arch/manager/ntfrcv.py --- python-pysnmp4-4.1.9a/examples/v3arch/manager/ntfrcv.py 2007-02-14 10:34:12.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/manager/ntfrcv.py 2011-11-07 07:50:44.000000000 +0000 @@ -32,14 +32,18 @@ # Callback function for receiving notifications def cbFun(snmpEngine, + stateReference, contextEngineId, contextName, varBinds, cbCtx): - print 'Notification from SNMP Engine \"%s\", Context \"%s\"' % ( - contextEngineId, contextName + transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) + 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/manager/setgen.py python-pysnmp4-4.2.2/examples/v3arch/manager/setgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/manager/setgen.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/manager/setgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -49,12 +49,16 @@ snmpEngine.transportDispatcher.runDispatcher() if cbCtx['errorIndication']: - print cbCtx['errorIndication'] + print(cbCtx['errorIndication']) elif cbCtx['errorStatus']: - print '%s at %s' % ( - cbCtx['errorStatus'].prettyPrint(), - cbCtx['varBinds'][int(cbCtx['errorIndex'])-1] + if cbCtx['errorIndex']: + print('%s at %s' % ( + cbCtx['errorStatus'].prettyPrint(), + cbCtx['varBinds'][int(cbCtx['errorIndex'])-1] + ) ) + else: + 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/agent/ntforg.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/agent/ntforg.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/agent/ntforg.py 2007-05-28 17:44:43.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/agent/ntforg.py 2011-12-07 16:54:33.000000000 +0000 @@ -2,11 +2,11 @@ from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 -errorIndication = ntforg.NotificationOriginator().sendNotification( +ntforg.NotificationOriginator().sendNotification( # SNMP v1 -# ntforg.CommunityData('test-manager', 'public', 0), +# ntforg.CommunityData('public', mpModel=0), # SNMP v2 -# ntforg.CommunityData('test-manager', 'public'), +# ntforg.CommunityData('public'), # SNMP v3 ntforg.UsmUserData('test-user', 'authkey1', 'privkey1'), ntforg.UdpTransportTarget(('localhost', 162)), @@ -20,6 +20,3 @@ # Plain OID name, rfc1902 class instance value ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('new name')) ) - -if errorIndication: - print errorIndication diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/async/nextgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/async/nextgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/async/nextgen.py 2007-04-03 15:23:59.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/async/nextgen.py 2011-12-21 16:52:16.000000000 +0000 @@ -4,12 +4,12 @@ # ( ( authData, transportTarget, varNames ), ... ) targets = ( - # 1-st target (SNMPv1) - ( cmdgen.CommunityData('test-agent', 'public'), + # 1-st target (SNMPv2c -- can't handle v1&v2c with equal communities) + ( cmdgen.CommunityData('public'), # , mpModel=0), cmdgen.UdpTransportTarget(('localhost', 161)), (rfc1902.ObjectName((1,3,6,1,2,1)), rfc1902.ObjectName((1,3,6,1,3,1)))), # 2-nd target (SNMPv2c) - ( cmdgen.CommunityData('test-agent', 'public', 1), + ( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('localhost', 161)), (rfc1902.ObjectName((1,3,6,1,4,1)),) ), # 3-nd target (SNMPv3) @@ -20,40 +20,43 @@ # ... ) -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 'SNMP engine error', errorIndication + print(errorIndication) return 1 if errorStatus: - print 'SNMP error %s at %s' % (errorStatus, errorIndex) + 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)): name, val = varBindTableRow[idx] - if val is not None and varBindHead[idx].isPrefixOf(name): + if val is not None and varBindHead[idx] <= name: # 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 -cmdGen = cmdgen.CommandGenerator() +cmdGen = cmdgen.AsynCommandGenerator() for authData, transportTarget, varNames in targets: - cmdGen.asyncNextCmd( + cmdGen.nextCmd( authData, transportTarget, varNames, # User-space callback function and its context (cbFun, (varNames, authData, transportTarget)) diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/bulkgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/bulkgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/bulkgen.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/bulkgen.py 2011-12-07 16:55:43.000000000 +0000 @@ -4,9 +4,9 @@ errorIndication, errorStatus, errorIndex, \ varBindTable = cmdgen.CommandGenerator().bulkCmd( # SNMP v1 -# cmdgen.CommunityData('test-agent', 'public', 0), +# cmdgen.CommunityData('public', mpModel=0), # SNMP v2 -# cmdgen.CommunityData('test-agent', 'public'), +# cmdgen.CommunityData('public'), # SNMP v3 cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('localhost', 161)), @@ -15,14 +15,15 @@ ) 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] + 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/getgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/getgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/getgen.py 2007-05-28 17:45:42.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/getgen.py 2011-12-07 16:53:48.000000000 +0000 @@ -4,9 +4,9 @@ errorIndication, errorStatus, \ errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( # SNMP v1 -# cmdgen.CommunityData('test-agent', 'public', 0), +# cmdgen.CommunityData('public', mpModel=0), # SNMP v2 - cmdgen.CommunityData('test-agent', 'public'), + cmdgen.CommunityData('public'), # SNMP v3 # cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('localhost', 161)), @@ -17,12 +17,14 @@ ) if errorIndication: - print errorIndication + print(errorIndication) else: if errorStatus: - print '%s at %s\n' % ( - errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] + 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/nextgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/nextgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/nextgen.py 2005-11-04 20:39:45.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/nextgen.py 2011-12-07 16:54:19.000000000 +0000 @@ -4,9 +4,9 @@ errorIndication, errorStatus, errorIndex, \ varBindTable = cmdgen.CommandGenerator().nextCmd( # SNMP v1 -# cmdgen.CommunityData('test-agent', 'public', 0), +# cmdgen.CommunityData('public', mpModel=0), # SNMP v2 - cmdgen.CommunityData('test-agent', 'public'), + cmdgen.CommunityData('public'), # SNMP v3 # cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('localhost', 161)), @@ -14,14 +14,15 @@ ) 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] + 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/setgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/setgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/setgen.py 2007-05-28 17:44:43.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/setgen.py 2011-12-07 16:54:07.000000000 +0000 @@ -5,9 +5,9 @@ errorIndication, errorStatus, \ errorIndex, varBinds = cmdgen.CommandGenerator().setCmd( # SNMP v1 -# cmdgen.CommunityData('test-agent', 'public', 0), +# cmdgen.CommunityData('public', mpModel=0), # SNMP v2 -# cmdgen.CommunityData('test-agent', 'public'), +# cmdgen.CommunityData('public'), # SNMP v3 cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('localhost', 161)), @@ -18,12 +18,14 @@ ) if errorIndication: - print errorIndication + print(errorIndication) else: if errorStatus: - print '%s at %s\n' % ( - errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] + 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/withmib/nextgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/withmib/nextgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/withmib/nextgen.py 2007-05-28 17:45:42.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/withmib/nextgen.py 2011-12-07 16:55:57.000000000 +0000 @@ -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 @@ -8,9 +7,9 @@ errorIndication, errorStatus, errorIndex, \ varBindTable = cmdGen.nextCmd( # SNMP v1 -# cmdgen.CommunityData('test-agent', 'public', 0), +# cmdgen.CommunityData('public', mpModel=0), # SNMP v2 -# cmdgen.CommunityData('test-agent', 'public'), +# cmdgen.CommunityData('public'), # SNMP v3 cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), # Transport @@ -25,13 +24,14 @@ ) 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 @@ 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/withmib/setgen.py python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/withmib/setgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/oneliner/manager/withmib/setgen.py 2007-05-28 17:44:43.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/oneliner/manager/withmib/setgen.py 2011-12-07 16:55:52.000000000 +0000 @@ -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 @@ -7,9 +6,9 @@ errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( # SNMP v1 -# cmdgen.CommunityData('test-agent', 'public', 0), +# cmdgen.CommunityData('public', mpModel=0), # SNMP v2 -# cmdgen.CommunityData('test-agent', 'public'), +# cmdgen.CommunityData('public'), # SNMP v3 cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), # Transport @@ -19,12 +18,13 @@ ) 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 @@ 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 -Nru python-pysnmp4-4.1.9a/examples/v3arch/proxy/cmdproxy.py python-pysnmp4-4.2.2/examples/v3arch/proxy/cmdproxy.py --- python-pysnmp4-4.1.9a/examples/v3arch/proxy/cmdproxy.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/proxy/cmdproxy.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,108 @@ +# +# SNMP proxy example +# +# Relay SNMP messages between Managers and Agents using any combinations +# of SNMP protocol versions for both up and downstream packets. +# +# To query SNMPv3 Manager over SNMPv2c through this Proxy use: +# snmpget -v2c -c tgt-v3-1 localhost:1161 sysDescr.0 +# or SNMPv2c Manager over SNMPv3: +# snmpget -v3 -u test-user -lauthPriv -A authkey1 -X privkey1 -n tgt-v2c-1 localhost:1161 sysDescr.0 +# there are four combinations in total. ;) +# +from pysnmp.entity import engine, config +from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context +from pysnmp.proto.api import v2c +from pysnmp.carrier.asynsock.dgram import udp + +# Create SNMP engine with autogenernated engineID and pre-bound +# to socket transport dispatcher +snmpEngine = engine.SnmpEngine() + +# Setup UDP over IPv4 transport endpoints + +# Agent will listen here +config.addSocketTransport( + snmpEngine, + udp.domainName + (1,), # use transport domain's sub-name + udp.UdpTransport().openServerMode(('127.0.0.1', 1161)) + ) + +# Manager will send packets there +config.addSocketTransport( + snmpEngine, + udp.domainName + (2,), # use transport domain's sub-name + udp.UdpTransport().openClientMode() + ) + +# SNMP credentials used by Manager + +# v1/2 setup +config.addV1System(snmpEngine, 'dest-cmt', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' +# config.usmAesCfb128Protocol, 'privkey1' + ) + +# Transport targets used by Manager + +# Target 1, SNMPv3 setup +config.addTargetParams(snmpEngine, 'v3-dest-1', 'test-user', 'authPriv') +config.addTargetAddr( + snmpEngine, 'tgt-v3-1', config.snmpUDPDomain + (2,), + ('127.0.0.1', 161), 'v3-dest-1' + ) +# This is to map community to context name in incoming messages +config.addV1System(snmpEngine, 'v2c-src-A', 'tgt-v3-1', contextName='tgt-v3-1') + +# Target 1, SNMPv2c setup +config.addTargetParams(snmpEngine, 'v2c-dest-1', 'dest-cmt', 'noAuthNoPriv', 1) +config.addTargetAddr( + snmpEngine, 'tgt-v2c-1', config.snmpUDPDomain + (2,), + ('127.0.0.1', 161), 'v2c-dest-1' + ) +# This is to map community to context name in incoming messages +config.addV1System(snmpEngine, 'v2c-src-B', 'tgt-v2c-1', contextName='tgt-v2c-1') + +# Default SNMP context +config.addContext(snmpEngine, '') +snmpContext = context.SnmpContext(snmpEngine) + + +class GetCommandProxy(cmdrsp.GetCommandResponder): + acmID = 0 # void access control method + cmdGen = cmdgen.GetCommandGenerator() + + def handleMgmtOperation(self, snmpEngine, stateReference, contextName, + PDU, acInfo): + (acFun, acCtx) = acInfo + varBinds = v2c.apiPDU.getVarBinds(PDU) + try: + # The trick here is to use contextName as SNMP Manager target name + self.cmdGen.sendReq( + snmpEngine, contextName, varBinds, + self.handleResponse, (stateReference, varBinds) + ) + except Exception: + self.sendRsp(snmpEngine, stateReference, 5, 0, varBinds) + + def handleResponse(self, sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBinds, cbCtx): + (stateReference, reqVarBinds) = cbCtx + if errorIndication: + errorStatus = 5 + varBinds = reqVarBinds + + self.sendRsp( + snmpEngine, stateReference, errorStatus, errorIndex, varBinds + ) + +# Apps registration +GetCommandProxy(snmpEngine, snmpContext) + +snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transportDispatcher.runDispatcher() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/agent/cmdrsp.py python-pysnmp4-4.2.2/examples/v3arch/twisted/agent/cmdrsp.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/agent/cmdrsp.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/agent/cmdrsp.py 2010-12-12 22:53:15.000000000 +0000 @@ -0,0 +1,50 @@ +# Command Responder over Twisted transport +from pysnmp.entity import engine, config +from pysnmp.entity.rfc3413 import cmdrsp, context +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.carrier.twisted import dispatch + +# Create SNMP engine with autogenernated engineID and pre-bound +# to socket transport dispatcher +snmpEngine = engine.SnmpEngine() + +# Setup non-default transport dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# Setup UDP over IPv4 transport endpoint +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTransport().openServerMode(('127.0.0.1', 161)) + ) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' +# config.usmAesCfb128Protocol, 'privkey1' + ) + +# Configure VACM from the scratch +config.addContext(snmpEngine, '') +config.addVacmUser(snmpEngine, 1, 'test-agent', 'noAuthNoPriv', + (1,3,6), (1,3,6)) # v1 +config.addVacmUser(snmpEngine, 2, 'test-agent', 'noAuthNoPriv', + (1,3,6), (1,3,6)) # v2c +config.addVacmUser(snmpEngine, 3, 'test-user', 'authPriv', + (1,3,6), (1,3,6)) # v3 + +# SNMP context +snmpContext = context.SnmpContext(snmpEngine) + +# Apps registration +cmdrsp.GetCommandResponder(snmpEngine, snmpContext) +cmdrsp.SetCommandResponder(snmpEngine, snmpContext) +cmdrsp.NextCommandResponder(snmpEngine, snmpContext) +cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) +snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish +snmpEngine.transportDispatcher.runDispatcher() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/agent/ntforg.py python-pysnmp4-4.2.2/examples/v3arch/twisted/agent/ntforg.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/agent/ntforg.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/agent/ntforg.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,89 @@ +# Notification originator +from twisted.internet import reactor +from pysnmp.entity import engine, config +from pysnmp.carrier.twisted import dispatch +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.entity.rfc3413 import context +from pysnmp.entity.rfc3413.twisted import ntforg +from pysnmp.proto.api import v2c + +# Send either Teap or Inform request +doInform = 1 + +snmpEngine = engine.SnmpEngine() + +# Set Twisted dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' + ) + +# Transport params +config.addTargetParams(snmpEngine, 'myParams', 'test-user', 'authPriv') +#config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 1) + +# Transport addresses +config.addTargetAddr( + snmpEngine, 'myNMS', config.snmpUDPDomain, + ('127.0.0.1', 162), 'myParams', tagList='myManagementStations' + ) + +# Notification targets +if doInform: + config.addNotificationTarget( + snmpEngine, 'myNotifyName', 'myParams','myManagementStations','inform' + ) +else: + config.addNotificationTarget( + snmpEngine, 'myNotifyName', 'myParams', 'myManagementStations', 'trap' + ) + +# Transport +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTwistedTransport().openClientMode() + ) + +# Agent-side VACM setup +config.addContext(snmpEngine, '') +config.addVacmUser(snmpEngine, 1, 'test-agent', 'noAuthNoPriv', + (), (), (1,3,6)) # v1 +config.addVacmUser(snmpEngine, 2, 'test-agent', 'noAuthNoPriv', + (), (), (1,3,6)) # v2c +config.addVacmUser(snmpEngine, 3, 'test-user', 'authPriv', + (), (), (1,3,6)) # v3 + +# SNMP context +snmpContext = context.SnmpContext(snmpEngine) + +# Twisted API follows + +def receiveResponse(cbCtx): + (sendRequestHandle, errorIndication) = cbCtx + if errorIndication: + print('Error: %s' % errorIndication) + reactor.stop() + +ntfOrg = ntforg.NotificationOriginator(snmpContext) + +df = ntfOrg.sendNotification( + snmpEngine, + # Notification targets + 'myNotifyName', + # Trap OID (SNMPv2-MIB::coldStart) + (1,3,6,1,6,3,1,1,5,1), + # ((oid, value), ... ) + (((1,3,6,1,2,1,1,5), v2c.OctetString('Example Notificator')),) + ) + +if doInform: + df.addCallback(receiveResponse) + reactor.run() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/bulkgen.py python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/bulkgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/bulkgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/bulkgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,80 @@ +# BULK Command Generator +from twisted.internet import reactor, defer +from pysnmp.entity import engine, config +from pysnmp.carrier.twisted import dispatch +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.entity.rfc3413.twisted import cmdgen +from pyasn1.type import univ + +snmpEngine = engine.SnmpEngine() + +# Set Twisted dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' + ) + +# Transport params +config.addTargetParams(snmpEngine, 'myParams', 'test-user', 'authPriv') +#config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 1) + +# Transport addresses +config.addTargetAddr( + snmpEngine, 'myRouter', config.snmpUDPDomain, + ('127.0.0.1', 161), 'myParams' + ) + +# Transport +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTwistedTransport().openClientMode() + ) + +# Twisted API follows + +def receiveResponse(cbCtx): + (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx + if errorIndication: + print('Error: %s' % errorIndication) + reactor.stop() + return + if errorStatus and errorStatus != 2: + 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())) + + for o, v in varBindTable[-1]: + if not isinstance(v, univ.Null): + break + else: + reactor.stop() # no more objects available + return + + df = defer.Deferred() + df.addCallback(receiveResponse) + return df # this is to indicate that we wish to continue walking + +bulkCmdGen = cmdgen.BulkCommandGenerator() + +df = bulkCmdGen.sendReq( + snmpEngine, 'myRouter', 0, 25, (((1,3,6,1,2), None), ((1,3,6,1,4), None)) + ) + +df.addCallback(receiveResponse) + +reactor.run() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/getgen.py python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/getgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/getgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/getgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,67 @@ +# GET Command Generator +from twisted.internet import reactor, defer +from pysnmp.entity import engine, config +from pysnmp.carrier.twisted import dispatch +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.entity.rfc3413.twisted import cmdgen + +snmpEngine = engine.SnmpEngine() + +# Set Twisted dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' + ) + +# Transport params +config.addTargetParams(snmpEngine, 'myParams', 'test-user', 'authPriv') +#config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 1) + +# Transport addresses +config.addTargetAddr( + snmpEngine, 'myRouter', config.snmpUDPDomain, + ('127.0.0.1', 161), 'myParams' + ) + +# Transport +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTwistedTransport().openClientMode() + ) + +# Twisted API follows + +def receiveResponse(cbCtx): + (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx + if errorIndication: + print('Error: %s' % errorIndication) + reactor.stop() + return + if errorStatus: + print('Error: %s at %s' % (errorStatus.prettyPrint(), errorIndex)) + reactor.stop() + return + for oid, val in varBinds: + if val is None: + print(oid.prettyPrint()) + else: + print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) + reactor.stop() + +getCmdGen = cmdgen.GetCommandGenerator() + +df = getCmdGen.sendReq( + snmpEngine, 'myRouter', (((1,3,6,1,2,1,1,1,0), None),) + ) + +df.addCallback(receiveResponse) + +reactor.run() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/nextgen.py python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/nextgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/nextgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/nextgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,80 @@ +# GETNEXT Command Generator +from twisted.internet import reactor, defer +from pysnmp.entity import engine, config +from pysnmp.carrier.twisted import dispatch +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.entity.rfc3413.twisted import cmdgen +from pyasn1.type import univ + +snmpEngine = engine.SnmpEngine() + +# Set Twisted dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' + ) + +# Transport params +config.addTargetParams(snmpEngine, 'myParams', 'test-user', 'authPriv') +#config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 1) + +# Transport addresses +config.addTargetAddr( + snmpEngine, 'myRouter', config.snmpUDPDomain, + ('127.0.0.1', 161), 'myParams' + ) + +# Transport +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTwistedTransport().openClientMode() + ) + +# Twisted API follows + +def receiveResponse(cbCtx): + (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx + if errorIndication: + print('Error: %s' % errorIndication) + reactor.stop() + return + if errorStatus and errorStatus != 2: + 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())) + + for o, v in varBindTable[-1]: + if not isinstance(v, univ.Null): + break + else: + reactor.stop() # no more objects available + return + + df = defer.Deferred() + df.addCallback(receiveResponse) + return df # this is to indicate that we wish to continue walking + +nextCmdGen = cmdgen.NextCommandGenerator() + +df = nextCmdGen.sendReq( + snmpEngine, 'myRouter', (((1,3,6,1,2,1,1), None),) + ) + +df.addCallback(receiveResponse) + +reactor.run() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/ntfrcv.py python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/ntfrcv.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/ntfrcv.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/ntfrcv.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,50 @@ +# Notification Receiver (TRAP/INFORM) +from twisted.internet import reactor +from pysnmp.entity import engine, config +from pysnmp.carrier.twisted import dispatch +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.entity.rfc3413 import ntfrcv + +# Create SNMP engine with autogenernated engineID and pre-bound +# to socket transport dispatcher +snmpEngine = engine.SnmpEngine() + +# Set Twisted dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' + ) + +# Transport +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 162)) + ) + +# Callback function for receiving notifications +def cbFun(snmpEngine, + stateReference, + contextEngineId, contextName, + varBinds, + cbCtx): + transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) + 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())) + +# Apps registration +ntfrcv.NotificationReceiver(snmpEngine, cbFun) + +reactor.run() diff -Nru python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/setgen.py python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/setgen.py --- python-pysnmp4-4.1.9a/examples/v3arch/twisted/manager/setgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/examples/v3arch/twisted/manager/setgen.py 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,69 @@ +# SET Command Generator +from twisted.internet import reactor, defer +from pysnmp.entity import engine, config +from pysnmp.carrier.twisted import dispatch +from pysnmp.carrier.twisted.dgram import udp +from pysnmp.entity.rfc3413.twisted import cmdgen +from pysnmp.proto import rfc1902 + +snmpEngine = engine.SnmpEngine() + +# Set Twisted dispatcher +snmpEngine.registerTransportDispatcher(dispatch.TwistedDispatcher()) + +# v1/2 setup +config.addV1System(snmpEngine, 'test-agent', 'public') + +# v3 setup +config.addV3User( + snmpEngine, 'test-user', + config.usmHMACMD5AuthProtocol, 'authkey1', + config.usmDESPrivProtocol, 'privkey1' + ) + +# Transport params +config.addTargetParams(snmpEngine, 'myParams', 'test-user', 'authPriv') +#config.addTargetParams(snmpEngine, 'myParams', 'test-agent', 'noAuthNoPriv', 1) + +# Transport addresses +config.addTargetAddr( + snmpEngine, 'myRouter', config.snmpUDPDomain, + ('127.0.0.1', 161), 'myParams' + ) + +# Transport +config.addSocketTransport( + snmpEngine, + udp.domainName, + udp.UdpTwistedTransport().openClientMode() + ) + +# Twisted API follows + +def receiveResponse(cbCtx): + (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx + if errorIndication: + print('Error: %s' % errorIndication) + reactor.stop() + return + if errorStatus: + print('Error: %s at %s' % (errorStatus.prettyPrint(), errorIndex)) + reactor.stop() + return + for oid, val in varBinds: + if val is None: + print(oid.prettyPrint()) + else: + print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) + reactor.stop() + +getCmdGen = cmdgen.SetCommandGenerator() + +df = getCmdGen.sendReq( + snmpEngine, 'myRouter', + (((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('Grinch')),) + ) + +df.addCallback(receiveResponse) + +reactor.run() diff -Nru python-pysnmp4-4.1.9a/LICENSE python-pysnmp4-4.2.2/LICENSE --- python-pysnmp4-4.1.9a/LICENSE 2007-11-28 09:20:14.000000000 +0000 +++ python-pysnmp4-4.2.2/LICENSE 2012-02-14 11:56:56.000000000 +0000 @@ -1,4 +1,4 @@ -Copyright (c) 1999-2007, Ilya Etingof , all rights reserved. +Copyright (c) 1999-2012, Ilya Etingof , all rights reserved. THIS SOFTWARE IS NOT FAULT TOLERANT AND SHOULD NOT BE USED IN ANY SITUATION ENDANGERING HUMAN LIFE OR PROPERTY. diff -Nru python-pysnmp4-4.1.9a/MANIFEST python-pysnmp4-4.2.2/MANIFEST --- python-pysnmp4-4.1.9a/MANIFEST 2007-07-09 13:39:47.000000000 +0000 +++ python-pysnmp4-4.2.2/MANIFEST 1970-01-01 00:00:00.000000000 +0000 @@ -1,138 +0,0 @@ -MANIFEST -CHANGES -LICENSE -README -THANKS -docs/mibs/PYSNMP-MIB.txt -docs/mibs/PYSNMP-USM-MIB.txt -docs/pysnmp-arch.gif -docs/pysnmp-tutorial.html -examples/smi/backend.py -examples/smi/instrum.py -examples/smi/view.py -examples/v1arch/agent/cmdrsp.py -examples/v1arch/agent/ntforg.py -examples/v1arch/manager/getgen.py -examples/v1arch/manager/nextgen.py -examples/v1arch/manager/setgen.py -examples/v1arch/manager/ntfrcv.py -examples/v3arch/agent/cmdrsp.py -examples/v3arch/agent/ntforg.py -examples/v3arch/manager/bulkgen.py -examples/v3arch/manager/getgen.py -examples/v3arch/manager/nextgen.py -examples/v3arch/manager/setgen.py -examples/v3arch/manager/ntfrcv.py -examples/v3arch/oneliner/manager/nextgen.py -examples/v3arch/oneliner/manager/getgen.py -examples/v3arch/oneliner/manager/bulkgen.py -examples/v3arch/oneliner/manager/async/nextgen.py -examples/v3arch/oneliner/manager/withmib/nextgen.py -examples/v3arch/oneliner/manager/withmib/setgen.py -examples/v3arch/oneliner/manager/setgen.py -examples/v3arch/oneliner/agent/ntforg.py -pysnmp/__init__.py -pysnmp/v4/debug.py -pysnmp/v4/smi/mibs/ASN1.py -pysnmp/v4/smi/mibs/PYSNMP-MIB.py -pysnmp/v4/smi/mibs/PYSNMP-USM-MIB.py -pysnmp/v4/smi/mibs/RFC1155-SMI.py -pysnmp/v4/smi/mibs/RFC1213-MIB.py -pysnmp/v4/smi/mibs/SNMP-COMMUNITY-MIB.py -pysnmp/v4/smi/mibs/SNMP-FRAMEWORK-MIB.py -pysnmp/v4/smi/mibs/SNMP-MPD-MIB.py -pysnmp/v4/smi/mibs/SNMP-NOTIFICATION-MIB.py -pysnmp/v4/smi/mibs/SNMP-TARGET-MIB.py -pysnmp/v4/smi/mibs/SNMP-USER-BASED-SM-MIB.py -pysnmp/v4/smi/mibs/SNMP-USM-AES-MIB.py -pysnmp/v4/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py -pysnmp/v4/smi/mibs/SNMPv2-CONF.py -pysnmp/v4/smi/mibs/SNMPv2-MIB.py -pysnmp/v4/smi/mibs/SNMPv2-SMI.py -pysnmp/v4/smi/mibs/SNMPv2-TC.py -pysnmp/v4/smi/mibs/SNMPv2-TM.py -pysnmp/v4/smi/mibs/TRANSPORT-ADDRESS-MIB.py -pysnmp/v4/smi/mibs/__init__.py -pysnmp/v4/smi/mibs/instances/__PYSNMP-USM-MIB.py -pysnmp/v4/smi/mibs/instances/__SNMPv2-MIB.py -pysnmp/v4/smi/mibs/instances/__SNMP-TARGET-MIB.py -pysnmp/v4/smi/mibs/instances/__SNMP-MPD-MIB.py -pysnmp/v4/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py -pysnmp/v4/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py -pysnmp/v4/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py -pysnmp/v4/smi/mibs/instances/__init__.py -pysnmp/v4/smi/__init__.py -pysnmp/v4/smi/builder.py -pysnmp/v4/smi/error.py -pysnmp/v4/smi/exval.py -pysnmp/v4/smi/indices.py -pysnmp/v4/smi/instrum.py -pysnmp/v4/smi/view.py -pysnmp/v4/__init__.py -pysnmp/v4/error.py -pysnmp/v4/carrier/asynsock/dgram/__init__.py -pysnmp/v4/carrier/asynsock/dgram/base.py -pysnmp/v4/carrier/asynsock/dgram/udp.py -pysnmp/v4/carrier/asynsock/dgram/unix.py -pysnmp/v4/carrier/asynsock/__init__.py -pysnmp/v4/carrier/asynsock/base.py -pysnmp/v4/carrier/asynsock/dispatch.py -pysnmp/v4/carrier/__init__.py -pysnmp/v4/carrier/base.py -pysnmp/v4/carrier/error.py -pysnmp/v4/entity/rfc3413/__init__.py -pysnmp/v4/entity/rfc3413/cmdgen.py -pysnmp/v4/entity/rfc3413/cmdrsp.py -pysnmp/v4/entity/rfc3413/oneliner/cmdgen.py -pysnmp/v4/entity/rfc3413/oneliner/__init__.py -pysnmp/v4/entity/rfc3413/oneliner/ntforg.py -pysnmp/v4/entity/rfc3413/mibvar.py -pysnmp/v4/entity/rfc3413/ntforg.py -pysnmp/v4/entity/rfc3413/context.py -pysnmp/v4/entity/rfc3413/ntfrcv.py -pysnmp/v4/entity/rfc3413/config.py -pysnmp/v4/entity/__init__.py -pysnmp/v4/entity/config.py -pysnmp/v4/entity/engine.py -pysnmp/v4/proto/acmod/__init__.py -pysnmp/v4/proto/acmod/rfc3415.py -pysnmp/v4/proto/__init__.py -pysnmp/v4/proto/error.py -pysnmp/v4/proto/rfc1155.py -pysnmp/v4/proto/rfc1157.py -pysnmp/v4/proto/rfc1902.py -pysnmp/v4/proto/rfc1905.py -pysnmp/v4/proto/rfc3411.py -pysnmp/v4/proto/rfc3412.py -pysnmp/v4/proto/api/__init__.py -pysnmp/v4/proto/api/v1.py -pysnmp/v4/proto/api/v2c.py -pysnmp/v4/proto/api/verdec.py -pysnmp/v4/proto/mpmod/__init__.py -pysnmp/v4/proto/mpmod/base.py -pysnmp/v4/proto/mpmod/rfc2576.py -pysnmp/v4/proto/mpmod/rfc3412.py -pysnmp/v4/proto/secmod/rfc3414/auth/__init__.py -pysnmp/v4/proto/secmod/rfc3414/auth/base.py -pysnmp/v4/proto/secmod/rfc3414/auth/hmacmd5.py -pysnmp/v4/proto/secmod/rfc3414/auth/hmacsha.py -pysnmp/v4/proto/secmod/rfc3414/auth/noauth.py -pysnmp/v4/proto/secmod/rfc3414/priv/__init__.py -pysnmp/v4/proto/secmod/rfc3414/priv/base.py -pysnmp/v4/proto/secmod/rfc3414/priv/des.py -pysnmp/v4/proto/secmod/rfc3414/priv/nopriv.py -pysnmp/v4/proto/secmod/rfc3414/__init__.py -pysnmp/v4/proto/secmod/rfc3414/localkey.py -pysnmp/v4/proto/secmod/rfc3414/service.py -pysnmp/v4/proto/secmod/rfc3826/priv/aes.py -pysnmp/v4/proto/secmod/rfc3826/priv/__init__.py -pysnmp/v4/proto/secmod/rfc3826/__init__.py -pysnmp/v4/proto/secmod/__init__.py -pysnmp/v4/proto/secmod/base.py -pysnmp/v4/proto/secmod/rfc2576.py -pysnmp/v4/proto/proxy/__init__.py -pysnmp/v4/proto/proxy/rfc2576.py -tools/libsmi2pysnmp -tools/build-pysnmp-mib -TODO -setup.py diff -Nru python-pysnmp4-4.1.9a/MANIFEST.in python-pysnmp4-4.2.2/MANIFEST.in --- python-pysnmp4-4.1.9a/MANIFEST.in 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/MANIFEST.in 2011-11-07 07:50:44.000000000 +0000 @@ -0,0 +1,4 @@ +include CHANGES README LICENSE THANKS +recursive-include examples *.py +recursive-include tools build-pysnmp-mib libsmi2pysnmp +recursive-include docs *.txt *.html *.gif diff -Nru python-pysnmp4-4.1.9a/PKG-INFO python-pysnmp4-4.2.2/PKG-INFO --- python-pysnmp4-4.1.9a/PKG-INFO 2007-11-28 12:18:36.000000000 +0000 +++ python-pysnmp4-4.2.2/PKG-INFO 2012-04-21 09:48:08.000000000 +0000 @@ -1,10 +1,23 @@ Metadata-Version: 1.0 Name: pysnmp -Version: 4.1.9a -Summary: SNMP framework for Python +Version: 4.2.2 +Summary: SNMP framework Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof -Author-email: ilya@glas.net +Author-email: ilya@glas.net License: BSD Description: UNKNOWN Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: Telecommunications Industry +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Security +Classifier: Topic :: Communications +Classifier: Topic :: System :: Monitoring +Classifier: Topic :: System :: Networking :: Monitoring +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: License :: OSI Approved :: BSD License diff -Nru python-pysnmp4-4.1.9a/pysnmp/cache.py python-pysnmp4-4.2.2/pysnmp/cache.py --- python-pysnmp4-4.1.9a/pysnmp/cache.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/cache.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,36 @@ +# Limited-size dictionary class to use for caches + +class Cache: + def __init__(self, maxSize=256): + self.__maxSize = maxSize + self.__size = 0 + self.__chopSize = maxSize//10 + self.__chopSize = self.__chopSize and self.__chopSize or 1 + self.__cache = {} + self.__usage = {} + + def __contains__(self, k): return k in self.__cache + + def __getitem__(self, k): + self.__usage[k] = self.__usage[k] + 1 + return self.__cache[k] + + def __len__(self): return self.__size + + def __setitem__(self, k, v): + if self.__size >= self.__maxSize: + 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] = 0 + self.__cache[k] = v + + def __delitem__(self, k): + del self.__cache[k] + del self.__usage[k] + self.__size = self.__size - 1 diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/base.py python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/base.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/base.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,62 @@ +"""Defines standard API to asyncore-based transport""" +import socket, sys +import asyncore +from pysnmp.carrier import error + +class AbstractSocketTransport(asyncore.dispatcher): + sockFamily = sockType = None + retryCount = 0; retryInterval = 0 + def __init__(self, sock=None, sockMap=None): + if sock is None: + if self.sockFamily is None: + raise error.CarrierError( + 'Address family %s not supported' % self.__class__.__name__ + ) + if self.sockType is None: + raise error.CarrierError( + 'Socket type %s not supported' % self.__class__.__name__ + ) + try: + sock = socket.socket(self.sockFamily, self.sockType) + except socket.error: + 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 + # socket map to avoid registering with deafult asyncore map. + sockMap = {} + asyncore.dispatcher.__init__(self, sock, sockMap) + + def registerSocket(self, sockMap=None): + self.add_channel(sockMap) + + def unregisterSocket(self, sockMap=None): + self.del_channel(sockMap) + + # Public API + + def openClientMode(self, iface=None): + raise error.CarrierError('Method not implemented') + + def openServerMode(self, iface=None): + raise error.CarrierError('Method not implemented') + + def sendMessage(self, outgoingMessage, transportAddress): + raise error.CarrierError('Method not implemented') + + def registerCbFun(self, cbFun): + self._cbFun = cbFun + + def unregisterCbFun(self): + self._cbFun = None + + def closeTransport(self): + self.unregisterCbFun() + self.close() + + # asyncore API + def handle_close(self): raise error.CarrierError( + 'Transport unexpectedly closed' + ) + def handle_error(self): raise + diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/base.py python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/base.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/base.py 2012-04-16 20:46:52.000000000 +0000 @@ -0,0 +1,82 @@ +"""Implements asyncore-based generic DGRAM transport""" +import socket, errno, sys +from pysnmp.carrier.asynsock.base import AbstractSocketTransport +from pysnmp.carrier import error +from pysnmp import debug + +sockErrors = { # Ignore these socket errors + errno.ESHUTDOWN: 1, + errno.ENOTCONN: 1, + errno.ECONNRESET: 0, + errno.ECONNREFUSED: 0, + errno.EAGAIN: 0, + errno.EWOULDBLOCK: 0 + } +try: + # bad FD may happen upon FD closure on n-1 select() event + sockErrors[errno.EBADFD] = 1 +except AttributeError: + # Windows sockets do not have EBADFD + pass + +class DgramSocketTransport(AbstractSocketTransport): + sockType = socket.SOCK_DGRAM + retryCount = 3; retryInterval = 1 + def __init__(self, sock=None, sockMap=None): + self.__outQueue = [] + AbstractSocketTransport.__init__(self, sock, sockMap) + + def openClientMode(self, iface=None): + if iface is not None: + try: + self.socket.bind(iface) + 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: + raise error.CarrierError('bind() failed: %s' % (sys.exc_info()[1],)) + self._iface = iface + return self + + def sendMessage(self, outgoingMessage, transportAddress): + self.__outQueue.append( + (outgoingMessage, transportAddress) + ) + + # asyncore API + def handle_connect(self): pass + def writable(self): return self.__outQueue + def handle_write(self): + outgoingMessage, transportAddress = self.__outQueue.pop() + debug.logger & debug.flagIO and debug.logger('handle_write: transportAddress %r outgoingMessage %r' % (transportAddress, outgoingMessage)) + try: + self.socket.sendto(outgoingMessage, transportAddress) + except socket.error: + if sys.exc_info()[1].args[0] in sockErrors: + debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (sys.exc_info()[1],)) + else: + raise socket.error(sys.exc_info()[1]) + + def readable(self): return 1 + def handle_read(self): + try: + incomingMessage, transportAddress = self.socket.recvfrom(65535) + debug.logger & debug.flagIO and debug.logger('handle_read: transportAddress %r incomingMessage %r' % (transportAddress, incomingMessage)) + if not incomingMessage: + self.handle_close() + return + else: + self._cbFun(self, transportAddress, incomingMessage) + return + except socket.error: + if sys.exc_info()[1].args[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].args[0]] and self.handle_close() + return + else: + raise socket.error(sys.exc_info()[1]) + def handle_close(self): pass # no datagram connection diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/udp6.py python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/udp6.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/udp6.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/udp6.py 2010-01-13 18:15:46.000000000 +0000 @@ -0,0 +1,13 @@ +"""Implements asyncore-based UDP6 transport domain""" +try: + from socket import AF_INET6 +except: + AF_INET6 = None +from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport + +domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2) + +class Udp6SocketTransport(DgramSocketTransport): + sockFamily = AF_INET6 + +Udp6Transport = Udp6SocketTransport diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/udp.py python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/udp.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/udp.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/udp.py 2009-05-18 17:29:50.000000000 +0000 @@ -0,0 +1,10 @@ +"""Implements asyncore-based UDP transport domain""" +from socket import AF_INET +from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport + +domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) + +class UdpSocketTransport(DgramSocketTransport): + sockFamily = AF_INET + +UdpTransport = UdpSocketTransport diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/unix.py python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/unix.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dgram/unix.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dgram/unix.py 2009-05-18 16:33:24.000000000 +0000 @@ -0,0 +1,21 @@ +"""Implements asyncore-based UNIX transport domain""" +from os import remove +from socket import AF_UNIX +from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport + +domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) + +class UnixSocketTransport(DgramSocketTransport): + sockFamily = AF_UNIX + + def closeTransport(self): + DgramSocketTransport.closeTransport(self) + try: + remove(self._iface) + except: + pass + +UnixTransport = UnixSocketTransport + +# Compatibility stub +UnixDgramSocketTransport = UnixSocketTransport diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dispatch.py python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dispatch.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/asynsock/dispatch.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/asynsock/dispatch.py 2011-01-20 17:13:20.000000000 +0000 @@ -0,0 +1,34 @@ +from time import time +from select import select +from asyncore import socket_map +from pysnmp.carrier.base import AbstractTransportDispatcher +from asyncore import poll + +class AsynsockDispatcher(AbstractTransportDispatcher): + """Implements I/O over asynchronous sockets""" + def __init__(self): + self.__sockMap = {} # use own map for MT safety + self.timeout = 0.5 + AbstractTransportDispatcher.__init__(self) + + def getSocketMap(self): return self.__sockMap + def setSocketMap(self, sockMap=socket_map): self.__sockMap = sockMap + + def registerTransport(self, tDomain, t): + AbstractTransportDispatcher.registerTransport(self, tDomain, t) + t.registerSocket(self.__sockMap) + + def unregisterTransport(self, tDomain): + self.getTransport(tDomain).unregisterSocket(self.__sockMap) + AbstractTransportDispatcher.unregisterTransport(self, tDomain) + + def transportsAreWorking(self): + for transport in self.__sockMap.values(): + if transport.writable(): + return 1 + return 0 + + def runDispatcher(self, timeout=0.0): + while self.jobsArePending() or self.transportsAreWorking(): + poll(timeout and timeout or self.timeout, self.__sockMap) + self.handleTimerTick(time()) diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/base.py python-pysnmp4-4.2.2/pysnmp/carrier/base.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/base.py 2011-12-07 17:10:09.000000000 +0000 @@ -0,0 +1,154 @@ +"""Abstract I/O dispatcher. Defines standard dispatcher API""" +from pysnmp.carrier import error + +class TimerCallable: + def __init__(self, cbFun, callInterval): + self.__cbFun = cbFun + self.__callInterval = callInterval + self.__nextCall = 0 + + def __call__(self, timeNow): + if self.__nextCall <= timeNow: + self.__cbFun(timeNow) + self.__nextCall = timeNow + self.__callInterval + + 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): + self.__transports = {} + self.__jobs = {} + self.__recvCbFun = None + self.__timerCallables = [] + self.__ticks = 0 + self.__timerResolution = 0.5 + self.__nextTime = 0 + + def _cbFun(self, incomingTransport, transportAddress, incomingMessage): + for name, transport in self.__transports.items(): + if transport is incomingTransport: + transportDomain = name + break + else: + raise error.CarrierError( + 'Unregistered transport %s' % (incomingTransport,) + ) + if self.__recvCbFun is None: + raise error.CarrierError( + 'Receive callback not registered -- loosing incoming event' + ) + self.__recvCbFun( + self, transportDomain, transportAddress, incomingMessage + ) + + # Dispatcher API + + def registerRecvCbFun(self, recvCbFun): + if self.__recvCbFun is not None: + raise error.CarrierError( + 'Receive callback already registered: %s' % self.__recvCbFun + ) + self.__recvCbFun = recvCbFun + + def unregisterRecvCbFun(self): + self.__recvCbFun = None + + def registerTimerCbFun(self, timerCbFun, tickInterval=None): + if not tickInterval: + tickInterval = self.__timerResolution + self.__timerCallables.append(TimerCallable(timerCbFun, tickInterval)) + + def unregisterTimerCbFun(self, timerCbFun=None): + if timerCbFun is None: + self.__timerCallables = [] + else: + self.__timerCallables.remove(timerCbFun) + + def registerTransport(self, tDomain, transport): + if tDomain in self.__transports: + raise error.CarrierError( + 'Transport %s already registered' % (tDomain,) + ) + transport.registerCbFun(self._cbFun) + self.__transports[tDomain] = transport + + def unregisterTransport(self, tDomain): + if tDomain not in self.__transports: + raise error.CarrierError( + 'Transport %s not registered' % (tDomain,) + ) + self.__transports[tDomain].unregisterCbFun() + del self.__transports[tDomain] + + def getTransport(self, transportDomain): + if transportDomain in self.__transports: + return self.__transports[transportDomain] + raise error.CarrierError( + 'Transport %s not registered' % (transportDomain,) + ) + + def sendMessage( + self, outgoingMessage, transportDomain, transportAddress + ): + if transportDomain in self.__transports: + self.__transports[transportDomain].sendMessage( + outgoingMessage, transportAddress + ) + else: + raise error.CarrierError( + 'No suitable transport domain for %s' % (transportDomain,) + ) + + def getTimerResolution(self): + return self.__timerResolution + def setTimerResolution(self, timerResolution): + if timerResolution < 0.01 or timerResolution > 10: + raise error.CarrierError('Impossible timer resolution') + self.__timerResolution = timerResolution + + def getTimerTicks(self): return self.__ticks + + def handleTimerTick(self, timeNow): + if self.__nextTime == 0: # initial initialization + self.__nextTime = timeNow + self.__timerResolution + + if self.__nextTime > timeNow: + return + + self.__ticks += 1 + self.__nextTime = timeNow + self.__timerResolution + + for timerCallable in self.__timerCallables: + timerCallable(timeNow) + + def jobStarted(self, jobId): + if jobId in self.__jobs: + self.__jobs[jobId] = self.__jobs[jobId] + 1 + else: + self.__jobs[jobId] = 1 + + def jobFinished(self, jobId): + self.__jobs[jobId] = self.__jobs[jobId] - 1 + if self.__jobs[jobId] == 0: + del self.__jobs[jobId] + + def jobsArePending(self): + if self.__jobs: + return 1 + else: + return 0 + + def runDispatcher(self, timeout=0.0): + raise error.CarrierError('Method not implemented') + + def closeDispatcher(self): + for tDomain in list(self.__transports): + self.__transports[tDomain].closeTransport() + self.unregisterTransport(tDomain) + self.unregisterRecvCbFun() + self.unregisterTimerCbFun() diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/error.py python-pysnmp4-4.2.2/pysnmp/carrier/error.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/error.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/error.py 2005-06-14 09:56:02.000000000 +0000 @@ -0,0 +1,3 @@ +from pysnmp import error + +class CarrierError(error.PySnmpError): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/base.py python-pysnmp4-4.2.2/pysnmp/carrier/twisted/base.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/twisted/base.py 2009-07-31 19:55:04.000000000 +0000 @@ -0,0 +1,26 @@ +# +# Copyright (C) 2008 Truelite Srl +# Author: Filippo Giunchedi +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License Version 2 +# as published by the Free Software Foundation +# +# Description: twisted DatagramProtocol UDP transport +# + +class AbstractTwistedTransport: + """Base Twisted Transport, to be used with TwistedDispatcher""" + def __init__(self): + self._writeQ = [] + + # AbstractTwistedTransport API + + def registerCbFun(self, cbFun): + self._cbFun = cbFun + + def unregisterCbFun(self): + self._cbFun = None + + def closeTransport(self): + self.unregisterCbFun() diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dgram/base.py python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dgram/base.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dgram/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dgram/base.py 2011-11-08 14:38:04.000000000 +0000 @@ -0,0 +1,44 @@ +"""Implements twisted-based generic DGRAM transport""" +import sys +from twisted.internet.protocol import DatagramProtocol +from twisted.internet import reactor +from pysnmp.carrier.twisted.base import AbstractTwistedTransport +from pysnmp.carrier import error +from pysnmp import debug + +class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport): + """Base Twisted datagram Transport, to be used with TwistedDispatcher""" + + # Twisted Datagram API + + def datagramReceived(self, datagram, address): + if self._cbFun is None: + raise error.CarrierError('Unable to call cbFun') + else: + # Callback fun is called through callLater() in attempt + # to make Twisted timed calls work under high load. + reactor.callLater(0, self._cbFun, self, address, datagram) + + def startProtocol(self): + debug.logger & debug.flagIO and debug.logger('startProtocol: invoked') + while self._writeQ: + outgoingMessage, transportAddress = self._writeQ.pop(0) + debug.logger & debug.flagIO and debug.logger('startProtocol: transportAddress %r outgoingMessage %r' % (transportAddress, outgoingMessage)) + try: + self.transport.write(outgoingMessage, transportAddress) + except Exception: + raise error.CarrierError('Twisted exception: %s' % (sys.exc_info()[1],)) + + def stopProtocol(self): + debug.logger & debug.flagIO and debug.logger('stopProtocol: invoked') + self.closeTransport() + + def sendMessage(self, outgoingMessage, transportAddress): + debug.logger & debug.flagIO and debug.logger('startProtocol: %s transportAddress %r outgoingMessage %r' % ((self.transport is None and "queuing" or "sending"), transportAddress, outgoingMessage)) + if self.transport is None: + self._writeQ.append((outgoingMessage, transportAddress)) + else: + try: + self.transport.write(outgoingMessage, transportAddress) + except Exception: + raise error.CarrierError('Twisted exception: %s' % (sys.exc_info()[1],)) diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dgram/udp.py python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dgram/udp.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dgram/udp.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dgram/udp.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,26 @@ +"""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 + +domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) + +class UdpTwistedTransport(DgramTwistedTransport): + # AbstractTwistedTransport API + + def openClientMode(self, iface=''): + try: + self._lport = reactor.listenUDP(0, self, iface) + 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: + raise error.CarrierError(sys.exc_info()[1]) + return self + +UdpTransport = UdpTwistedTransport diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dgram/unix.py python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dgram/unix.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dgram/unix.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dgram/unix.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,27 @@ +"""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 + +domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) + +class UnixTwistedTransport(DgramTwistedTransport): + # AbstractTwistedTransport API + + def openClientMode(self, iface=''): + try: + self._lport = reactor.connectUNIXDatagram(iface, self) + 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: + raise error.CarrierError(sys.exc_info()[1]) + + return self + +UnixTransport = UnixTwistedTransport diff -Nru python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dispatch.py python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dispatch.py --- python-pysnmp4-4.1.9a/pysnmp/carrier/twisted/dispatch.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/carrier/twisted/dispatch.py 2011-11-30 15:55:57.000000000 +0000 @@ -0,0 +1,56 @@ +# +# Copyright (C) 2008 Truelite Srl +# Author: Filippo Giunchedi +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License Version 2 +# as published by the Free Software Foundation +# +# Description: Transport dispatcher based on twisted.internet.reactor +# +import sys, time +from twisted.internet import reactor, task +from pysnmp.carrier.base import AbstractTransportDispatcher +from pysnmp.carrier import error + +class TwistedDispatcher(AbstractTransportDispatcher): + """TransportDispatcher based on twisted.internet.reactor""" + def __init__(self, *args, **kwargs): + AbstractTransportDispatcher.__init__(self) + self.__transportCount = 0 + if 'timeout' in kwargs: + self.setTimerResolution(kwargs['timeout']) + else: + self.setTimerResolution(1.0) + self.loopingcall = task.LoopingCall(self.handleTimeout) + + def handleTimeout(self): + self.handleTimerTick(time.time()) + + def runDispatcher(self, timeout=0.0): + if not reactor.running: + try: + reactor.run() + except Exception: + raise error.CarrierError(sys.exc_info()[1]) + + # jobstarted/jobfinished might be okay as-is + + def registerTransport(self, tDomain, transport): + if not self.loopingcall.running and self.getTimerResolution() > 0: + self.loopingcall.start(self.getTimerResolution(), now = False) + AbstractTransportDispatcher.registerTransport( + self, tDomain, transport + ) + self.__transportCount = self.__transportCount + 1 + + def unregisterTransport(self, tDomain): + t = AbstractTransportDispatcher.getTransport(self, tDomain) + if t is not None: + AbstractTransportDispatcher.unregisterTransport(self, tDomain) + t.closeTransport() + self.__transportCount = self.__transportCount - 1 + + # The last transport has been removed, stop the timeout + if self.__transportCount == 0 and self.loopingcall.running: + self.loopingcall.stop() diff -Nru python-pysnmp4-4.1.9a/pysnmp/debug.py python-pysnmp4-4.2.2/pysnmp/debug.py --- python-pysnmp4-4.1.9a/pysnmp/debug.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/debug.py 2011-01-20 18:20:34.000000000 +0000 @@ -0,0 +1,60 @@ +import sys +from pysnmp import error + +flagNone = 0x0000 +flagIO = 0x0001 +flagDsp = 0x0002 +flagMP = 0x0004 +flagSM = 0x0008 +flagBld = 0x0010 +flagMIB = 0x0020 +flagIns = 0x0040 +flagACL = 0x0080 +flagPrx = 0x0100 +flagApp = 0x0200 +flagAll = 0xffff + +flagMap = { + 'io': flagIO, + 'dsp': flagDsp, + 'msgproc': flagMP, + 'secmod': flagSM, + 'mibbuild': flagBld, + 'mibview': flagMIB, + 'mibinstrum': flagIns, + 'acl': flagACL, + 'proxy': flagPrx, + 'app': flagApp, + 'all': flagAll + } + +class Debug: + defaultPrinter = sys.stderr.write + def __init__(self, *flags): + self._flags = flagNone + self._printer = self.defaultPrinter + for f in flags: + if f not in flagMap: + raise error.PySnmpError('bad debug flag %s' % f) + self._flags = self._flags | flagMap[f] + self('debug category %s enabled' % f) + + def __str__(self): + return 'logger %s, flags %x' % (self._printer, self._flags) + + def __call__(self, msg): + self._printer('DBG: %s\n' % msg) + + def __and__(self, flag): + return self._flags & flag + + def __rand__(self, flag): + return flag & self._flags + +# This will yield false from bitwise and with a flag, and save +# on unnecessary calls +logger = 0 + +def setLogger(l): + global logger + logger = l diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/config.py python-pysnmp4-4.2.2/pysnmp/entity/config.py --- python-pysnmp4-4.1.9a/pysnmp/entity/config.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/config.py 2012-04-13 19:04:59.000000000 +0000 @@ -0,0 +1,626 @@ +# Initial SNMP engine configuration functions. During further operation, +# SNMP engine might be configured remotely (through SNMP). +from pyasn1.compat.octets import null +from pysnmp.carrier.asynsock import dispatch +from pysnmp.carrier.asynsock.dgram import udp, udp6 +try: + from pysnmp.carrier.asynsock.dgram import unix + snmpLocalDomain = unix.snmpLocalDomain +except ImportError: # UNIX-specific -- may not be always available + pass +from pysnmp.proto import rfc3412 +from pysnmp.entity import engine +from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha, noauth +from pysnmp.proto.secmod.rfc3414.priv import des, nopriv +from pysnmp.proto.secmod.rfc3826.priv import aes +from pysnmp.proto.secmod.eso.priv import des3, aes192, aes256 +from pysnmp.smi.error import NotWritableError +from pysnmp import error + +# A shortcut to popular constants + +# Transports +snmpUDPDomain = udp.snmpUDPDomain +snmpUDP6Domain = udp6.snmpUDP6Domain + +# Auth protocol +usmHMACMD5AuthProtocol = hmacmd5.HmacMd5.serviceID +usmHMACSHAAuthProtocol = hmacsha.HmacSha.serviceID +usmNoAuthProtocol = noauth.NoAuth.serviceID + +# Privacy protocol +usmDESPrivProtocol = des.Des.serviceID +usm3DESEDEPrivProtocol = des3.Des3.serviceID +usmAesCfb128Protocol = aes.Aes.serviceID +usmAesCfb192Protocol = aes192.Aes192.serviceID +usmAesCfb256Protocol = aes256.Aes256.serviceID +usmNoPrivProtocol = nopriv.NoPriv.serviceID + +# Auth services +authServices = { + hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), + hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), + noauth.NoAuth.serviceID: noauth.NoAuth() + } + +# Privacy services +privServices = { + des.Des.serviceID: des.Des(), + des3.Des3.serviceID: des3.Des3(), + aes.Aes.serviceID: aes.Aes(), + aes192.Aes192.serviceID: aes192.Aes192(), + aes256.Aes256.serviceID: aes256.Aes256(), + nopriv.NoPriv.serviceID: nopriv.NoPriv() + } + +def __cookV1SystemInfo(snmpEngine, securityName): + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + + snmpCommunityEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') + tblIdx = snmpCommunityEntry.getInstIdFromIndices(securityName) + return snmpCommunityEntry, tblIdx, snmpEngineID + +def addV1System(snmpEngine, securityName, communityName, + contextEngineId=None, contextName=None, + transportTag=None): + snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( + snmpEngine, securityName + ) + + if contextEngineId is None: + contextEngineId = snmpEngineID.syntax + if contextName is None: + contextName = null + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo'), + (snmpCommunityEntry.name + (2,) + tblIdx, communityName), + (snmpCommunityEntry.name + (3,) + tblIdx, securityName), + (snmpCommunityEntry.name + (4,) + tblIdx, contextEngineId), + (snmpCommunityEntry.name + (5,) + tblIdx, contextName), + (snmpCommunityEntry.name + (6,) + tblIdx, transportTag), + (snmpCommunityEntry.name + (7,) + tblIdx, 'nonVolatile')) + ) + +def delV1System(snmpEngine, securityName): + snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( + snmpEngine, securityName + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) + ) + +def __cookV3UserInfo(snmpEngine, securityName, contextEngineId): + if contextEngineId is None: + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID = snmpEngineID.syntax + else: + snmpEngineID = contextEngineId + + usmUserEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') + tblIdx1 = usmUserEntry.getInstIdFromIndices( + snmpEngineID, securityName + ) + + pysnmpUsmSecretEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') + tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) + + return snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 + +def addV3User(snmpEngine, securityName, + authProtocol=usmNoAuthProtocol, authKey=None, + privProtocol=usmNoPrivProtocol, privKey=None, + contextEngineId=None): + ( snmpEngineID, usmUserEntry, tblIdx1, + pysnmpUsmSecretEntry, tblIdx2 ) = __cookV3UserInfo( + snmpEngine, securityName, contextEngineId + ) + + # Load augmenting table before creating new row in base one + pysnmpUsmKeyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') + + # Load clone-from (may not be needed) + zeroDotZero, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((usmUserEntry.name + (13,) + tblIdx1, 'createAndGo'), + (usmUserEntry.name + (3,) + tblIdx1, securityName), + (usmUserEntry.name + (4,) + tblIdx1, zeroDotZero.name), + (usmUserEntry.name + (5,) + tblIdx1, authProtocol), + (usmUserEntry.name + (8,) + tblIdx1, privProtocol)) + ) + + # Localize keys + if authProtocol in authServices: + hashedAuthPassphrase = authServices[authProtocol].hashPassphrase( + authKey and authKey or null + ) + localAuthKey = authServices[authProtocol].localizeKey( + hashedAuthPassphrase, snmpEngineID + ) + else: + raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,)) + + if privProtocol in privServices: + hashedPrivPassphrase = privServices[privProtocol].hashPassphrase( + authProtocol, privKey and privKey or null + ) + localPrivKey = privServices[privProtocol].localizeKey( + authProtocol, hashedPrivPassphrase, snmpEngineID + ) + else: + raise error.PySnmpError( + 'Unknown priv protocol %s' % (privProtocol,) + ) + + # Commit localized keys + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((pysnmpUsmKeyEntry.name + (1,) + tblIdx1, localAuthKey), + (pysnmpUsmKeyEntry.name + (2,) + tblIdx1, localPrivKey), + (pysnmpUsmKeyEntry.name + (3,) + tblIdx1, hashedAuthPassphrase), + (pysnmpUsmKeyEntry.name + (4,) + tblIdx1, hashedPrivPassphrase)) + ) + + # Commit passphrases + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo'), + (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey), + (pysnmpUsmSecretEntry.name + (3,) + tblIdx2, privKey),) + ) + +def delV3User(snmpEngine, securityName, contextEngineId=None): + ( snmpEngineID, usmUserEntry, tblIdx1, + pysnmpUsmSecretEntry, tblIdx2 ) = __cookV3UserInfo( + snmpEngine, securityName, contextEngineId + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) + ) + +def __cookTargetParamsInfo(snmpEngine, name): + snmpTargetParamsEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') + tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) + return snmpTargetParamsEntry, tblIdx + +def addTargetParams( + snmpEngine, + name, + securityName, + securityLevel, + mpModel=3 # 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 + ): + if mpModel == 0: + securityModel = 1 + elif mpModel == 1 or mpModel == 2: + securityModel = 2 + elif mpModel == 3: + securityModel = 3 + else: + raise error.PySnmpError('Unknown MP model %s' % mpModel) + + snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo'), + (snmpTargetParamsEntry.name + (1,) + tblIdx, name), + (snmpTargetParamsEntry.name + (2,) + tblIdx, mpModel), + (snmpTargetParamsEntry.name + (3,) + tblIdx, securityModel), + (snmpTargetParamsEntry.name + (4,) + tblIdx, securityName), + (snmpTargetParamsEntry.name + (5,) + tblIdx, securityLevel)) + ) + +def delTargetParams(snmpEngine, name): + snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo( + snmpEngine, name + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) + ) + +def __cookTargetAddrInfo(snmpEngine, addrName): + snmpTargetAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') + tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) + return snmpTargetAddrEntry, tblIdx + +def addTargetAddr( + snmpEngine, + addrName, + transportDomain, + transportAddress, + params, + timeout=None, + retryCount=None, + tagList=null + ): + snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo( + snmpEngine, addrName + ) + + if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain: + SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + transportAddress = SnmpUDPAddress(transportAddress) + elif transportDomain[:len(snmpUDP6Domain)] == snmpUDP6Domain: + TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + transportAddress = TransportAddressIPv6(transportAddress) + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo'), + (snmpTargetAddrEntry.name + (1,) + tblIdx, addrName), + (snmpTargetAddrEntry.name + (2,) + tblIdx, transportDomain), + (snmpTargetAddrEntry.name + (3,) + tblIdx, transportAddress), + (snmpTargetAddrEntry.name + (4,) + tblIdx, timeout), + (snmpTargetAddrEntry.name + (5,) + tblIdx, retryCount), + # XXX + (snmpTargetAddrEntry.name + (6,) + tblIdx,'%s%s%s' % (addrName, tagList and ' ' or '', tagList)), + (snmpTargetAddrEntry.name + (7,) + tblIdx, params),) + ) + +def delTargetAddr(snmpEngine, addrName): + snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo( + snmpEngine, addrName + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) + ) + +def addSocketTransport(snmpEngine, transportDomain, transport): + """Add transport object to socket dispatcher of snmpEngine""" + if not snmpEngine.transportDispatcher: + snmpEngine.registerTransportDispatcher(dispatch.AsynsockDispatcher()) + snmpEngine.transportDispatcher.registerTransport( + transportDomain, transport + ) + +def delSocketTransport(snmpEngine, transportDomain): + """Unregister transport object at socket dispatcher of snmpEngine""" + if not snmpEngine.transportDispatcher: + return + snmpEngine.transportDispatcher.unregisterTransport(transportDomain) + snmpEngine.unregisterTransportDispatcher() + +# VACM shortcuts + +def addContext(snmpEngine, contextName): + vacmContextEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry' + ) + tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmContextEntry.name + (1,) + tblIdx, contextName),) + ) + +def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): + vacmSecurityToGroupEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' + ) + tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( + securityModel, securityName + ) + return vacmSecurityToGroupEntry, tblIdx + +def addVacmGroup(snmpEngine, groupName, securityModel, securityName): + vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( + snmpEngine, securityModel, securityName + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo'), + (vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), + (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), + (vacmSecurityToGroupEntry.name + (3,) + tblIdx, groupName),) + ) + +def delVacmGroup(snmpEngine, securityModel, securityName): + vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( + snmpEngine, securityModel, securityName + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) + ) + +def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, + securityLevel): + vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' + ) + tblIdx = vacmAccessEntry.getInstIdFromIndices( + groupName, contextName, securityModel, securityLevel + ) + return vacmAccessEntry, tblIdx + +def addVacmAccess(snmpEngine, groupName, contextName, securityModel, + securityLevel, prefix, readView, writeView, notifyView): + vacmAccessEntry, tblIdx = __cookVacmAccessInfo( + snmpEngine, groupName, contextName, securityModel, securityLevel + ) + + addContext(snmpEngine, contextName) # this is leaky + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo'), + (vacmAccessEntry.name + (1,) + tblIdx, contextName), + (vacmAccessEntry.name + (2,) + tblIdx, securityModel), + (vacmAccessEntry.name + (3,) + tblIdx, securityLevel), + (vacmAccessEntry.name + (4,) + tblIdx, prefix), + (vacmAccessEntry.name + (5,) + tblIdx, readView), + (vacmAccessEntry.name + (6,) + tblIdx, writeView), + (vacmAccessEntry.name + (7,) + tblIdx, notifyView),) + ) + +def delVacmAccess(snmpEngine, groupName, contextName, securityModel, + securityLevel): + vacmAccessEntry, tblIdx = __cookVacmAccessInfo( + snmpEngine, groupName, contextName, securityModel, securityLevel + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) + ) + +def __cookVacmViewInfo(snmpEngine, viewName, subTree): + vacmViewTreeFamilyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' + ) + tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices( + viewName, subTree + ) + return vacmViewTreeFamilyEntry, tblIdx + +def addVacmView(snmpEngine, viewName, viewType, subTree, mask): + vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( + snmpEngine, viewName, subTree + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo'), + (vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), + (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), + (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, mask), + (vacmViewTreeFamilyEntry.name + (4,) + tblIdx, viewType),) + ) + +def delVacmView(snmpEngine, viewName, subTree): + vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( + snmpEngine, viewName, subTree + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) + ) + +# VACM simplicity wrappers + +def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): + groupName = 'v-%s-%d' % (hash(securityName), securityModel) + SnmpSecurityLevel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') + securityLevel = SnmpSecurityLevel(securityLevel) + return ( groupName, securityLevel, + 'r' + groupName, 'w' + groupName, 'n' + groupName ) + +def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, + readSubTree=(), writeSubTree=(), notifySubTree=(), + contextName=null): + ( groupName, securityLevel, + readView, writeView, notifyView ) = __cookVacmUserInfo( + snmpEngine, securityModel, securityName, securityLevel, + ) + addVacmGroup( + snmpEngine, groupName, securityModel, securityName + ) + addVacmAccess( + snmpEngine, groupName, contextName, securityModel, securityLevel, 1, + readView, writeView, notifyView + ) + if readSubTree: + addVacmView( + snmpEngine, readView, "included", readSubTree, null, + ) + if writeSubTree: + addVacmView( + snmpEngine, writeView, "included", writeSubTree, null, + ) + if notifySubTree: + addVacmView( + snmpEngine, notifyView, "included", notifySubTree, null, + ) + +def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, + readSubTree=(), writeSubTree=(), notifySubTree=()): + ( groupName, securityLevel, + readView, writeView, notifyView ) = __cookVacmUserInfo( + snmpEngine, securityModel, securityName, securityLevel, + ) + delVacmGroup( + snmpEngine, securityModel, securityName + ) + delVacmAccess( + snmpEngine, groupName, null, securityModel, securityLevel + ) + if readSubTree: + delVacmView( + snmpEngine, readView, readSubTree + ) + if writeSubTree: + delVacmView( + snmpEngine, writeView, writeSubTree + ) + if notifySubTree: + delVacmView( + snmpEngine, notifyView, notifySubTree + ) + +# Obsolete shortcuts for add/delVacmUser() wrappers + +def addRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): + addVacmUser( + snmpEngine, securityModel, securityName, securityLevel, subTree + ) + +def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): + delVacmUser( + snmpEngine, securityModel, securityName, securityLevel, subTree + ) + +def addRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): + addVacmUser( + snmpEngine, securityModel, securityName, securityLevel, + subTree, subTree + ) + +def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): + delVacmUser( + snmpEngine, securityModel, securityName, securityLevel, + subTree, subTree + ) + +def addTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): + addVacmUser( + snmpEngine, securityModel, securityName, securityLevel, + (), (), subTree, + ) + +def delTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): + delVacmUser( + snmpEngine, securityModel, securityName, securityLevel, + (), (), subTree, + ) + +# Notification target setup + +def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, + filterSubtree=None): + snmpNotifyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') + tblIdx1 = snmpNotifyEntry.getInstIdFromIndices( + notificationName + ) + + snmpNotifyFilterProfileEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') + tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices( + paramsName + ) + + profileName = '%s-filter' % hash(notificationName) + + if filterSubtree: + snmpNotifyFilterEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') + tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices( + profileName, filterSubtree + ) + else: + snmpNotifyFilterEntry = tblIdx3 = None + + return ( snmpNotifyEntry, tblIdx1, + snmpNotifyFilterProfileEntry, tblIdx2, profileName, + snmpNotifyFilterEntry, tblIdx3 ) + +def addNotificationTarget(snmpEngine, notificationName, paramsName, + transportTag, notifyType=None, filterSubtree=None, + filterMask=None, filterType=None): + ( snmpNotifyEntry, tblIdx1, + snmpNotifyFilterProfileEntry, tblIdx2, profileName, + snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( + snmpEngine, notificationName, paramsName, filterSubtree + ) + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyEntry.name + (5,) + tblIdx1, 'createAndGo'), + (snmpNotifyEntry.name + (2,) + tblIdx1, transportTag), + (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType),) + ) + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'createAndGo'), + (snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName),) + ) + + if not snmpNotifyFilterEntry: + return + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) + ) + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo'), + (snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), + (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), + (snmpNotifyFilterEntry.name + (3,) + tblIdx3, filterType),) + ) + +def delNotificationTarget(snmpEngine, notificationName, paramsName, + filterSubtree=None): + ( snmpNotifyEntry, tblIdx1, + snmpNotifyFilterProfileEntry, tblIdx2, profileName, + snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( + snmpEngine, notificationName, paramsName, filterSubtree + ) + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) + ) + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) + ) + + if not snmpNotifyFilterEntry: + return + + snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( + ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) + ) + +# rfc3415: A.1 +def setInitialVacmParameters(snmpEngine): + # rfc3415: A.1.1 --> initial-semi-security-configuration + + # rfc3415: A.1.2 + addContext(snmpEngine, "") + + # rfc3415: A.1.3 + addVacmGroup(snmpEngine, "initial", 3, "initial") + + # rfc3415: A.1.4 + addVacmAccess(snmpEngine, "initial", "", 3, "noAuthNoPriv", "exact", + "restricted", None, "restricted") + addVacmAccess(snmpEngine, "initial", "", 3, "authNoPriv", "exact", + "internet", "internet", "internet") + addVacmAccess(snmpEngine, "initial", "", 3, "authPriv", "exact", + "internet", "internet", "internet") + + # rfc3415: A.1.5 (semi-secure) + addVacmView(snmpEngine, "internet", "included", (1,3,6,1),"") + addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,2,1,1),"") + addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,2,1,11),"") + addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,10,2,1),"") + addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,11,2,1),"") + addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,15,1,1),"") diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/engine.py python-pysnmp4-4.2.2/pysnmp/entity/engine.py --- python-pysnmp4-4.1.9a/pysnmp/entity/engine.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/engine.py 2010-12-01 12:50:22.000000000 +0000 @@ -0,0 +1,91 @@ +# SNMP engine +from pysnmp.proto.rfc3412 import MsgAndPduDispatcher +from pysnmp.proto.mpmod.rfc2576 import SnmpV1MessageProcessingModel, \ + SnmpV2cMessageProcessingModel +from pysnmp.proto.mpmod.rfc3412 import SnmpV3MessageProcessingModel +from pysnmp.proto.secmod.rfc2576 import SnmpV1SecurityModel, \ + SnmpV2cSecurityModel +from pysnmp.proto.secmod.rfc3414 import SnmpUSMSecurityModel +from pysnmp.proto.acmod import rfc3415, void +from pysnmp import error + +class SnmpEngine: + def __init__(self, snmpEngineID=None, maxMessageSize=65507, + msgAndPduDsp=None): + if msgAndPduDsp is None: + self.msgAndPduDsp = MsgAndPduDispatcher() + else: + self.msgAndPduDsp = msgAndPduDsp + self.messageProcessingSubsystems = { + SnmpV1MessageProcessingModel.messageProcessingModelID: + SnmpV1MessageProcessingModel(), + SnmpV2cMessageProcessingModel.messageProcessingModelID: + SnmpV2cMessageProcessingModel(), + SnmpV3MessageProcessingModel.messageProcessingModelID: + SnmpV3MessageProcessingModel() + } + self.securityModels = { + SnmpV1SecurityModel.securityModelID: SnmpV1SecurityModel(), + SnmpV2cSecurityModel.securityModelID: SnmpV2cSecurityModel(), + SnmpUSMSecurityModel.securityModelID: SnmpUSMSecurityModel() + } + self.accessControlModel = { + void.accessModelID: void, + rfc3415.accessModelID: rfc3415 + } + + self.transportDispatcher = None + + if self.msgAndPduDsp.mibInstrumController is None: + raise error.PySnmpError( + 'MIB instrumentation does not yet exist' + ) + snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize) + snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') + snmpEngineBoots.syntax = snmpEngineBoots.syntax + 1 + if snmpEngineID is not None: + origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) + + # Transport dispatcher bindings + + def __receiveMessageCbFun( + self, + transportDispatcher, + transportDomain, + transportAddress, + wholeMsg + ): + self.msgAndPduDsp.receiveMessage( + self, transportDomain, transportAddress, wholeMsg + ) + + def __receiveTimerTickCbFun(self, timeNow): + self.msgAndPduDsp.receiveTimerTick(self, timeNow) + for mpHandler in self.messageProcessingSubsystems.values(): + mpHandler.receiveTimerTick(self, timeNow) + for smHandler in self.securityModels.values(): + smHandler.receiveTimerTick(self, timeNow) + + def registerTransportDispatcher(self, transportDispatcher): + if self.transportDispatcher is not None: + raise error.PySnmpError( + 'Transport dispatcher already registered' + ) + transportDispatcher.registerRecvCbFun( + self.__receiveMessageCbFun + ) + transportDispatcher.registerTimerCbFun( + self.__receiveTimerTickCbFun + ) + self.transportDispatcher = transportDispatcher + + def unregisterTransportDispatcher(self): + if self.transportDispatcher is None: + raise error.PySnmpError( + 'Transport dispatcher not registered' + ) + self.transportDispatcher.unregisterRecvCbFun() + self.transportDispatcher.unregisterTimerCbFun() + self.transportDispatcher = None diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/cmdgen.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/cmdgen.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/cmdgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/cmdgen.py 2012-04-14 08:13:35.000000000 +0000 @@ -0,0 +1,629 @@ +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 + +getNextHandle = nextid.Integer(0x7fffffff) + +def getVersionSpecifics(snmpVersion): + if snmpVersion == 0: + pduVersion = 0 + else: + pduVersion = 1 + return pduVersion, api.protoModules[pduVersion] + +__null = univ.Null('') + +def getNextVarBinds(origVarBinds, varBinds): + errorIndication = None + idx = nonNulls = len(varBinds) + rspVarBinds = [] + while idx: + idx = idx - 1 + if isinstance(varBinds[idx][1], univ.Null): + nonNulls = nonNulls - 1 + elif origVarBinds[idx][0].asTuple() >= varBinds[idx][0].asTuple(): + errorIndication = errind.oidNotIncreasing + + rspVarBinds.insert(0, (varBinds[idx][0], __null)) + + if not nonNulls: + rspVarBinds = [] + + return errorIndication, rspVarBinds + +class CommandGeneratorBase: + _null = univ.Null('') + def __init__(self): + self.__pendingReqs = {} + self.__SnmpEngineID, self.__SnmpAdminString = None, None + + def processResponsePdu( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + statusInformation, + sendPduHandle, + cbInfo + ): + (cbFun, cbCtx) = cbInfo + # 3.1.1 + ( origTransportDomain, + origTransportAddress, + origMessageProcessingModel, + origSecurityModel, + origSecurityName, + origSecurityLevel, + origContextEngineId, + origContextName, + origPduVersion, + origPdu, + origTimeout, + origRetryCount, + origRetries, + origSendRequestHandle + ) = self.__pendingReqs[sendPduHandle] + del self.__pendingReqs[sendPduHandle] + + snmpEngine.transportDispatcher.jobFinished(id(self)) + + # 3.1.3 + if statusInformation: + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) + if origRetries == origRetryCount: + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) + cbFun(origSendRequestHandle, + statusInformation['errorIndication'], 0, 0, (), + cbCtx) + return + self._sendPdu( + snmpEngine, + origTransportDomain, + origTransportAddress, + origMessageProcessingModel, + origSecurityModel, + origSecurityName, + origSecurityLevel, + origContextEngineId, + origContextName, + origPduVersion, + origPdu, + origTimeout, + origRetryCount, + origRetries + 1, + origSendRequestHandle, + (self.processResponsePdu, (cbFun, cbCtx)) + ) + return + + if origMessageProcessingModel != messageProcessingModel or \ + origSecurityModel != securityModel or \ + origSecurityName != origSecurityName or \ + origContextEngineId and origContextEngineId != contextEngineId or \ + origContextName and origContextName != contextName or \ + origPduVersion != pduVersion: + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) + cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx) + return + + pMod = api.protoModules[pduVersion] + + # 3.1.2 + if pMod.apiPDU.getRequestID(PDU) != pMod.apiPDU.getRequestID(origPdu): + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle) + cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx) + return + + # User-side API assumes SMIv2 + if messageProcessingModel == 0: + PDU = rfc2576.v1ToV2(PDU, origPdu) + pMod = api.protoModules[api.protoVersion2c] + + self._handleResponse( + snmpEngine, + origTransportDomain, + origTransportAddress, + origMessageProcessingModel, + origSecurityModel, + origSecurityName, + origSecurityLevel, + origContextEngineId, + origContextName, + origPduVersion, + origPdu, + origTimeout, + origRetryCount, + pMod, + PDU, + origSendRequestHandle, + (cbFun, cbCtx), + ) + + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + cbFun, + cbCtx=None, + contextEngineId=None, + contextName='' + ): + raise error.PySnmpError('Method not implemented') + + def _sendPdu( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + timeout, + retryCount, + retries, + sendRequestHandle, + cbInfo + ): + (processResponsePdu, cbCtx) = cbInfo + + # Convert timeout in seconds into timeout in timer ticks + timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + + if not self.__SnmpEngineID or not self.__SnmpAdminString: + self.__SnmpEngineID, self.__SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') + + # Cast possible strings into bytes + if contextEngineId: + contextEngineId = self.__SnmpEngineID(contextEngineId) + contextName = self.__SnmpAdminString(contextName) + + # 3.1 + sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + 1, # expectResponse + timeoutInTicks, + processResponsePdu, + cbCtx + ) + + snmpEngine.transportDispatcher.jobStarted(id(self)) + + debug.logger & debug.flagApp and debug.logger('_sendPdu: sendPduHandle %s, timeout %d, retry %d of %d' % (sendPduHandle, timeout, retries, retryCount)) + + self.__pendingReqs[sendPduHandle] = ( + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + timeout, + retryCount, + retries, + sendRequestHandle, + ) + +class GetCommandGenerator(CommandGeneratorBase): + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + cbFun, + cbCtx=None, + contextEngineId=None, + contextName='' + ): + ( transportDomain, + transportAddress, + timeout, + retryCount, + messageProcessingModel, + securityModel, + securityName, + securityLevel ) = config.getTargetInfo(snmpEngine, addrName) + + pduVersion, pMod = getVersionSpecifics(messageProcessingModel) + + reqPDU = pMod.GetRequestPDU() + pMod.apiPDU.setDefaults(reqPDU) + + pMod.apiPDU.setVarBinds(reqPDU, varBinds) + + requestHandle = getNextHandle() + + self._sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + timeout, + retryCount, + 0, + requestHandle, + (self.processResponsePdu, (cbFun, cbCtx)) + ) + + return requestHandle + + def _handleResponse( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + timeout, + retryCount, + pMod, + rspPDU, + sendRequestHandle, + cbInfo + ): + (cbFun, cbCtx) = cbInfo + cbFun(sendRequestHandle, + None, + pMod.apiPDU.getErrorStatus(rspPDU), + pMod.apiPDU.getErrorIndex(rspPDU), + pMod.apiPDU.getVarBinds(rspPDU), + cbCtx) + +class SetCommandGenerator(CommandGeneratorBase): + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + cbFun, + cbCtx=None, + contextEngineId=None, + contextName='' + ): + ( transportDomain, + transportAddress, + timeout, + retryCount, + messageProcessingModel, + securityModel, + securityName, + securityLevel ) = config.getTargetInfo(snmpEngine, addrName) + + pduVersion, pMod = getVersionSpecifics(messageProcessingModel) + + reqPDU = pMod.SetRequestPDU() + pMod.apiPDU.setDefaults(reqPDU) + + pMod.apiPDU.setVarBinds(reqPDU, varBinds) + + # User-side API assumes SMIv2 + if messageProcessingModel == 0: + reqPDU = rfc2576.v2ToV1(reqPDU) + pMod = api.protoModules[api.protoVersion1] + + requestHandle = getNextHandle() + + self._sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + timeout, + retryCount, + 0, + requestHandle, + (self.processResponsePdu, (cbFun, cbCtx)) + ) + + return requestHandle + + def _handleResponse( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + timeout, + retryCount, + pMod, + rspPDU, + sendRequestHandle, + cbInfo + ): + (cbFun, cbCtx) = cbInfo + cbFun(sendRequestHandle, + None, + pMod.apiPDU.getErrorStatus(rspPDU), + pMod.apiPDU.getErrorIndex(rspPDU), + pMod.apiPDU.getVarBinds(rspPDU), + cbCtx) + +class NextCommandGenerator(CommandGeneratorBase): + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + cbFun, + cbCtx=None, + contextEngineId=None, + contextName='' + ): + ( transportDomain, + transportAddress, + timeout, + retryCount, + messageProcessingModel, + securityModel, + securityName, + securityLevel ) = config.getTargetInfo(snmpEngine, addrName) + + pduVersion, pMod = getVersionSpecifics(messageProcessingModel) + + reqPDU = pMod.GetNextRequestPDU() + pMod.apiPDU.setDefaults(reqPDU) + + pMod.apiPDU.setVarBinds(reqPDU, varBinds) + + requestHandle = getNextHandle() + + self._sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + timeout, + retryCount, + 0, + requestHandle, + (self.processResponsePdu, (cbFun, cbCtx)) + ) + + return requestHandle + + def _handleResponse( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + timeout, + retryCount, + pMod, + rspPDU, + sendRequestHandle, + cbInfo + ): + (cbFun, cbCtx) = cbInfo + varBindTable = pMod.apiPDU.getVarBindTable(PDU, rspPDU) + + if pMod.apiPDU.getErrorStatus(rspPDU): + errorIndication, varBinds = None, () + elif not varBindTable: + errorIndication, varBinds = errind.emptyResponse, () + else: + errorIndication, varBinds = getNextVarBinds( + pMod.apiPDU.getVarBinds(PDU), varBindTable[-1] + ) + + if not cbFun(sendRequestHandle, errorIndication, + pMod.apiPDU.getErrorStatus(rspPDU), + pMod.apiPDU.getErrorIndex(rspPDU), + varBindTable, cbCtx): + debug.logger & debug.flagApp and debug.logger('_handleResponse: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) + return # app says enough + + if not varBinds: + return # no more objects available + + pMod.apiPDU.setRequestID(PDU, pMod.getNextRequestID()) + pMod.apiPDU.setVarBinds(PDU, varBinds) + + self._sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + timeout, + retryCount, + 0, + getNextHandle(), + (self.processResponsePdu, (cbFun, cbCtx)) + ) + +class BulkCommandGenerator(CommandGeneratorBase): + def sendReq( + self, + snmpEngine, + addrName, + nonRepeaters, + maxRepetitions, + varBinds, + cbFun, + cbCtx=None, + contextEngineId=None, + contextName='' + ): + ( transportDomain, + transportAddress, + timeout, + retryCount, + messageProcessingModel, + securityModel, + securityName, + securityLevel ) = config.getTargetInfo(snmpEngine, addrName) + + pduVersion, pMod = getVersionSpecifics(messageProcessingModel) + + if not hasattr(pMod, 'GetBulkRequestPDU'): + raise error.PySnmpError('BULK PDU not implemented at %s' % pMod) + reqPDU = pMod.GetBulkRequestPDU() + pMod.apiBulkPDU.setDefaults(reqPDU) + + pMod.apiBulkPDU.setNonRepeaters(reqPDU, nonRepeaters) + pMod.apiBulkPDU.setMaxRepetitions(reqPDU, maxRepetitions) + + pMod.apiBulkPDU.setVarBinds(reqPDU, varBinds) + + requestHandle = getNextHandle() + + self._sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + reqPDU, + timeout, + retryCount, + 0, + requestHandle, + (self.processResponsePdu, (cbFun, cbCtx)) + ) + + return requestHandle + + def _handleResponse( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + timeout, + retryCount, + pMod, + rspPDU, + sendRequestHandle, + cbInfo + ): + (cbFun, cbCtx) = cbInfo + varBindTable = pMod.apiBulkPDU.getVarBindTable(PDU, rspPDU) + + if pMod.apiBulkPDU.getErrorStatus(rspPDU): + errorIndication, varBinds = None, () + elif not varBindTable: + errorIndication, varBinds = errind.emptyResponse, () + else: + errorIndication, varBinds = getNextVarBinds( + pMod.apiBulkPDU.getVarBinds(PDU), varBindTable[-1] + ) + + if not cbFun(sendRequestHandle, errorIndication, + pMod.apiBulkPDU.getErrorStatus(rspPDU), + pMod.apiBulkPDU.getErrorIndex(rspPDU), + varBindTable, cbCtx): + debug.logger & debug.flagApp and debug.logger('_handleResponse: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) + return # app says enough + + if not varBinds: + return # no more objects available + + pMod.apiBulkPDU.setRequestID(PDU, pMod.getNextRequestID()) + pMod.apiBulkPDU.setVarBinds(PDU, varBinds) + + self._sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + timeout, + retryCount, + 0, + getNextHandle(), + (self.processResponsePdu, (cbFun, cbCtx)) + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/cmdrsp.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/cmdrsp.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/cmdrsp.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/cmdrsp.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,347 @@ +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 +import pysnmp.smi.error +from pysnmp import debug + +# 3.2 +class CommandResponderBase: + acmID = 3 # default MIB access control method to use + pduTypes = () + + def __init__(self, snmpEngine, snmpContext): + snmpEngine.msgAndPduDsp.registerContextEngineId( + snmpContext.contextEngineId, self.pduTypes, self.processPdu + ) + self.snmpContext = snmpContext # for unregistration + self.__pendingReqs = {} + + def handleMgmtOperation( + self, snmpEngine, stateReference, contextName, PDU, acInfo + ): pass + + def close(self, snmpEngine): + snmpEngine.msgAndPduDsp.unregisterContextEngineId( + self.snmpContext.contextEngineId, self.pduTypes + ) + + def sendRsp(self, snmpEngine, stateReference, + errorStatus, errorIndex, varBinds): + ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + origPdu, + maxSizeResponseScopedPDU, + statusInformation ) = self.__pendingReqs[stateReference] + + debug.logger & debug.flagApp and debug.logger('sendRsp: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % (stateReference, errorStatus, errorIndex, varBinds)) + + v2c.apiPDU.setErrorStatus(PDU, errorStatus) + v2c.apiPDU.setErrorIndex(PDU, errorIndex) + v2c.apiPDU.setVarBinds(PDU, varBinds) + + # Agent-side API complies with SMIv2 + if messageProcessingModel == 0: + PDU = rfc2576.v2ToV1(PDU, origPdu) + + # 3.2.6 + try: + snmpEngine.msgAndPduDsp.returnResponsePdu( + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ) + 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 + + _getRequestType = rfc1905.GetRequestPDU.tagSet + _getNextRequestType = rfc1905.GetNextRequestPDU.tagSet + _setRequestType = rfc1905.SetRequestPDU.tagSet + _counter64Type = rfc1902.Counter64.tagSet + + def releaseStateInformation(self, stateReference): + if stateReference in self.__pendingReqs: + del self.__pendingReqs[stateReference] + + def processPdu( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference + ): + + # Agent-side API complies with SMIv2 + if messageProcessingModel == 0: + origPdu = PDU + PDU = rfc2576.v1ToV2(PDU) + else: + origPdu = None + + # 3.2.1 + if PDU.tagSet not in rfc3411.readClassPDUs and \ + PDU.tagSet not in rfc3411.writeClassPDUs: + raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) + + # 3.2.2 --> no-op + + # 3.2.4 + rspPDU = v2c.apiPDU.getResponse(PDU) + + statusInformation = {} + + self.__pendingReqs[stateReference] = ( + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + rspPDU, + origPdu, + maxSizeResponseScopedPDU, + statusInformation + ) + + acCtx = ( + snmpEngine, securityModel, securityName, securityLevel, + contextName, PDU.getTagSet() + ) + + # 3.2.5 + varBinds = v2c.apiPDU.getVarBinds(PDU) + errorStatus, errorIndex = 'noError', 0 + + debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) + + try: + self.handleMgmtOperation( + snmpEngine, stateReference, + contextName, PDU, (self.__verifyAccess, acCtx) + ) + return + # SNMPv2 SMI exceptions + except pysnmp.smi.error.GenError: + errorIndication = sys.exc_info()[1] + debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) + if 'oid' in errorIndication: + # Request REPORT generation + statusInformation['oid'] = errorIndication['oid'] + statusInformation['val'] = errorIndication['val'] + + # PDU-level SMI errors + 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: + self.releaseStateInformation(stateReference) + return + + self.sendRsp( + snmpEngine, stateReference, errorStatus, errorIndex, varBinds + ) + + self.releaseStateInformation(stateReference) + + 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 = sys.exc_info()[1] + debug.logger & debug.flagApp and debug.logger('__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) + errorIndication = statusInformation['errorIndication'] + # 3.2.5... + if errorIndication == errind.noSuchView or \ + errorIndication == errind.noAccessEntry or \ + errorIndication == errind.noGroupName: + raise pysnmp.smi.error.AuthorizationError( + name=name, idx=idx + ) + elif errorIndication == errind.otherError: + raise pysnmp.smi.error.GenError(name=name, idx=idx) + elif errorIndication == errind.noSuchContext: + snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-TARGET-MIB', 'snmpUnknownContexts') + snmpUnknownContexts.syntax = snmpUnknownContexts.syntax + 1 + # Request REPORT generation + raise pysnmp.smi.error.GenError( + name=name, idx=idx, + oid=snmpUnknownContexts.name, + val=snmpUnknownContexts.syntax + ) + elif errorIndication == errind.notInView: + return 1 + else: + raise error.ProtocolError( + 'Unknown ACM error %s' % errorIndication + ) + else: + # rfc2576: 4.1.2.1 + if securityModel == 1 and \ + syntax is not None and \ + self._counter64Type == syntax.getTagSet() and \ + self._getNextRequestType == pduType: + # This will cause MibTree to skip this OID-value + raise pysnmp.smi.error.NoAccessError(name=name, idx=idx) + +class GetCommandResponder(CommandResponderBase): + pduTypes = ( rfc1905.GetRequestPDU.tagSet, ) + + # rfc1905: 4.2.1 + def handleMgmtOperation( + self, snmpEngine, stateReference, contextName, PDU, acInfo + ): + (acFun, acCtx) = acInfo + # rfc1905: 4.2.1.1 + mgmtFun = self.snmpContext.getMibInstrum(contextName).readVars + self.sendRsp( + snmpEngine, stateReference, 0, 0, mgmtFun( + v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) + ) + ) + self.releaseStateInformation(stateReference) + +class NextCommandResponder(CommandResponderBase): + pduTypes = ( rfc1905.GetNextRequestPDU.tagSet, ) + + # rfc1905: 4.2.2 + def handleMgmtOperation( + self, snmpEngine, stateReference, contextName, PDU, acInfo + ): + (acFun, acCtx) = acInfo + # rfc1905: 4.2.2.1 + mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars + varBinds = v2c.apiPDU.getVarBinds(PDU) + while 1: + rspVarBinds = mgmtFun(varBinds, (acFun, acCtx)) + try: + self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds) + except error.StatusInformation: + idx = sys.exc_info()[1]['idx'] + varBinds[idx] = (rspVarBinds[idx][0], varBinds[idx][1]) + else: + break + self.releaseStateInformation(stateReference) + +class BulkCommandResponder(CommandResponderBase): + pduTypes = ( rfc1905.GetBulkRequestPDU.tagSet, ) + maxVarBinds = 64 + + # rfc1905: 4.2.3 + def handleMgmtOperation( + self, snmpEngine, stateReference, contextName, PDU, acInfo + ): + (acFun, acCtx) = acInfo + nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU) + if nonRepeaters < 0: + nonRepeaters = 0 + maxRepetitions = v2c.apiBulkPDU.getMaxRepetitions(PDU) + if maxRepetitions < 0: + maxRepetitions = 0 + + reqVarBinds = v2c.apiPDU.getVarBinds(PDU) + + N = min(int(nonRepeaters), len(reqVarBinds)) + M = int(maxRepetitions) + R = max(len(reqVarBinds)-N, 0) + + if R: M = min(M, self.maxVarBinds/R) + + debug.logger & debug.flagApp and debug.logger('handleMgmtOperation: N %d, M %d, R %d' % (N, M, R)) + + mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars + + if N: + rspVarBinds = mgmtFun(reqVarBinds[:N], (acFun, acCtx)) + else: + rspVarBinds = [] + + varBinds = reqVarBinds[-R:] + while M and R: + rspVarBinds.extend( + mgmtFun(varBinds, (acFun, acCtx)) + ) + varBinds = rspVarBinds[-R:] + M = M - 1 + + if len(rspVarBinds): + self.sendRsp( + snmpEngine, stateReference, 0, 0, rspVarBinds + ) + self.releaseStateInformation(stateReference) + else: + raise pysnmp.smi.error.SmiError() + +class SetCommandResponder(CommandResponderBase): + pduTypes = ( rfc1905.SetRequestPDU.tagSet, ) + + # rfc1905: 4.2.5 + def handleMgmtOperation( + self, snmpEngine, stateReference, contextName, PDU, acInfo + ): + (acFun, acCtx) = acInfo + mgmtFun = self.snmpContext.getMibInstrum(contextName).writeVars + # rfc1905: 4.2.5.1-13 + try: + self.sendRsp( + snmpEngine, stateReference, 0, 0, mgmtFun( + v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) + ) + ) + self.releaseStateInformation(stateReference) + except ( pysnmp.smi.error.NoSuchObjectError, + pysnmp.smi.error.NoSuchInstanceError ): + e = pysnmp.smi.error.NotWritableError() + e.update(sys.exc_info()[1]) + raise e diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/config.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/config.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/config.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/config.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,158 @@ +# Shortcuts to MIB instrumentation items used internally in SNMP applications +from pysnmp.smi.error import SmiError, NoSuchObjectError +from pysnmp.smi.exval import noSuchInstance +from pysnmp.entity import config + +def getTargetAddr(snmpEngine, snmpTargetAddrName): + mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController + # Transport endpoint + snmpTargetAddrEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry' + ) + tblIdx = snmpTargetAddrEntry.getInstIdFromIndices( + snmpTargetAddrName + ) + + ((v, snmpTargetAddrTDomain), + (v, snmpTargetAddrTAddress), + (v, snmpTargetAddrTimeout), + (v, snmpTargetAddrRetryCount), + (v, snmpTargetAddrParams)) = mibInstrumController.readVarsFast( + ((snmpTargetAddrEntry.name + (2,) + tblIdx, None), + (snmpTargetAddrEntry.name + (3,) + tblIdx, None), + (snmpTargetAddrEntry.name + (4,) + tblIdx, None), + (snmpTargetAddrEntry.name + (5,) + tblIdx, None), + (snmpTargetAddrEntry.name + (7,) + tblIdx, None)) + ) + + if noSuchInstance.isSameTypeWith(snmpTargetAddrParams): + raise SmiError('Target %s not configured at SMI' % snmpTargetAddrName) + + if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain: + SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + snmpTargetAddrTAddress = tuple( + SnmpUDPAddress(snmpTargetAddrTAddress) + ) + elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain: + TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + snmpTargetAddrTAddress = tuple( + TransportAddressIPv6(snmpTargetAddrTAddress) + ) + + return ( snmpTargetAddrTDomain, + snmpTargetAddrTAddress, + snmpTargetAddrTimeout, + snmpTargetAddrRetryCount, + snmpTargetAddrParams ) + +def getTargetInfo(snmpEngine, snmpTargetAddrName): + # Transport endpoint + ( snmpTargetAddrTDomain, + snmpTargetAddrTAddress, + snmpTargetAddrTimeout, + snmpTargetAddrRetryCount, + snmpTargetAddrParams ) = getTargetAddr(snmpEngine, snmpTargetAddrName) + + mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController + + # Target params + snmpTargetParamsEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetParamsEntry' + ) + + tblIdx = snmpTargetParamsEntry.getInstIdFromIndices( + snmpTargetAddrParams + ) + ((v, snmpTargetParamsMPModel), + (v, snmpTargetParamsSecurityModel), + (v, snmpTargetParamsSecurityName), + (v, snmpTargetParamsSecurityLevel)) = mibInstrumController.readVarsFast( + ((snmpTargetParamsEntry.name + (2,) + tblIdx, None), + (snmpTargetParamsEntry.name + (3,) + tblIdx, None), + (snmpTargetParamsEntry.name + (4,) + tblIdx, None), + (snmpTargetParamsEntry.name + (5,) + tblIdx, None)) + ) + + if noSuchInstance.isSameTypeWith(snmpTargetParamsSecurityName): + raise SmiError('Parameters %s not configured at SMI' % snmpTargetAddrParams) + + return ( snmpTargetAddrTDomain, + snmpTargetAddrTAddress, + snmpTargetAddrTimeout, + snmpTargetAddrRetryCount, + snmpTargetParamsMPModel, + snmpTargetParamsSecurityModel, + snmpTargetParamsSecurityName, + snmpTargetParamsSecurityLevel ) + +def getTargetParams(snmpEngine, paramsName): + mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController + snmpTargetParamsEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetParamsEntry' + ) + tblIdx = snmpTargetParamsEntry.getInstIdFromIndices( + paramsName + ) + ((v, snmpTargetParamsMPModel), + (v, snmpTargetParamsSecurityModel), + (v, snmpTargetParamsSecurityName), + (v, snmpTargetParamsSecurityLevel)) = mibInstrumController.readVarsFast( + ((snmpTargetParamsEntry.name + (2,) + tblIdx, None), + (snmpTargetParamsEntry.name + (3,) + tblIdx, None), + (snmpTargetParamsEntry.name + (4,) + tblIdx, None), + (snmpTargetParamsEntry.name + (5,) + tblIdx, None)) + ) + + if noSuchInstance.isSameTypeWith(snmpTargetParamsMPModel): + raise SmiError('Parameters %s not configured at SMI' % paramsName) + + return ( snmpTargetParamsMPModel, + snmpTargetParamsSecurityModel, + snmpTargetParamsSecurityName, + snmpTargetParamsSecurityLevel ) + +def getNotificationInfo(snmpEngine, notificationTarget): + mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController + # Transport endpoint + snmpNotifyEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry' + ) + tblIdx = snmpNotifyEntry.getInstIdFromIndices( + notificationTarget + ) + ((v, snmpNotifyTag), + (v, snmpNotifyType)) = mibInstrumController.readVarsFast( + ((snmpNotifyEntry.name + (2,) + tblIdx, None), + (snmpNotifyEntry.name + (3,) + tblIdx, None)) + ) + + if noSuchInstance.isSameTypeWith(snmpNotifyTag): + raise SmiError('Target %s not configured at SMI' % notificationTarget) + + return snmpNotifyTag, snmpNotifyType + +def getTargetNames(snmpEngine, tag): + mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController + # Transport endpoint + ( snmpTargetAddrEntry, + snmpTargetAddrTagList ) = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry', 'snmpTargetAddrTagList' + ) + targetNames = [] + nextName = snmpTargetAddrTagList.name + while 1: + try: + mibNode = snmpTargetAddrTagList.getNextNode(nextName) + except NoSuchObjectError: + break + # XXX stop on eot + if tag in mibNode.syntax.asOctets().split(): # XXX add __split__() + idx = mibNode.name[len(snmpTargetAddrTagList.name):] + targetNames.append( + snmpTargetAddrEntry.getIndicesFromInstId(idx)[0] + ) + nextName = mibNode.name + return targetNames + +# XXX +# convert cmdrsp/cmdgen into this api diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/context.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/context.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/context.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/context.py 2011-11-08 14:55:46.000000000 +0000 @@ -0,0 +1,46 @@ +# SNMP entity context +from pyasn1.type import univ +from pyasn1.compat.octets import null +from pysnmp import error +from pysnmp import debug + +class SnmpContext: + def __init__(self, snmpEngine, contextEngineId=None): + if contextEngineId is None: + # Default to local snmpEngineId + contextEngineId,= snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + contextEngineId = contextEngineId.syntax + self.contextEngineId = contextEngineId + debug.logger & debug.flagIns and debug.logger('SnmpContext: contextEngineId \"%r\"' % (contextEngineId,)) + self.contextNames = { + 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[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( + 'Missing contextName %s' % contextName + ) + else: + debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName \"%s\", mibInstum %s' % (contextName, self.contextNames[contextName])) + return self.contextNames[contextName] diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/mibvar.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/mibvar.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/mibvar.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/mibvar.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,70 @@ +# MIB variable pretty printers/parsers +from pyasn1.type import univ +from pysnmp.smi.error import NoSuchObjectError + +# Name + +def mibNameToOid(mibView, name): + if isinstance(name[0], tuple): + f = lambda x='',y='': (x,y) + modName, symName = f(*name[0]) + if modName: # load module if needed + mibView.mibBuilder.loadModules(modName) + else: + mibView.mibBuilder.loadModules() # load all (slow) + if symName: + oid, label, suffix = mibView.getNodeNameByDesc(symName, modName) + else: + oid, label, suffix = mibView.getFirstNodeName(modName) + suffix = name[1:] + modName, symName, _s = mibView.getNodeLocation(oid) + mibNode, = mibView.mibBuilder.importSymbols( + modName, symName + ) + if hasattr(mibNode, 'createTest'): # table column XXX + modName, symName, _s = mibView.getNodeLocation(oid[:-1]) + rowNode, = mibView.mibBuilder.importSymbols(modName, symName) + return oid, rowNode.getInstIdFromIndices(*suffix) + else: # scalar or incomplete spec + 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): + 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 + ) + if hasattr(mibNode, 'createTest'): # table column + __modName, __symName, __s = mibView.getNodeLocation(_oid[:-1]) + rowNode, = mibView.mibBuilder.importSymbols(__modName, __symName) + return (symName, modName), rowNode.getIndicesFromInstId(suffix) + elif not suffix: # scalar + return (symName, modName), suffix + elif suffix == (0,): # scalar + return (symName, modName), __scalarSuffix + else: + raise NoSuchObjectError( + str='No MIB info for %s (closest parent %s)' % + (oid, mibNode.name) + ) + +# Value + +def cloneFromMibValue(mibView, modName, symName, value): + mibNode, = mibView.mibBuilder.importSymbols( + modName, symName + ) + if hasattr(mibNode, 'syntax'): # scalar + return mibNode.syntax.clone(value) + else: + return # identifier diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/ntforg.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/ntforg.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/ntforg.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/ntforg.py 2011-11-30 15:55:57.000000000 +0000 @@ -0,0 +1,289 @@ +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 +from pysnmp.smi import error +from pysnmp import nextid +from pysnmp import debug + +getNextHandle = nextid.Integer(0x7fffffff) + +class NotificationOriginator: + acmID = 3 # default MIB access control method to use + def __init__(self, snmpContext): + self.__pendingReqs = {} + self.__context = snmpContext + + def processResponsePdu( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + statusInformation, + sendPduHandle, + cbInfo + ): + (cbFun, cbCtx) = cbInfo + # 3.3.6d + ( origTransportDomain, + origTransportAddress, + origMessageProcessingModel, + origSecurityModel, + origSecurityName, + origSecurityLevel, + origContextEngineId, + origContextName, + origPduVersion, + origPdu, + origTimeout, + origRetryCount, + origRetries, + origSendRequestHandle + ) = self.__pendingReqs[sendPduHandle] + del self.__pendingReqs[sendPduHandle] + + snmpEngine.transportDispatcher.jobFinished(id(self)) + + if statusInformation: + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s statusInformation %s' % (sendPduHandle, statusInformation)) + if origRetries == origRetryCount: + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s retry count %d exceeded' % (sendPduHandle, origRetries)) + self._handleResponse( + origSendRequestHandle, + statusInformation['errorIndication'], + cbFun, + cbCtx) + return + + # Convert timeout in seconds into timeout in timer ticks + timeoutInTicks = float(origTimeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + + # 3.3.6a + sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + snmpEngine, + origTransportDomain, + origTransportAddress, + origMessageProcessingModel, + origSecurityModel, + origSecurityName, + origSecurityLevel, + origContextEngineId, + origContextName, + origPduVersion, + origPdu, + 1, # expectResponse + timeoutInTicks, + self.processResponsePdu, + (cbFun, cbCtx) + ) + + snmpEngine.transportDispatcher.jobStarted(id(self)) + + debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, timeout %d, retry %d of %d' % (sendPduHandle, origTimeout, origRetries, origRetryCount)) + + # 3.3.6b + self.__pendingReqs[sendPduHandle] = ( + origTransportDomain, + origTransportAddress, + origMessageProcessingModel, + origSecurityModel, + origSecurityName, + origSecurityLevel, + origContextEngineId, + origContextName, + origPduVersion, + origPdu, + origTimeout, + origRetryCount, + origRetries + 1, + sendPduHandle + ) + return + + # 3.3.6c + self._handleResponse(origSendRequestHandle, None, cbFun, cbCtx) + + def _handleResponse( + self, + sendRequestHandle, + errorIndication, + cbFun, + cbCtx): + cbFun(sendRequestHandle, errorIndication, cbCtx) + + def sendNotification( + self, + snmpEngine, + notificationTarget, + notificationName, + additionalVarBinds=None, + cbFun=None, + cbCtx=None, + contextName=null + ): + # 3.3 + ( notifyTag, + notifyType ) = config.getNotificationInfo( + snmpEngine, notificationTarget + ) + + debug.logger & debug.flagApp and debug.logger('sendNoification: notifyTag %s notifyType %s' % (notifyTag, notifyType)) + + contextMibInstrumCtl = self.__context.getMibInstrum( + contextName + ) + + for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): + ( transportDomain, + transportAddress, + timeout, + retryCount, + params ) = config.getTargetAddr(snmpEngine, targetAddrName) + ( messageProcessingModel, + securityModel, + securityName, + securityLevel ) = config.getTargetParams(snmpEngine, params) + + # 3.3.1 XXX +# XXX filtering's yet to be implemented +# filterProfileName = config.getNotifyFilterProfile(params) + +# ( filterSubtree, +# filterMask, +# filterType ) = config.getNotifyFilter(filterProfileName) + + varBinds = [] + + # 3.3.2 & 3.3.3 + sysUpTime, = contextMibInstrumCtl.mibBuilder.importSymbols( + '__SNMPv2-MIB', 'sysUpTime' + ) + varBinds.append( + (sysUpTime.name, sysUpTime.syntax.clone()) # for actual value + ) + + snmpTrapOid, = contextMibInstrumCtl.mibBuilder.importSymbols( + '__SNMPv2-MIB', 'snmpTrapOID' + ) + if notificationName: + varBinds.append( + (snmpTrapOid.name, + snmpTrapOid.syntax.clone(notificationName)) + ) + else: + varBinds.append((snmpTrapOid.name, snmpTrapOid.syntax)) + +# XXX it's still not clear how to instantiate OBJECTS clause +# # Get notification objects names +# for notificationObject in snmpTrapVal.getObjects(): +# mibNode, = contextMibInstrumCtl.mibBuilder.importSymbols( +# *notificationObject +# ) +# try: +# objectInstance = mibNode.getNode(mibNode.name + (0,)) +# except error.SmiError: +# return +# varBinds.append((objectInstance.name, objectInstance.syntax)) + + if additionalVarBinds: + varBinds.extend(additionalVarBinds) + + for varName, varVal in varBinds: + try: + snmpEngine.accessControlModel[self.acmID].isAccessAllowed( + snmpEngine, securityModel, securityName, + securityLevel, 'notify', contextName, varName + ) + except error.SmiError: + return + + # 3.3.4 + if notifyType == 1: + pdu = v2c.SNMPv2TrapPDU() + elif notifyType == 2: + pdu = v2c.InformRequestPDU() + else: + raise RuntimeError() + v2c.apiPDU.setDefaults(pdu) + v2c.apiPDU.setVarBinds(pdu, varBinds) + + # User-side API assumes SMIv2 + if messageProcessingModel == 0: + pdu = rfc2576.v2ToV1(pdu) + pduVersion = 0 + else: + pduVersion = 1 + + # 3.3.5 + if notifyType == 1: + snmpEngine.msgAndPduDsp.sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + self.__context.contextEngineId, + contextName, + pduVersion, + pdu, + None + ) + else: + # Convert timeout in seconds into timeout in timer ticks + timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() + + # 3.3.6a + sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + self.__context.contextEngineId, + contextName, + pduVersion, + pdu, + 1, # expectResponse + timeoutInTicks, + self.processResponsePdu, + (cbFun, cbCtx) + ) + + debug.logger & debug.flagApp and debug.logger('sendNoification: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) + + # 3.3.6b + self.__pendingReqs[sendPduHandle] = ( + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + self.__context.contextEngineId, + contextName, + pduVersion, + pdu, + timeout, + retryCount, + 1, + getNextHandle() + ) + + snmpEngine.transportDispatcher.jobStarted(id(self)) + + return sendPduHandle + +# XXX +# move/group/implement config setting/retrieval at a stand-alone module + diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/ntfrcv.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/ntfrcv.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/ntfrcv.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/ntfrcv.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,119 @@ +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 +from pysnmp import debug + +# 3.4 +class NotificationReceiver: + pduTypes = ( + v1.TrapPDU.tagSet, + v2c.SNMPv2TrapPDU.tagSet, + v2c.InformRequestPDU.tagSet + ) + + def __init__(self, snmpEngine, cbFun, cbCtx=None): + snmpEngine.msgAndPduDsp.registerContextEngineId( + null, self.pduTypes, self.processPdu # '' is a wildcard + ) + self.__cbFunVer = 0 + self.__cbFun = cbFun + self.__cbCtx = cbCtx + + def close(self, snmpEngine): + snmpEngine.msgAndPduDsp.unregisterContextEngineId( + null, self.pduTypes + ) + + def processPdu( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference + ): + + # Agent-side API complies with SMIv2 + if messageProcessingModel == 0: + origPdu = PDU + PDU = rfc2576.v1ToV2(PDU) + else: + origPdu = None + + errorStatus = 'noError'; errorIndex = 0 + varBinds = v2c.apiPDU.getVarBinds(PDU) + + debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) + + # 3.4 + if PDU.tagSet in rfc3411.confirmedClassPDUs: + # 3.4.1 --> no-op + + rspPDU = v2c.apiPDU.getResponse(PDU) + + # 3.4.2 + v2c.apiPDU.setErrorStatus(rspPDU, errorStatus) + v2c.apiPDU.setErrorIndex(rspPDU, errorIndex) + v2c.apiPDU.setVarBinds(rspPDU, varBinds) + + debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint())) + + # Agent-side API complies with SMIv2 + if messageProcessingModel == 0: + rspPDU = rfc2576.v2ToV1(rspPDU, origPdu) + + statusInformation = {} + + # 3.4.3 + try: + snmpEngine.msgAndPduDsp.returnResponsePdu( + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + rspPDU, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ) + except error.StatusInformation: + debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') + snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 + + elif PDU.tagSet in rfc3411.unconfirmedClassPDUs: + pass + else: + raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) + + debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (stateReference, self.__cbFun, self.__cbCtx, varBinds)) + + if self.__cbFunVer: + self.__cbFun( + snmpEngine, stateReference, contextEngineId, contextName, + varBinds, self.__cbCtx + ) + else: + # Compatibility stub (handle legacy cbFun interface) + try: + self.__cbFun( + snmpEngine, contextEngineId, contextName, + varBinds, self.__cbCtx + ) + except TypeError: + self.__cbFunVer = 1 + self.__cbFun( + snmpEngine, stateReference, contextEngineId, contextName, + varBinds, self.__cbCtx + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/oneliner/cmdgen.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/oneliner/cmdgen.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/oneliner/cmdgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/oneliner/cmdgen.py 2012-04-13 19:00:52.000000000 +0000 @@ -0,0 +1,552 @@ +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, base +from pyasn1.compat.octets import null + +# Auth protocol +usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol +usmHMACSHAAuthProtocol = config.usmHMACSHAAuthProtocol +usmNoAuthProtocol = config.usmNoAuthProtocol + +# Privacy protocol +usmDESPrivProtocol = config.usmDESPrivProtocol +usm3DESEDEPrivProtocol = config.usm3DESEDEPrivProtocol +usmAesCfb128Protocol = config.usmAesCfb128Protocol +usmAesCfb192Protocol = config.usmAesCfb192Protocol +usmAesCfb256Protocol = config.usmAesCfb256Protocol +usmNoPrivProtocol = config.usmNoPrivProtocol + +nextID = nextid.Integer(0xffffffff) + +class CommunityData: + mpModel = 1 # Default is SMIv2 + securityModel = mpModel + 1 + securityLevel = 'noAuthNoPriv' + contextName = null + def __init__(self, securityName, communityName=None, mpModel=None, + contextEngineId=None, contextName=None): + self.securityName = securityName + self.communityName = communityName + if mpModel is not None: + self.mpModel = mpModel + self.securityModel = mpModel + 1 + self.contextEngineId = contextEngineId + if contextName is not None: + self.contextName = contextName + # Autogenerate securityName if not specified + if communityName is None: + self.communityName = securityName + self.securityName = 's%s' % hash( + ( securityName, self.mpModel, + self.contextEngineId, self.contextName ) + ) + + def __repr__(self): + return '%s("%s", , %r, %r, %r)' % ( + self.__class__.__name__, + self.securityName, + self.mpModel, + self.contextEngineId, + self.contextName + ) + + def __hash__(self): return hash(self.securityName) + + def __eq__(self, other): return self.securityName == other + def __ne__(self, other): return self.securityName != other + def __lt__(self, other): return self.securityName < other + def __le__(self, other): return self.securityName <= other + def __gt__(self, other): return self.securityName > other + def __ge__(self, other): return self.securityName >= other + +class UsmUserData: + authKey = privKey = None + authProtocol = usmNoAuthProtocol + privProtocol = usmNoPrivProtocol + securityLevel = 'noAuthNoPriv' + securityModel = 3 + mpModel = 3 + contextName = null + def __init__(self, securityName, + authKey=None, privKey=None, + authProtocol=None, privProtocol=None, + contextEngineId=None, contextName=None): + self.securityName = securityName + + if authKey is not None: + self.authKey = authKey + if authProtocol is None: + self.authProtocol = usmHMACMD5AuthProtocol + else: + self.authProtocol = authProtocol + if self.securityLevel != 'authPriv': + self.securityLevel = 'authNoPriv' + + if privKey is not None: + self.privKey = privKey + if self.authProtocol == usmNoAuthProtocol: + raise error.PySnmpError('Privacy implies authenticity') + self.securityLevel = 'authPriv' + if privProtocol is None: + self.privProtocol = usmDESPrivProtocol + else: + self.privProtocol = privProtocol + + self.contextEngineId = contextEngineId + if contextName is not None: + self.contextName = contextName + + def __repr__(self): + return '%s("%s", , , %r, %r, %r, %r)' % ( + self.__class__.__name__, + self.securityName, + self.authProtocol, + self.privProtocol, + self.contextEngineId, + self.contextName + ) + + def __hash__(self): return hash(self.securityName) + + def __eq__(self, other): return self.securityName == other + def __ne__(self, other): return self.securityName != other + def __lt__(self, other): return self.securityName < other + def __le__(self, other): return self.securityName <= other + def __gt__(self, other): return self.securityName > other + def __ge__(self, other): return self.securityName >= other + +class UdpTransportTarget: + transportDomain = udp.domainName + def __init__(self, transportAddr, timeout=1, retries=5): + self.transportAddr = ( + socket.gethostbyname(transportAddr[0]), transportAddr[1] + ) + self.timeout = timeout + self.retries = retries + + def __repr__(self): return '%s(%r, %r, %r)' % ( + self.__class__.__name__, self.transportAddr, self.timeout, self.retries + ) + + def __hash__(self): return hash(self.transportAddr) + + 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() + return self.transport + +class AsynCommandGenerator: + _null = univ.Null('') + def __init__(self, snmpEngine=None): + self.__knownAuths = {} + self.__knownParams = {} + self.__knownTransports = {} + self.__knownTransportAddrs = {} + if snmpEngine is None: + self.snmpEngine = engine.SnmpEngine() + else: + self.snmpEngine = snmpEngine + self.mibViewController = view.MibViewController( + self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder + ) + + def __del__(self): self.uncfgCmdGen() + + def cfgCmdGen(self, authData, transportTarget, tagList=null): + if authData not in self.__knownAuths: + if isinstance(authData, CommunityData): + config.addV1System( + self.snmpEngine, + authData.securityName, + authData.communityName, + authData.contextEngineId, + authData.contextName, + tagList + ) + elif isinstance(authData, UsmUserData): + config.addV3User( + self.snmpEngine, + authData.securityName, + authData.authProtocol, authData.authKey, + authData.privProtocol, authData.privKey, + authData.contextEngineId + ) + else: + raise error.PySnmpError('Unsupported authentication object') + + self.__knownAuths[authData] = 1 + + k = authData.securityName, authData.securityLevel, authData.mpModel + if k in self.__knownParams: + paramsName = self.__knownParams[k] + else: + paramsName = 'p%s' % nextID() + config.addTargetParams( + self.snmpEngine, paramsName, + authData.securityName, authData.securityLevel, authData.mpModel + ) + self.__knownParams[k] = paramsName + + if transportTarget.transportDomain not in self.__knownTransports: + transport = transportTarget.openClientMode() + config.addSocketTransport( + self.snmpEngine, + transportTarget.transportDomain, + transport + ) + self.__knownTransports[transportTarget.transportDomain] = transport + + k = paramsName, transportTarget, tagList + if k in self.__knownTransportAddrs: + addrName = self.__knownTransportAddrs[k] + else: + addrName = 'a%s' % nextID() + config.addTargetAddr( + self.snmpEngine, addrName, + transportTarget.transportDomain, + transportTarget.transportAddr, + paramsName, + transportTarget.timeout * 100, + transportTarget.retries, + tagList + ) + self.__knownTransportAddrs[k] = addrName + + return addrName, paramsName + + def uncfgCmdGen(self): + for authData in self.__knownAuths: + if isinstance(authData, CommunityData): + config.delV1System( + self.snmpEngine, + authData.securityName + ) + elif isinstance(authData, UsmUserData): + config.delV3User( + self.snmpEngine, authData.securityName + ) + else: + raise error.PySnmpError('Unsupported authentication object') + self.__knownAuths.clear() + + for paramsName in self.__knownParams.values(): + config.delTargetParams( + self.snmpEngine, paramsName + ) + self.__knownParams.clear() + + for transportDomain, transport in self.__knownTransports.items(): + config.delSocketTransport( + self.snmpEngine, transportDomain + ) + transport.closeTransport() + self.__knownTransports.clear() + + for addrName in self.__knownTransportAddrs.values(): + config.delTargetAddr( + self.snmpEngine, addrName + ) + 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 isinstance(varName[0], self.intTypes): + name = varName + else: + name, oid = mibvar.mibNameToOid( + self.mibViewController, varName + ) + name = name + oid + varBinds.append((name, self._null)) + return varBinds + + # Async SNMP apps + + def getCmd(self, authData, transportTarget, varNames, cbInfo): + (cbFun, cbCtx) = cbInfo + addrName, paramsName = self.cfgCmdGen( + authData, transportTarget + ) + varBinds = self.makeReadVarBinds(varNames) + return cmdgen.GetCommandGenerator().sendReq( + self.snmpEngine, addrName, varBinds, cbFun, cbCtx, + authData.contextEngineId, authData.contextName + ) + + asyncGetCmd = getCmd + + def setCmd(self, authData, transportTarget, varBinds, cbInfo): + (cbFun, cbCtx) = cbInfo + addrName, paramsName = self.cfgCmdGen( + authData, transportTarget + ) + __varBinds = [] + for varName, varVal in varBinds: + name, oid = mibvar.mibNameToOid( + self.mibViewController, varName + ) + if not isinstance(varVal, base.AbstractSimpleAsn1Item): + ((symName, modName), suffix) = mibvar.oidToMibName( + self.mibViewController, name + oid + ) + syntax = mibvar.cloneFromMibValue( + self.mibViewController, modName, symName, varVal + ) + if syntax is None: + raise error.PySnmpError( + 'Value type MIB lookup failed for %r' % (varName,) + ) + varVal = syntax.clone(varVal) + __varBinds.append((name + oid, varVal)) + return cmdgen.SetCommandGenerator().sendReq( + self.snmpEngine, addrName, __varBinds, cbFun, cbCtx, + authData.contextEngineId, authData.contextName + ) + + asyncSetCmd = setCmd + + def nextCmd(self, authData, transportTarget, varNames, cbInfo): + (cbFun, cbCtx) = cbInfo + addrName, paramsName = self.cfgCmdGen( + authData, transportTarget + ) + varBinds = self.makeReadVarBinds(varNames) + return cmdgen.NextCommandGenerator().sendReq( + self.snmpEngine, addrName, varBinds, cbFun, cbCtx, + authData.contextEngineId, authData.contextName + ) + + asyncNextCmd = nextCmd + + def bulkCmd(self, authData, transportTarget, nonRepeaters, maxRepetitions, + varNames, cbInfo): + (cbFun, cbCtx) = cbInfo + addrName, paramsName = self.cfgCmdGen( + authData, transportTarget + ) + varBinds = self.makeReadVarBinds(varNames) + return cmdgen.BulkCommandGenerator().sendReq( + self.snmpEngine, addrName, + nonRepeaters, maxRepetitions, varBinds, cbFun, cbCtx, + authData.contextEngineId, authData.contextName + ) + + asyncBulkCmd = bulkCmd + +class CommandGenerator: + lexicographicMode = ignoreNonIncreasingOid = maxRows = None + def __init__(self, snmpEngine=None, asynCmdGen=None): + if asynCmdGen is None: + self.__asynCmdGen = AsynCommandGenerator(snmpEngine) + else: + self.__asynCmdGen = asynCmdGen + + # compatibility attributes + self.snmpEngine = self.__asynCmdGen.snmpEngine + self.mibViewController = self.__asynCmdGen.mibViewController + + def getCmd(self, authData, transportTarget, *varNames): + def __cbFun( + sendRequestHandle, errorIndication, errorStatus, errorIndex, + varBinds, appReturn + ): + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBinds'] = varBinds + + appReturn = {} + self.__asynCmdGen.getCmd( + authData, transportTarget, varNames, (__cbFun, appReturn) + ) + self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() + return ( + appReturn['errorIndication'], + appReturn['errorStatus'], + appReturn['errorIndex'], + appReturn['varBinds'] + ) + + def setCmd(self, authData, transportTarget, *varBinds): + def __cbFun( + sendRequestHandle, errorIndication, errorStatus, errorIndex, + varBinds, appReturn + ): + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBinds'] = varBinds + + appReturn = {} + self.__asynCmdGen.setCmd( + authData, transportTarget, varBinds, (__cbFun, appReturn) + ) + self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() + return ( + appReturn['errorIndication'], + appReturn['errorStatus'], + appReturn['errorIndex'], + appReturn['varBinds'] + ) + + def nextCmd(self, authData, transportTarget, *varNames): + def __cbFun(sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + (self, varBindHead, varBindTotalTable, appReturn) = cbCtx + if self.ignoreNonIncreasingOid and errorIndication and \ + isinstance(errorIndication, errind.OidNotIncreasing): + errorIndication = None + if errorStatus or errorIndication: + appReturn['errorIndication'] = errorIndication + if errorStatus == 2: + # Hide SNMPv1 noSuchName error which leaks in here + # from SNMPv1 Agent through internal pysnmp proxy. + appReturn['errorStatus'] = errorStatus.clone(0) + appReturn['errorIndex'] = errorIndex.clone(0) + else: + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBindTable'] = varBindTotalTable + return + else: + if self.maxRows and len(varBindTotalTable) >= self.maxRows: + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBindTable'] = varBindTotalTable[:self.maxRows] + return + + varBindTableRow = varBindTable and varBindTable[-1] or varBindTable + for idx in range(len(varBindTableRow)): + name, val = varBindTableRow[idx] + # XXX extra rows + if not isinstance(val, univ.Null): + if self.lexicographicMode: + if varBindHead[idx] <= name: + break + else: + if varBindHead[idx].isPrefixOf(name): + break + else: + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBindTable'] = varBindTotalTable + return + + varBindTotalTable.extend(varBindTable) + + return 1 # continue table retrieval + + varBindHead = [] + for varName in varNames: + name, suffix = mibvar.mibNameToOid( + self.__asynCmdGen.mibViewController, varName + ) + varBindHead.append(univ.ObjectIdentifier(name + suffix)) + + appReturn = {} + self.__asynCmdGen.nextCmd( + authData, transportTarget, varNames, + (__cbFun, (self, varBindHead, [], appReturn)) + ) + + self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() + + return ( + appReturn['errorIndication'], + appReturn['errorStatus'], + appReturn['errorIndex'], + appReturn['varBindTable'] + ) + + def bulkCmd(self, authData, transportTarget, + nonRepeaters, maxRepetitions, *varNames): + def __cbFun(sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBindTable, cbCtx): + (self, varBindHead, varBindTotalTable, appReturn) = cbCtx + if self.ignoreNonIncreasingOid and errorIndication and \ + isinstance(errorIndication, errind.OidNotIncreasing): + errorIndication = None + if errorStatus or errorIndication: + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBindTable'] = varBindTable + return + else: + while varBindTable: + if len(varBindTable[-1]) != len(varBindHead): + # Fix possibly non-rectangular table + del varBindTable[-1] + else: + break + + varBindTotalTable.extend(varBindTable) # XXX out of table + # rows possible + + if self.maxRows and len(varBindTotalTable) >= self.maxRows: + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBindTable'] = varBindTotalTable[:self.maxRows] + return + + varBindTableRow = varBindTable and varBindTable[-1] or varBindTable + for idx in range(len(varBindTableRow)): + name, val = varBindTableRow[idx] + if not isinstance(val, univ.Null): + if self.lexicographicMode: + if varBindHead[idx] <= name: + break + else: + if varBindHead[idx].isPrefixOf(name): + break + else: + appReturn['errorIndication'] = errorIndication + appReturn['errorStatus'] = errorStatus + appReturn['errorIndex'] = errorIndex + appReturn['varBindTable'] = varBindTotalTable + return + + return 1 # continue table retrieval + + varBindHead = [] + for varName in varNames: + name, suffix = mibvar.mibNameToOid( + self.__asynCmdGen.mibViewController, varName + ) + varBindHead.append(univ.ObjectIdentifier(name + suffix)) + + appReturn = {} + + self.__asynCmdGen.bulkCmd( + authData, transportTarget, nonRepeaters, maxRepetitions, + varNames, (__cbFun, (self, varBindHead, [], appReturn)) + ) + + self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() + + return ( + appReturn['errorIndication'], + appReturn['errorStatus'], + appReturn['errorIndex'], + appReturn['varBindTable'] + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/oneliner/ntforg.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/oneliner/ntforg.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/oneliner/ntforg.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/oneliner/ntforg.py 2011-12-05 13:08:46.000000000 +0000 @@ -0,0 +1,153 @@ +from pyasn1.type import base +from pysnmp import nextid +from pysnmp.entity import config +from pysnmp.entity.rfc3413 import ntforg, context, mibvar +from pysnmp.entity.rfc3413.oneliner import cmdgen + +# Auth protocol +usmHMACMD5AuthProtocol = cmdgen.usmHMACMD5AuthProtocol +usmHMACSHAAuthProtocol = cmdgen.usmHMACSHAAuthProtocol +usmNoAuthProtocol = cmdgen.usmNoAuthProtocol + +# Privacy protocol +usmDESPrivProtocol = cmdgen.usmDESPrivProtocol +usm3DESEDEPrivProtocol = cmdgen.usm3DESEDEPrivProtocol +usmAesCfb128Protocol = cmdgen.usmAesCfb128Protocol +usmAesCfb192Protocol = cmdgen.usmAesCfb192Protocol +usmAesCfb256Protocol = cmdgen.usmAesCfb256Protocol +usmNoPrivProtocol = cmdgen.usmNoPrivProtocol + +# Credentials +CommunityData = cmdgen.CommunityData +UsmUserData = cmdgen.UsmUserData + +# Transport +UdpTransportTarget = cmdgen.UdpTransportTarget + +nextID = nextid.Integer(0xffffffff) + +class AsynNotificationOriginator(cmdgen.AsynCommandGenerator): + def __init__(self, snmpEngine=None, snmpContext=None): + cmdgen.AsynCommandGenerator.__init__(self, snmpEngine) + self.snmpContext = snmpContext + self.__knownNotifyNames = {} + self.__knownAuths = {} + + def __del__(self): self.uncfgNtfOrg() + + def cfgNtfOrg(self, authData, transportTarget, notifyType, tagList): + addrName, paramsName = self.cfgCmdGen( + authData, transportTarget, tagList + ) + k = paramsName, tagList, notifyType + if k in self.__knownNotifyNames: + notifyName, _ = self.__knownNotifyNames[k] + else: + notifyName = 'n%s' % nextID() + config.addNotificationTarget( + self.snmpEngine, + notifyName, + paramsName, + tagList, + notifyType + ) + self.__knownNotifyNames[k] = notifyName, paramsName + k = ( authData.securityModel, + authData.securityName, + authData.securityLevel ) + if k not in self.__knownAuths: + subTree = (1,3,6) + config.addTrapUser( + self.snmpEngine, + authData.securityModel, + authData.securityName, + authData.securityLevel, + subTree + ) + self.__knownAuths[k] = subTree + if self.snmpContext is None: + self.snmpContext = context.SnmpContext(self.snmpEngine) + config.addContext( + self.snmpEngine, '' # this is leaky + ) + return notifyName + + def uncfgNtfOrg(self): + for notifyName, paramsName in self.__knownNotifyNames.values(): + config.delNotificationTarget( + self.snmpEngine, notifyName, paramsName + ) + for k, subTree in self.__knownAuths.items(): + securityModel, securityName, securityLevel = k + config.delTrapUser( + self.snmpEngine, + securityModel, + securityName, + securityLevel, + subTree + ) + self.uncfgCmdGen() + + def sendNotification( + self, authData, transportTarget, notifyType, + notificationType, varBinds=None, cbInfo=(None, None) + ): + (cbFun, cbCtx) = cbInfo + tagList = str(transportTarget.transportAddr).replace(' ', '_') + notifyName = self.cfgNtfOrg(authData, transportTarget, + notifyType, tagList) + if notificationType: + name, oid = mibvar.mibNameToOid( + self.mibViewController, notificationType + ) + notificationType = name + oid + if varBinds: + __varBinds = [] + for varName, varVal in varBinds: + name, oid = mibvar.mibNameToOid( + self.mibViewController, varName + ) + if not isinstance(varVal, base.Asn1ItemBase): + ((symName, modName), suffix) = mibvar.oidToMibName( + self.mibViewController, name + oid + ) + syntax = mibvar.cloneFromMibValue( + self.mibViewController, modName, symName, varVal + ) + if syntax is None: + raise error.PySnmpError( + 'Value type MIB lookup failed for %r' % (varName,) + ) + varVal = syntax.clone(varVal) + __varBinds.append((name + oid, varVal)) + else: + __varBinds = None + + return ntforg.NotificationOriginator(self.snmpContext).sendNotification(self.snmpEngine, notifyName, notificationType, __varBinds, cbFun, cbCtx) + + asyncSendNotification = sendNotification + +class NotificationOriginator: + def __init__(self, snmpEngine=None, snmpContext=None, asynNtfOrg=None): + if asynNtfOrg is None: + self.__asynNtfOrg = AsynNotificationOriginator( + snmpEngine, snmpContext + ) + else: + self.__asynNtfOrg = asynNtfOrg + + def sendNotification( + self, authData, transportTarget, notifyType, + notificationType, *varBinds + ): + def __cbFun(sendRequestHandle, errorIndication, appReturn): + appReturn['errorIndication'] = errorIndication + + appReturn = {} + self.__asynNtfOrg.sendNotification( + authData, transportTarget, notifyType, notificationType, varBinds, + (__cbFun, appReturn) + ) + self.__asynNtfOrg.snmpEngine.transportDispatcher.runDispatcher() + if 'errorIndication' in appReturn: + return appReturn['errorIndication'] diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/twisted/cmdgen.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/twisted/cmdgen.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/twisted/cmdgen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/twisted/cmdgen.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,112 @@ +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): + cbCtx.callback((errorIndication, errorStatus, errorIndex, varBinds)) + +class GetCommandGenerator(cmdgen.GetCommandGenerator): + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + contextEngineId=None, + contextName=null + ): + df = defer.Deferred() + cmdgen.GetCommandGenerator.sendReq( + self, + snmpEngine, + addrName, + varBinds, + _cbFun, + df, + contextEngineId, + contextName + ) + return df + +class SetCommandGenerator(cmdgen.SetCommandGenerator): + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + contextEngineId=None, + contextName=null + ): + df = defer.Deferred() + cmdgen.SetCommandGenerator.sendReq( + self, + snmpEngine, + addrName, + varBinds, + _cbFun, + df, + contextEngineId, + contextName + ) + return df + +def _cbFunWithDeferred(sendRequestHandle, errorIndication, + errorStatus, errorIndex, varBinds, cbCtx): + df = cbCtx['df'] + df.callback( + (errorIndication, errorStatus, errorIndex, varBinds) + ) + # Callback function may return another deferred to indicate + # it wishes to continue MIB walk. + if isinstance(df.result, defer.Deferred): + cbCtx['df'] = df.result + return 1 # continue walking + +class NextCommandGenerator(cmdgen.NextCommandGenerator): + def sendReq( + self, + snmpEngine, + addrName, + varBinds, + contextEngineId=None, + contextName=null + ): + df = defer.Deferred() + cmdgen.NextCommandGenerator.sendReq( + self, + snmpEngine, + addrName, + varBinds, + _cbFunWithDeferred, + { 'df': df }, # anonymous dictionary used for cbCtx + contextEngineId, + contextName + ) + return df + +class BulkCommandGenerator(cmdgen.BulkCommandGenerator): + def sendReq( + self, + snmpEngine, + addrName, + nonRepeaters, + maxRepetitions, + varBinds, + contextEngineId=None, + contextName=null + ): + df = defer.Deferred() + cmdgen.BulkCommandGenerator.sendReq( + self, + snmpEngine, + addrName, + nonRepeaters, + maxRepetitions, + varBinds, + _cbFunWithDeferred, + { 'df': df }, # anonymous dictionary used for cbCtx + contextEngineId=None, + contextName=null + ) + return df + diff -Nru python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/twisted/ntforg.py python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/twisted/ntforg.py --- python-pysnmp4-4.1.9a/pysnmp/entity/rfc3413/twisted/ntforg.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/entity/rfc3413/twisted/ntforg.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,33 @@ +from twisted.internet import reactor, defer +from pysnmp.entity.rfc3413 import ntforg +from pyasn1.compat.octets import null + +class NotificationOriginator(ntforg.NotificationOriginator): + def sendNotification( + self, + snmpEngine, + notificationTarget, + notificationName, + additionalVarBinds=None, + contextName=null + ): + df = defer.Deferred() + ntforg.NotificationOriginator.sendNotification( + self, + snmpEngine, + notificationTarget, + notificationName, + additionalVarBinds, + None, + df, + contextName=null + ) + return df + + def _handleResponse( + self, + sendRequestHandle, + errorIndication, + cbFun, + cbCtx): + cbCtx.callback((sendRequestHandle, errorIndication)) diff -Nru python-pysnmp4-4.1.9a/pysnmp/error.py python-pysnmp4-4.2.2/pysnmp/error.py --- python-pysnmp4-4.1.9a/pysnmp/error.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/error.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1 @@ +class PySnmpError(Exception): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/__init__.py python-pysnmp4-4.2.2/pysnmp/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/__init__.py 2006-12-13 20:23:33.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/__init__.py 2011-11-07 07:50:45.000000000 +0000 @@ -1,27 +1,3 @@ -"""Various components of SNMP applications""" -import os -import sys -import string - -def switchApiVersion(subPkg): - pkg = os.path.split(__path__[0])[-1] - newMod = __import__(subPkg, globals(), locals()) - realPkg = '_real_' + pkg - if sys.modules.has_key(realPkg): - sys.modules[pkg] = sys.modules[realPkg] - sys.modules[realPkg] = sys.modules[pkg] - sys.modules[pkg] = newMod - -def __isSubPackage(subDir): - if subDir and subDir[0] == 'v' and subDir[1] in string.digits \ - and len(subDir) == 2: - return 1 - -if os.environ.has_key('PYSNMP_API_VERSION'): - v = os.environ['PYSNMP_API_VERSION'] - if v: - switchApiVersion(v) # do not load any API -else: - subDirs = filter(__isSubPackage, os.listdir(__path__[0])) - subDirs.sort(); - switchApiVersion(subDirs[-1]) # take the most recent version +# PySNMP, version 4 +majorVersionId = '4' +version = (4, 2, 1) diff -Nru python-pysnmp4-4.1.9a/pysnmp/nextid.py python-pysnmp4-4.2.2/pysnmp/nextid.py --- python-pysnmp4-4.1.9a/pysnmp/nextid.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/nextid.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,34 @@ +# Return a next value in a reasonably MT-safe manner +import random + +random.seed() + +class Integer: + def __init__(self, maximum, increment=256): + self.__maximum = maximum + if increment >= maximum: + increment = maximum + self.__increment = increment + self.__threshold = increment//2 + e = random.randrange(self.__maximum - self.__increment) + self.__bank = list(range(e, e+self.__increment)) + + def __repr__(self): + return '%s(%d, %d)' % ( + self.__class__.__name__, + self.__maximum, + self.__increment + ) + + def __call__(self): + v = self.__bank.pop(0) + if v % self.__threshold: + return v + else: + # this is MT-safe unless too many (~ increment/2) threads + # bump into this code simultaneously + e = self.__bank[-1]+1 + if e > self.__maximum: + e = 0 + self.__bank.extend(range(e, e+self.__threshold)) + return v diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/acmod/rfc3415.py python-pysnmp4-4.2.2/pysnmp/proto/acmod/rfc3415.py --- python-pysnmp4-4.1.9a/pysnmp/proto/acmod/rfc3415.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/acmod/rfc3415.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,113 @@ +# View-based Access Control Model +from pysnmp.smi.error import NoSuchObjectError +from pysnmp.proto import errind, error +from pysnmp import debug + +accessModelID = 3 + +__powOfTwoSeq = [128, 64, 32, 16, 8, 4, 2, 1] + +# 3.2 +def isAccessAllowed( + snmpEngine, + securityModel, + securityName, + securityLevel, + viewType, + contextName, + variableName): + mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController + + debug.logger & debug.flagACL and debug.logger('isAccessAllowed: viewType %s for variableName %s' % (viewType, variableName)) + + # 3.2.1 + vacmContextEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') + tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) + try: + vacmContextName = vacmContextEntry.getNode( + vacmContextEntry.name + (1,) + tblIdx + ).syntax + except NoSuchObjectError: + raise error.StatusInformation(errorIndication=errind.noSuchContext) + + # 3.2.2 + vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' + ) + tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( + securityModel, securityName + ) + try: + vacmGroupName = vacmSecurityToGroupEntry.getNode( + vacmSecurityToGroupEntry.name + (3,) + tblIdx + ).syntax + except NoSuchObjectError: + raise error.StatusInformation(errorIndication=errind.noGroupName) + + # 3.2.3 + vacmAccessEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' + ) + # XXX partial context name match + tblIdx = vacmAccessEntry.getInstIdFromIndices( + vacmGroupName, contextName, securityModel, securityLevel + ) + + # 3.2.4 + if viewType == 'read': + entryIdx = vacmAccessEntry.name + (5,) + tblIdx + elif viewType == 'write': + entryIdx = vacmAccessEntry.name + (6,) + tblIdx + elif viewType == 'notify': + entryIdx = vacmAccessEntry.name + (7,) + tblIdx + else: + raise error.ProtocolError('Unknown view type %s' % viewType) + + try: + viewName = vacmAccessEntry.getNode(entryIdx).syntax + except NoSuchObjectError: + raise error.StatusInformation(errorIndication=errind.noAccessEntry) + if not len(viewName): + raise error.StatusInformation(errorIndication=errind.noSuchView) + + # XXX split onto object & instance ? + + # 3.2.5a + vacmViewTreeFamilyEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry') + tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName) + + # Walk over entries + initialTreeName = treeName = vacmViewTreeFamilyEntry.name + (2,) + tblIdx + maskName = vacmViewTreeFamilyEntry.name + (3,) + tblIdx + while 1: + vacmViewTreeFamilySubtree = vacmViewTreeFamilyEntry.getNextNode( + treeName + ) + vacmViewTreeFamilyMask = vacmViewTreeFamilyEntry.getNextNode( + maskName + ) + treeName = vacmViewTreeFamilySubtree.name + maskName = vacmViewTreeFamilyMask.name + if initialTreeName != treeName[:len(initialTreeName)]: + # 3.2.5b + raise error.StatusInformation(errorIndication=errind.notInView) + l = len(vacmViewTreeFamilySubtree.syntax) + if l > len(variableName): + continue + if vacmViewTreeFamilyMask.syntax: + mask = [] + for c in vacmViewTreeFamilyMask.syntax.asNumbers(): + mask = mask + [ b&c for b in __powOfTwoSeq ] + m = len(mask)-1 + idx = l-1 + while idx: + if idx > m or mask[idx] and \ + vacmViewTreeFamilySubtree.syntax[idx] != variableName[idx]: + break + idx = idx - 1 + if idx: continue # no match + else: # no mask + if vacmViewTreeFamilySubtree.syntax != variableName[:l]: + continue # no match + # 3.2.5c + return error.StatusInformation(errorIndication=errind.accessAllowed) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/acmod/void.py python-pysnmp4-4.2.2/pysnmp/proto/acmod/void.py --- python-pysnmp4-4.1.9a/pysnmp/proto/acmod/void.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/acmod/void.py 2011-01-17 00:14:55.000000000 +0000 @@ -0,0 +1,20 @@ +# Void Access Control Model +from pysnmp.smi.error import NoSuchObjectError +from pysnmp.proto import errind, error + +accessModelID = 0 + +# rfc3415 3.2 +def isAccessAllowed( + snmpEngine, + securityModel, + securityName, + securityLevel, + viewType, + contextName, + variableName): + + debug.logger & debug.flagACL and debug.logger('isAccessAllowed: viewType %s for variableName %s - OK' % (viewType, variableName)) + + # rfc3415 3.2.5c + return error.StatusInformation(errorIndication=errind.accessAllowed) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/api/__init__.py python-pysnmp4-4.2.2/pysnmp/proto/api/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/proto/api/__init__.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/api/__init__.py 2005-06-14 10:40:08.000000000 +0000 @@ -0,0 +1,8 @@ +from pysnmp.proto.api import v1, v2c, verdec + +# Protocol versions +protoVersion1 = 0 +protoVersion2c = 1 +protoModules = { protoVersion1: v1, protoVersion2c: v2c } + +decodeMessageVersion = verdec.decodeMessageVersion diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/api/v1.py python-pysnmp4-4.2.2/pysnmp/proto/api/v1.py --- python-pysnmp4-4.1.9a/pysnmp/proto/api/v1.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/api/v1.py 2012-04-02 14:48:04.000000000 +0000 @@ -0,0 +1,207 @@ +from pyasn1.type import univ +from pysnmp.proto import rfc1155, rfc1157, error +from pysnmp import nextid + +# Shortcuts to SNMP types +Integer = univ.Integer +OctetString = univ.OctetString +Null = univ.Null +null = Null('') +ObjectIdentifier = univ.ObjectIdentifier + +IpAddress = rfc1155.IpAddress +NetworkAddress = rfc1155.NetworkAddress +Counter = rfc1155.Counter +Gauge = rfc1155.Gauge +TimeTicks = rfc1155.TimeTicks +Opaque = rfc1155.Opaque + +VarBind = rfc1157.VarBind +VarBindList = rfc1157.VarBindList +GetRequestPDU = rfc1157.GetRequestPDU +GetNextRequestPDU = rfc1157.GetNextRequestPDU +GetResponsePDU = rfc1157.GetResponsePDU +SetRequestPDU = rfc1157.SetRequestPDU +TrapPDU = rfc1157.TrapPDU +Message = rfc1157.Message + +class VarBindAPI: + 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) + return varBind + + def getOIDVal(self, varBind): + return varBind[0], varBind[1].getComponent(1) + +apiVarBind = VarBindAPI() + +getNextRequestID = nextid.Integer(0xffffff) + +class PDUAPI: + _errorStatus = _errorIndex = Integer(0) + def setDefaults(self, pdu): + pdu.setComponentByPosition( + 0, getNextRequestID(), verifyConstraints=False + ) + pdu.setComponentByPosition( + 1, self._errorStatus, verifyConstraints=False + ) + pdu.setComponentByPosition( + 2, self._errorIndex, verifyConstraints=False + ) + pdu.setComponentByPosition(3) + + def getRequestID(self, pdu): return pdu.getComponentByPosition(0) + def setRequestID(self, pdu, value): pdu.setComponentByPosition(0, value) + + def getErrorStatus(self, pdu): return pdu.getComponentByPosition(1) + def setErrorStatus(self, pdu, value): pdu.setComponentByPosition(1, value) + + def getErrorIndex(self, pdu): + errorIndex = pdu.getComponentByPosition(2) + if errorIndex > len(pdu[3]): + raise error.ProtocolError( + 'Error index out of range: %s > %s' % (errorIndex, len(pdu[3])) + ) + return errorIndex + def setErrorIndex(self, pdu, value): + pdu.setComponentByPosition(2, value) + + def setEndOfMibError(self, pdu, errorIndex): + self.setErrorIndex(pdu, errorIndex) + self.setErrorStatus(pdu, 2) + + def setNoSuchInstanceError(self, pdu, errorIndex): + self.setEndOfMibError(pdu, errorIndex) + + def getVarBindList(self, pdu): + return pdu.getComponentByPosition(3) + + def setVarBindList(self, pdu, varBindList): + varBindList = pdu.setComponentByPosition(3, varBindList) + def getVarBinds(self, pdu): + varBinds = [] + for varBind in pdu.getComponentByPosition(3): + varBinds.append(apiVarBind.getOIDVal(varBind)) + return varBinds + def setVarBinds(self, pdu, varBinds): + varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) + varBindList.clear() + idx = 0 + for varBind in varBinds: + if isinstance(varBind, VarBind): + varBindList.setComponentByPosition(idx, varBind) + else: + varBindList.setComponentByPosition(idx) + apiVarBind.setOIDVal( + varBindList.getComponentByPosition(idx), varBind + ) + idx = idx + 1 + + def getResponse(self, reqPDU): + rspPDU = GetResponsePDU() + self.setDefaults(rspPDU) + self.setRequestID(rspPDU, self.getRequestID(reqPDU)) + return rspPDU + + def getVarBindTable(self, reqPDU, rspPDU): + if apiPDU.getErrorStatus(rspPDU) == 2: + varBindRow = [] + for varBind in apiPDU.getVarBinds(reqPDU): + varBindRow.append((varBind[0], null)) + return [ varBindRow ] + else: + return [ apiPDU.getVarBinds(rspPDU) ] + +apiPDU = PDUAPI() + +class TrapPDUAPI: + try: + import socket + agentAddress = IpAddress(socket.gethostbyname(socket.gethostname())) + except: + agentAddress = IpAddress('0.0.0.0') + _entOid = ObjectIdentifier((1,3,6,1,4,1,20408)) + _zeroInt = univ.Integer(0) + def setDefaults(self, pdu): + pdu.setComponentByPosition(0, self._entOid, verifyConstraints=False) + pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(0, self.agentAddress, verifyConstraints=False) + pdu.setComponentByPosition(2, self._zeroInt, verifyConstraints=False) + pdu.setComponentByPosition(3, self._zeroInt, verifyConstraints=False) + pdu.setComponentByPosition(4, self._zeroInt, verifyConstraints=False) + pdu.setComponentByPosition(5) + + def getEnterprise(self, pdu): return pdu.getComponentByPosition(0) + def setEnterprise(self, pdu, value): pdu.setComponentByPosition(0, value) + + def getAgentAddr(self, pdu): + return pdu.getComponentByPosition(1).getComponentByPosition(0) + def setAgentAddr(self, pdu, value): + pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(0, value) + + def getGenericTrap(self, pdu): return pdu.getComponentByPosition(2) + def setGenericTrap(self, pdu, value): pdu.setComponentByPosition(2, value) + + def getSpecificTrap(self, pdu): return pdu.getComponentByPosition(3) + def setSpecificTrap(self, pdu, value): pdu.setComponentByPosition(3, value) + + def getTimeStamp(self, pdu): return pdu.getComponentByPosition(4) + def setTimeStamp(self, pdu, value): pdu.setComponentByPosition(4, value) + + def getVarBindList(self, pdu): + return pdu.getComponentByPosition(5) + def setVarBindList(self, pdu, varBindList): + varBindList = pdu.setComponentByPosition(5, varBindList) + + def getVarBinds(self, pdu): + varBinds = [] + for varBind in pdu.getComponentByPosition(5): + varBinds.append(apiVarBind.getOIDVal(varBind)) + return varBinds + def setVarBinds(self, pdu, varBinds): + varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5) + varBindList.clear() + idx = 0 + for varBind in varBinds: + if isinstance(varBind, VarBind): + varBindList.setComponentByPosition(idx, varBind) + else: + varBindList.setComponentByPosition(idx) + apiVarBind.setOIDVal( + varBindList.getComponentByPosition(idx), varBind + ) + idx = idx + 1 + +apiTrapPDU = TrapPDUAPI() + +class MessageAPI: + _verInt = univ.Integer(0) + _commStr = univ.OctetString('public') + def setDefaults(self, msg): + msg.setComponentByPosition(0, self._verInt, verifyConstraints=False) + msg.setComponentByPosition(1, self._commStr, verifyConstraints=False) + return msg + + def getVersion(self, msg): return msg.getComponentByPosition(0) + def setVersion(self, msg, value): msg.setComponentByPosition(0, value) + + def getCommunity(self, msg): return msg.getComponentByPosition(1) + def setCommunity(self, msg, value): msg.setComponentByPosition(1, value) + + def getPDU(self, msg): return msg.getComponentByPosition(2).getComponent() + def setPDU(self, msg, value): + msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(value.getTagSet(), value, 1, verifyConstraints=False) + + def getResponse(self, reqMsg): + rspMsg = Message() + self.setDefaults(rspMsg) + self.setVersion(rspMsg, self.getVersion(reqMsg)) + self.setCommunity(rspMsg, self.getCommunity(reqMsg)) + self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) + return rspMsg + +apiMessage = MessageAPI() + diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/api/v2c.py python-pysnmp4-4.2.2/pysnmp/proto/api/v2c.py --- python-pysnmp4-4.1.9a/pysnmp/proto/api/v2c.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/api/v2c.py 2012-04-04 13:14:00.000000000 +0000 @@ -0,0 +1,143 @@ +from pysnmp.proto import rfc1902, rfc1905, error +from pysnmp.proto.api import v1 +from pyasn1.type import univ, namedtype, namedval, constraint + +# Shortcuts to SNMP types +Null = univ.Null +null = Null('') +ObjectIdentifier = univ.ObjectIdentifier + +Integer = rfc1902.Integer +Integer32 = rfc1902.Integer32 +OctetString = rfc1902.OctetString +IpAddress = rfc1902.IpAddress +Counter32 = rfc1902.Counter32 +Gauge32 = rfc1902.Gauge32 +Unsigned32 = rfc1902.Unsigned32 +TimeTicks = rfc1902.TimeTicks +Opaque = rfc1902.Opaque +Counter64 = rfc1902.Counter64 +Bits = rfc1902.Bits + +VarBind = rfc1905.VarBind +VarBindList = rfc1905.VarBindList +GetRequestPDU = rfc1905.GetRequestPDU +GetNextRequestPDU = rfc1905.GetNextRequestPDU +ResponsePDU = GetResponsePDU = rfc1905.ResponsePDU +SetRequestPDU = rfc1905.SetRequestPDU +GetBulkRequestPDU = rfc1905.GetBulkRequestPDU +InformRequestPDU = rfc1905.InformRequestPDU +SNMPv2TrapPDU = TrapPDU = rfc1905.SNMPv2TrapPDU +ReportPDU = rfc1905.ReportPDU + +# v2 model uses v1 messaging but it's not defined in v2 MIB +class Message(v1.Message): + componentType = namedtype.NamedTypes( + namedtype.NamedType('version', univ.Integer(namedValues = namedval.NamedValues(('version-2', 1)))), + namedtype.NamedType('community', univ.OctetString()), + namedtype.NamedType('data', rfc1905.PDUs()) + ) + +getNextRequestID = v1.getNextRequestID + +apiVarBind = v1.apiVarBind + +class PDUAPI(v1.PDUAPI): + _errorIndex = univ.Integer(0).subtype(subtypeSpec=constraint.ValueRangeConstraint(0, rfc1905.max_bindings)) + def getResponse(self, reqPDU): + rspPDU = ResponsePDU() + self.setDefaults(rspPDU) + self.setRequestID(rspPDU, self.getRequestID(reqPDU)) + return rspPDU + + def getVarBindTable(self, reqPDU, rspPDU): + return [ apiPDU.getVarBinds(rspPDU) ] + + def setEndOfMibError(self, pdu, errorIndex): + varBindList = self.getVarBindList(pdu) + varBindList[errorIndex-1].setComponentByPosition( + 1, rfc1905.endOfMibView, verifyConstraints=False + ) + + def setNoSuchInstanceError(self, pdu, errorIndex): + varBindList = self.getVarBindList(pdu) + varBindList[errorIndex-1].setComponentByPosition( + 1, rfc1905.noSuchInstance, verifyConstraints=False + ) + +apiPDU = PDUAPI() + +class BulkPDUAPI(PDUAPI): + _tenInt = rfc1902.Integer(10) + def setDefaults(self, pdu): + PDUAPI.setDefaults(self, pdu) + pdu.setComponentByPosition(2, self._tenInt, verifyConstraints=False) + + def getNonRepeaters(self, pdu): return pdu.getComponentByPosition(1) + def setNonRepeaters(self, pdu, value): pdu.setComponentByPosition(1, value) + + def getMaxRepetitions(self, pdu): return pdu.getComponentByPosition(2) + def setMaxRepetitions(self,pdu,value): pdu.setComponentByPosition(2,value) + + def getVarBindTable(self, reqPDU, rspPDU): + nonRepeaters = self.getNonRepeaters(reqPDU) + maxRepetitions = self.getMaxRepetitions(reqPDU) + + reqVarBinds = self.getVarBinds(reqPDU) + + N = min(int(nonRepeaters), len(reqVarBinds)) + M = int(maxRepetitions) + R = max(len(reqVarBinds)-N, 0) + + rspVarBinds = self.getVarBinds(rspPDU) + + varBindTable = [] + + if R: + for i in range(0, len(rspVarBinds)-N, R): + varBindRow = rspVarBinds[:N] + rspVarBinds[N+i:N+R+i] + # ignore stray OIDs / non-rectangular table + if len(varBindRow) == N + R: + varBindTable.append(varBindRow) + elif N: + varBindTable.append(rspVarBinds[:N]) + + return varBindTable + +apiBulkPDU = BulkPDUAPI() + +class TrapPDUAPI(v1.PDUAPI): + sysUpTime = (1,3,6,1,2,1,1,3,0) + snmpTrapAddress = (1,3,6,1,6,3,18,1,3,0) + snmpTrapCommunity = (1,3,6,1,6,3,18,1,4,0) + snmpTrapOID = (1,3,6,1,6,3,1,1,4,1,0) + snmpTrapEnterprise = (1,3,6,1,6,3,1,1,4,3,0) + _zeroTime = TimeTicks(0) + _genTrap = ObjectIdentifier((1,3,6,1,6,3,1,1,5,1)) + def setDefaults(self, pdu): + v1.PDUAPI.setDefaults(self, pdu) + varBinds = [ + ( self.sysUpTime, self._zeroTime), + # generic trap + ( self.snmpTrapOID, self._genTrap) + ] + self.setVarBinds(pdu, varBinds) + +apiTrapPDU = TrapPDUAPI() + +class MessageAPI(v1.MessageAPI): + _verInt = univ.Integer(1) + def setDefaults(self, msg): + msg.setComponentByPosition(0, self._verInt, verifyConstraints=False) + msg.setComponentByPosition(1, self._commStr, verifyConstraints=False) + return msg + + def getResponse(self, reqMsg): + rspMsg = Message() + self.setDefaults(rspMsg) + self.setVersion(rspMsg, self.getVersion(reqMsg)) + self.setCommunity(rspMsg, self.getCommunity(reqMsg)) + self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) + return rspMsg + +apiMessage = MessageAPI() diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/api/verdec.py python-pysnmp4-4.2.2/pysnmp/proto/api/verdec.py --- python-pysnmp4-4.1.9a/pysnmp/proto/api/verdec.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/api/verdec.py 2011-01-21 19:10:06.000000000 +0000 @@ -0,0 +1,6 @@ +from pyasn1.codec.ber import decoder + +def decodeMessageVersion(wholeMsg): + seq, wholeMsg = decoder.decode(wholeMsg, recursiveFlag=0) + ver, wholeMsg = decoder.decode(wholeMsg, recursiveFlag=0) + return ver diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/cache.py python-pysnmp4-4.2.2/pysnmp/proto/cache.py --- python-pysnmp4-4.1.9a/pysnmp/proto/cache.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/cache.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,31 @@ +from pysnmp.proto import error + +class Cache: + def __init__(self): + self.__cacheRepository = {} + + def add(self, index, **kwargs): + self.__cacheRepository[index] = kwargs + return index + + def pop(self, index): + if index in self.__cacheRepository: + cachedParams = self.__cacheRepository[index] + else: + return + del self.__cacheRepository[index] + return cachedParams + + def update(self, index, **kwargs): + if index not in self.__cacheRepository: + raise error.ProtocolError( + 'Cache miss on update for %s' % kwargs + ) + self.__cacheRepository[index].update(kwargs) + + def expire(self, cbFun, cbCtx): + for index, cachedParams in list(self.__cacheRepository.items()): + if cbFun: + if cbFun(index, cachedParams, cbCtx): + del self.__cacheRepository[index] + diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/errind.py python-pysnmp4-4.2.2/pysnmp/proto/errind.py --- python-pysnmp4-4.1.9a/pysnmp/proto/errind.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/errind.py 2011-11-07 07:50:45.000000000 +0000 @@ -0,0 +1,128 @@ +# SNMPv3 error-indication values. +# Object below could be compared with literals thus are backward-compatible +# with original pysnmperror-indication values. + +class ErrorIndication: + def __init__(self, descr=None): + self.__value = self.__descr = self.__class__.__name__[0].lower() + self.__class__.__name__[1:] + if descr: self.__descr = descr + + 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 + +class ParseError(ErrorIndication): pass +parseError = ParseError('SNMP message deserialization error') + +class UnsupportedMsgProcessingModel(ErrorIndication): pass +unsupportedMsgProcessingModel = UnsupportedMsgProcessingModel('Unknown SNMP message processing model ID encountered') + +class UnknownPDUHandler(ErrorIndication): pass +unknownPDUHandler = UnknownPDUHandler('Unhandled PDU type encountered') + +class UnsupportedPDUtype(ErrorIndication): pass +unsupportedPDUtype = UnsupportedPDUtype('Unsupported SNMP PDU type encountered') + +class RequestTimedOut(ErrorIndication): pass +requestTimedOut = RequestTimedOut('No SNMP response received before timeout') + +class EmptyResponse(ErrorIndication): pass +emptyResponse = EmptyResponse('Empty SNMP response message') + +class NonReportable(ErrorIndication): pass +nonReportable = NonReportable('Report PDU generation not attempted') + +class DataMismatch(ErrorIndication): pass +dataMismatch = DataMismatch('SNMP request/response parameters mismatched') + +class EngineIDMispatch(ErrorIndication): pass +engineIDMispatch = EngineIDMispatch('SNMP engine ID mismatch encountered') + +class UnknownEngineID(ErrorIndication): pass +unknownEngineID = UnknownEngineID('Unknown SNMP engine ID encountered') + +class TooBig(ErrorIndication): pass +tooBig = TooBig('SNMP message will be too big') + +class LoopTerminated(ErrorIndication):pass +loopTerminated = LoopTerminated('Infinite SNMP entities talk terminated') + +class InvalidMsg(ErrorIndication):pass +invalidMsg = InvalidMsg('Invalid SNMP message header parameters encountered') + +# SNMP security modules errors + +class UnknownCommunityName(ErrorIndication): pass +unknownCommunityName = UnknownCommunityName('Unknown SNMP community name encountered') + +class NoEncryption(ErrorIndication): pass +noEncryption = NoEncryption('No encryption services configured') + +class EncryptionError(ErrorIndication): pass +encryptionError = EncryptionError('Ciphering services not available') + +class DecryptionError(ErrorIndication): pass +decryptionError = DecryptionError('Ciphering services not available or ciphertext is broken') + +class NoAuthentication(ErrorIndication): pass +noAuthentication = NoAuthentication('No authentication services configured') + +class AuthenticationError(ErrorIndication): pass +authenticationError = AuthenticationError('Ciphering services not available or bad parameters') + +class AuthenticationFailure(ErrorIndication): pass +authenticationFailure = AuthenticationFailure('Authenticator mismatched') + +class UnsupportedAuthProtocol(ErrorIndication): pass +unsupportedAuthProtocol = UnsupportedAuthProtocol('Authentication protocol is not supprted') + +class UnsupportedPrivProtocol(ErrorIndication): pass +unsupportedPrivProtocol = UnsupportedPrivProtocol('Privacy protocol is not supprted') + +class UnknownSecurityName(ErrorIndication): pass +unknownSecurityName = UnknownSecurityName('Unknown SNMP security name encountered') + +class UnsupportedSecurityModel(ErrorIndication): pass +unsupportedSecurityModel = UnsupportedSecurityModel('Unsupported SNMP security model') + +class UnsupportedSecurityLevel(ErrorIndication): pass +unsupportedSecurityLevel = UnsupportedSecurityLevel('Unsupported SNMP security level') + +class NotInTimeWindow(ErrorIndication): pass +notInTimeWindow = NotInTimeWindow('SNMP message timing parameters not in windows of trust') + +# SNMP access-control errors + +class NoSuchView(ErrorIndication): pass +noSuchView = NoSuchView('No such MIB view currently exists') + +class NoAccessEntry(ErrorIndication): pass +noAccessEntry = NoAccessEntry('Access to MIB node denined') + +class NoGroupName(ErrorIndication): pass +noGroupName = NoGroupName('No such VACM group configured') + +class NoSuchContext(ErrorIndication): pass +noSuchContext = NoSuchContext('SNMP context now found') + +class NotInView(ErrorIndication): pass +notInView = NotInView('Requested OID is out of MIB view') + +class AccessAllowed(ErrorIndication): pass +accessAllowed = AccessAllowed() + +class OtherError(ErrorIndication): pass +otherError = OtherError('Unspecified SNMP engine error occurred') + +# SNMP Apps errors + +class OidNotIncreasing(ErrorIndication): pass +oidNotIncreasing = OidNotIncreasing('OIDs are not increasing') + diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/error.py python-pysnmp4-4.2.2/pysnmp/proto/error.py --- python-pysnmp4-4.1.9a/pysnmp/proto/error.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/error.py 2011-01-20 14:59:40.000000000 +0000 @@ -0,0 +1,23 @@ +from pyasn1.error import PyAsn1Error +from pysnmp.error import PySnmpError +from pysnmp import debug + +class ProtocolError(PySnmpError, PyAsn1Error): pass + +# SNMP v3 exceptions + +class SnmpV3Error(ProtocolError): pass +class StatusInformation(SnmpV3Error): + def __init__(self, **kwargs): + SnmpV3Error.__init__(self) + self.__errorIndication = kwargs + debug.logger & (debug.flagDsp|debug.flagMP|debug.flagSM|debug.flagACL) and debug.logger('StatusInformation: %s' % kwargs) + def __str__(self): return str(self.__errorIndication) + def __getitem__(self, key): return self.__errorIndication[key] + def __contains__(self, key): return key in self.__errorIndication + def get(self, key, defVal=None): + return self.__errorIndication.get(key, defVal) +class CacheExpiredError(SnmpV3Error): pass +class InternalError(SnmpV3Error): pass +class MessageProcessingError(SnmpV3Error): pass +class RequestTimeout(SnmpV3Error): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/__init__.py python-pysnmp4-4.2.2/pysnmp/proto/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/proto/__init__.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/__init__.py 2004-11-12 14:21:29.000000000 +0000 @@ -0,0 +1,7 @@ +""" + SNMP framework for Python. + + The pysnmp.proto sub-package implements various SNMP protocols. + + Copyright 1999-2004 by Ilya Etingof . See LICENSE for details. +""" diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/base.py python-pysnmp4-4.2.2/pysnmp/proto/mpmod/base.py --- python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/mpmod/base.py 2011-01-31 07:54:18.000000000 +0000 @@ -0,0 +1,60 @@ +# MP-specific cache management +from pysnmp.proto.mpmod import cache + +class AbstractMessageProcessingModel: + def __init__(self): + self._snmpMsgSpec = self.snmpMsgSpec() # local copy + self._cache = cache.Cache() + + def prepareOutgoingMessage( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + expectResponse, + sendPduHandle + ): + raise error.ProtocolError('method not implemented') + + def prepareResponseMessage( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ): + raise error.ProtocolError('method not implemented') + + def prepareDataElements( + self, + snmpEngine, + transportDomain, + transportAddress, + wholeMsg + ): + raise error.ProtocolError('method not implemented') + + def releaseStateInformation(self, sendPduHandle): + try: + self._cache.popBySendPduHandle(sendPduHandle) + except error.ProtocolError: + pass # XXX maybe these should all follow some scheme? + + def receiveTimerTick(self, snmpEngine, timeNow): + self._cache.expireCaches() diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/cache.py python-pysnmp4-4.2.2/pysnmp/proto/mpmod/cache.py --- python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/cache.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/mpmod/cache.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,98 @@ +from pysnmp.proto import error +from pysnmp import nextid + +class Cache: + __stateReference = nextid.Integer(0xffffff) + __msgID = nextid.Integer(0xffffff) + def __init__(self): + self.__msgIdIndex = {} + self.__stateReferenceIndex = {} + self.__sendPduHandleIdx = {} + # Message expiration mechanics + self.__expirationQueue = {} + self.__expirationTimer = 0 + + # Server mode cache handling + + def newStateReference(self): return self.__stateReference() + + def pushByStateRef(self, stateReference, **msgInfo): + if stateReference in self.__stateReferenceIndex: + raise error.ProtocolError( + 'Cache dup for stateReference=%s at %s' % + (stateReference, self) + ) + expireAt = self.__expirationTimer+60 + self.__stateReferenceIndex[stateReference] = ( msgInfo, expireAt ) + + # Schedule to expire + if expireAt not in self.__expirationQueue: + self.__expirationQueue[expireAt] = {} + if 'stateReference' not in self.__expirationQueue[expireAt]: + self.__expirationQueue[expireAt]['stateReference'] = {} + self.__expirationQueue[expireAt]['stateReference'][stateReference] = 1 + + def popByStateRef(self, stateReference): + if stateReference in self.__stateReferenceIndex: + cacheInfo = self.__stateReferenceIndex[stateReference] + else: + raise error.ProtocolError( + 'Cache miss for stateReference=%s at %s' % + (stateReference, self) + ) + del self.__stateReferenceIndex[stateReference] + cacheEntry, expireAt = cacheInfo + del self.__expirationQueue[expireAt]['stateReference'][stateReference] + return cacheEntry + + # Client mode cache handling + + def newMsgID(self): return self.__msgID() + + def pushByMsgId(self, msgId, **msgInfo): + if msgId in self.__msgIdIndex: + raise error.ProtocolError( + 'Cache dup for msgId=%s at %s' % (msgId, self) + ) + expireAt = self.__expirationTimer+60 + self.__msgIdIndex[msgId] = ( msgInfo, expireAt ) + + self.__sendPduHandleIdx[msgInfo['sendPduHandle']] = msgId + + # Schedule to expire + if expireAt not in self.__expirationQueue: + self.__expirationQueue[expireAt] = {} + if 'msgId' not in self.__expirationQueue[expireAt]: + self.__expirationQueue[expireAt]['msgId'] = {} + self.__expirationQueue[expireAt]['msgId'][msgId] = 1 + + def popByMsgId(self, msgId): + if msgId in self.__msgIdIndex: + cacheInfo = self.__msgIdIndex[msgId] + else: + raise error.ProtocolError( + 'Cache miss for msgId=%s at %s' % (msgId, self) + ) + msgInfo, expireAt = cacheInfo + del self.__sendPduHandleIdx[msgInfo['sendPduHandle']] + del self.__msgIdIndex[msgId] + cacheEntry, expireAt = cacheInfo + del self.__expirationQueue[expireAt]['msgId'][msgId] + return cacheEntry + + def popBySendPduHandle(self, sendPduHandle): + if sendPduHandle in self.__sendPduHandleIdx: + self.popByMsgId(self.__sendPduHandleIdx[sendPduHandle]) + + def expireCaches(self): + # Uses internal clock to expire pending messages + if self.__expirationTimer in self.__expirationQueue: + cacheInfo = self.__expirationQueue[self.__expirationTimer] + if 'stateReference' in cacheInfo: + for stateReference in cacheInfo['stateReference']: + del self.__stateReferenceIndex[stateReference] + if 'msgId' in cacheInfo: + for msgId in cacheInfo['msgId']: + del self.__msgIdIndex[msgId] + del self.__expirationQueue[self.__expirationTimer] + self.__expirationTimer = self.__expirationTimer + 1 diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/rfc2576.py python-pysnmp4-4.2.2/pysnmp/proto/mpmod/rfc2576.py --- python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/rfc2576.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/mpmod/rfc2576.py 2012-04-20 19:25:28.000000000 +0000 @@ -0,0 +1,421 @@ +# SNMP v1 & v2c message processing models implementation +import sys +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 pysnmp import debug + +# Since I have not found a detailed reference to v1MP/v2cMP +# inner workings, the following has been patterned from v3MP. Most +# references here goes to RFC3412. + +class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): + messageProcessingModelID = univ.Integer(0) # SNMPv1 + snmpMsgSpec = v1.Message + # rfc3412: 7.1 + def prepareOutgoingMessage( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + expectResponse, + sendPduHandle + ): + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID = snmpEngineID.syntax + + # rfc3412: 7.1.1b + if pdu.tagSet in rfc3411.confirmedClassPDUs: + pdu.setComponentByPosition(1) + msgID = pdu.getComponentByPosition(0) + + # rfc3412: 7.1.4 + # Since there's no SNMP engine identification in v1/2c, + # set destination contextEngineId to ours + if not contextEngineId: + contextEngineId = snmpEngineID + + # rfc3412: 7.1.5 + if not contextName: + contextName = null + + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) + + # rfc3412: 7.1.6 + scopedPDU = ( contextEngineId, contextName, pdu ) + + msg = self._snmpMsgSpec + msg.setComponentByPosition(0, self.messageProcessingModelID) + msg.setComponentByPosition(2) + msg.getComponentByPosition(2).setComponentByType( + pdu.tagSet, pdu, verifyConstraints=False + ) + + # rfc3412: 7.1.7 + globalData = ( msg, ) + + k = int(securityModel) + if k in snmpEngine.securityModels: + smHandler = snmpEngine.securityModels[k] + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityModel + ) + + # rfc3412: 7.1.9.a & rfc2576: 5.2.1 --> no-op + + snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + + # rfc3412: 7.1.9.b + ( securityParameters, + wholeMsg ) = smHandler.generateRequestMsg( + snmpEngine, + self.messageProcessingModelID, + globalData, + snmpEngineMaxMessageSize.syntax, + securityModel, + snmpEngineID, + securityName, + securityLevel, + scopedPDU + ) + + # rfc3412: 7.1.9.c + if pdu.tagSet in rfc3411.confirmedClassPDUs: + # XXX rfc bug? why stateReference should be created? + self._cache.pushByMsgId( + int(msgID), + sendPduHandle=sendPduHandle, + msgID=msgID, + snmpEngineID=snmpEngineID, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + transportDomain=transportDomain, + transportAddress=transportAddress + ) + + return ( transportDomain, transportAddress, wholeMsg ) + + # rfc3412: 7.1 + def prepareResponseMessage( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ): + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID = snmpEngineID.syntax + + # rfc3412: 7.1.2.b + cachedParams = self._cache.popByStateRef(stateReference) + msgID = cachedParams['msgID'] + contextEngineId = cachedParams['contextEngineId'] + contextName = cachedParams['contextName'] + securityModel = cachedParams['securityModel'] + securityName = cachedParams['securityName'] + securityLevel = cachedParams['securityLevel'] + securityStateReference = cachedParams['securityStateReference'] + maxMessageSize = cachedParams['msgMaxSize'] + transportDomain = cachedParams['transportDomain'] + transportAddress = cachedParams['transportAddress'] + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % (msgID, transportDomain, transportAddress, stateReference)) + + # rfc3412: 7.1.3 + if statusInformation: + # rfc3412: 7.1.3a (N/A) + + # rfc3412: 7.1.3b (always discard) + raise error.StatusInformation( + errorIndication = errind.nonReportable + ) + + # rfc3412: 7.1.4 + # Since there's no SNMP engine identification in v1/2c, + # set destination contextEngineId to ours + if not contextEngineId: + contextEngineId = snmpEngineID + + # rfc3412: 7.1.5 + if not contextName: + contextName = null + + # rfc3412: 7.1.6 + scopedPDU = ( contextEngineId, contextName, pdu ) + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) + + msg = self._snmpMsgSpec + msg.setComponentByPosition(0, messageProcessingModel) + msg.setComponentByPosition(2) + msg.getComponentByPosition(2).setComponentByType( + pdu.tagSet, pdu, verifyConstraints=False + ) + + # att: msgId not set back to PDU as it's up to responder app + + # rfc3412: 7.1.7 + globalData = ( msg, ) + + k = int(securityModel) + if k in snmpEngine.securityModels: + smHandler = snmpEngine.securityModels[k] + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityModel + ) + + securityEngineId = snmpEngineID + + # rfc3412: 7.1.8.a + ( securityParameters, + wholeMsg ) = smHandler.generateResponseMsg( + snmpEngine, + self.messageProcessingModelID, + globalData, + maxMessageSize, + securityModel, + snmpEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ) + + return ( transportDomain, transportAddress, wholeMsg ) + + # rfc3412: 7.2.1 + + def prepareDataElements( + self, + snmpEngine, + transportDomain, + transportAddress, + wholeMsg + ): + # rfc3412: 7.2.2 + try: + msg, restOfwholeMsg = decoder.decode( + wholeMsg, asn1Spec=self._snmpMsgSpec + ) + except PyAsn1Error: + debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (sys.exc_info()[1],)) + snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') + snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 + raise error.StatusInformation( + errorIndication = errind.parseError + ) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) + + # rfc3412: 7.2.3 + msgVersion = messageProcessingModel = msg.getComponentByPosition(0) + + # rfc2576: 5.2.1 + snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + securityParameters = ( + msg.getComponentByPosition(1), + (transportDomain, transportAddress), + ('0.0.0.0', 0) # XXX + ) + messageProcessingModel = int(msg.getComponentByPosition(0)) + securityModel = messageProcessingModel + 1 + securityLevel = 1 + + # rfc3412: 7.2.4 -- 7.2.5 -> noop + + k = int(securityModel) + if k in snmpEngine.securityModels: + smHandler = snmpEngine.securityModels[k] + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityModel + ) + + # rfc3412: 7.2.6 + ( securityEngineID, + securityName, + scopedPDU, + maxSizeResponseScopedPDU, + securityStateReference ) = smHandler.processIncomingMsg( + snmpEngine, + messageProcessingModel, + snmpEngineMaxMessageSize.syntax, + securityParameters, + securityModel, + securityLevel, + wholeMsg, + msg + ) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM returned securityEngineID %r securityName %r' % (securityEngineID, securityName)) + + # rfc3412: 7.2.6a --> noop + + # rfc3412: 7.2.7 + contextEngineId, contextName, pdu = scopedPDU + + # rfc2576: 5.2.1 + pduVersion = msgVersion + pduType = pdu.tagSet + + # XXX use cache + # set stateref to null as in v3 model + stateReference = securityStateReference + + # rfc3412: 7.2.8, 7.2.9 -> noop + + # rfc3412: 7.2.10 + if pduType in rfc3411.responseClassPDUs: + # (wild hack: use PDU reqID at MsgID) + msgID = pdu.getComponentByPosition(0) + + # 7.2.10a + try: + cachedReqParams = self._cache.popByMsgId(int(msgID)) + except error.ProtocolError: + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.dataMismatch + ) + + # 7.2.10b + sendPduHandle = cachedReqParams['sendPduHandle'] + else: + sendPduHandle = None + + statusInformation = None + + # rfc3412: 7.2.11 -> noop + + # rfc3412: 7.2.12 + if pduType in rfc3411.responseClassPDUs: + # rfc3412: 7.2.12a -> noop + # rfc3412: 7.2.12b + if securityModel != cachedReqParams['securityModel'] or \ + securityName != cachedReqParams['securityName'] or \ + securityLevel != cachedReqParams['securityLevel'] or \ + contextEngineId != cachedReqParams['contextEngineId'] or \ + contextName != cachedReqParams['contextName']: + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.dataMismatch + ) + + # rfc3412: 7.2.12c + smHandler.releaseStateInformation(securityStateReference) + + # rfc3412: 7.2.12d + return ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) + + # rfc3412: 7.2.13 + if pduType in rfc3411.confirmedClassPDUs: + # (wild hack: use PDU reqID at MsgID) + msgID = pdu.getComponentByPosition(0) + + # rfc3412: 7.2.13a + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + if securityEngineID != snmpEngineID.syntax: + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.engineIDMispatch + ) + + # rfc3412: 7.2.13b + stateReference = self._cache.newStateReference() + self._cache.pushByStateRef( + stateReference, + msgVersion=messageProcessingModel, + msgID=msgID, + contextEngineId=contextEngineId, + contextName=contextName, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + securityStateReference=securityStateReference, + msgMaxSize=snmpEngineMaxMessageSize.syntax, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, + transportDomain=transportDomain, + transportAddress=transportAddress + ) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: cached by new stateReference %s' % stateReference) + + # rfc3412: 7.2.13c + return ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) + + # rfc3412: 7.2.14 + if pduType in rfc3411.unconfirmedClassPDUs: + # This is not specified explicitly in RFC + smHandler.releaseStateInformation(securityStateReference) + return ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) + + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.unsupportedPDUtype + ) + +class SnmpV2cMessageProcessingModel(SnmpV1MessageProcessingModel): + messageProcessingModelID = univ.Integer(1) # SNMPv2c + snmpMsgSpec = v2c.Message diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/rfc3412.py python-pysnmp4-4.2.2/pysnmp/proto/mpmod/rfc3412.py --- python-pysnmp4-4.1.9a/pysnmp/proto/mpmod/rfc3412.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/mpmod/rfc3412.py 2012-04-20 19:26:10.000000000 +0000 @@ -0,0 +1,796 @@ +# 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 +from pyasn1.type import univ, namedtype, constraint +from pyasn1.codec.ber import decoder +from pyasn1.error import PyAsn1Error +from pysnmp import debug + +# API to rfc1905 protocol objects +pMod = api.protoModules[api.protoVersion2c] + +# SNMPv3 message format + +class ScopedPDU(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('contextEngineId', univ.OctetString()), + namedtype.NamedType('contextName', univ.OctetString()), + namedtype.NamedType('data', rfc1905.PDUs()) + ) + +class ScopedPduData(univ.Choice): + componentType = namedtype.NamedTypes( + namedtype.NamedType('plaintext', ScopedPDU()), + namedtype.NamedType('encryptedPDU', univ.OctetString()), + ) + +class HeaderData(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('msgID', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), + namedtype.NamedType('msgMaxSize', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647))), + namedtype.NamedType('msgFlags', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 1))), + namedtype.NamedType('msgSecurityModel', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647))) + ) + +class SNMPv3Message(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), + namedtype.NamedType('msgGlobalData', HeaderData()), + namedtype.NamedType('msgSecurityParameters', univ.OctetString()), + namedtype.NamedType('msgData', ScopedPduData()) + ) + +# XXX move somewhere? +_snmpErrors = { + (1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0): 'unsupportedSecLevel', + (1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0): 'notInTimeWindow', + (1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0): 'unknownUserName', + (1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0): 'unknownEngineID', + (1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0): 'wrongDigest', + (1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0): 'decryptionError', + } + +class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): + messageProcessingModelID = univ.Integer(3) # SNMPv3 + snmpMsgSpec = SNMPv3Message + _emptyStr = univ.OctetString('') + _msgFlags = { + 0: univ.OctetString('\x00'), + 1: univ.OctetString('\x01'), + 3: univ.OctetString('\x03'), + 4: univ.OctetString('\x04'), + 5: univ.OctetString('\x05'), + 7: univ.OctetString('\x07') + } + def __init__(self): + AbstractMessageProcessingModel.__init__(self) + self.__scopedPDU = ScopedPDU() + self.__engineIDs = {} + self.__engineIDsExpQueue = {} + self.__expirationTimer = 0 + + # 7.1.1a + def prepareOutgoingMessage( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + expectResponse, + sendPduHandle + ): + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID = snmpEngineID.syntax + + # 7.1.1b + msgID = self._cache.newMsgID() + + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID) + + k = (transportDomain, transportAddress) + if k in self.__engineIDs: + peerSnmpEngineData = self.__engineIDs[k] + else: + peerSnmpEngineData = None + + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % (peerSnmpEngineData, transportDomain, transportAddress)) + + # 7.1.4 + if contextEngineId is None: + if peerSnmpEngineData is None: + contextEngineId = snmpEngineID + else: + contextEngineId = peerSnmpEngineData['contextEngineId'] + # Defaulting contextEngineID to securityEngineID should + # probably be done on Agent side (see 7.1.3.d.2,) so this + # is a sort of workaround. + if not contextEngineId: + contextEngineId = peerSnmpEngineData['securityEngineID'] + # 7.1.5 + if not contextName: + contextName = self._emptyStr + + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) + + # 7.1.6 + scopedPDU = self.__scopedPDU + scopedPDU.setComponentByPosition(0, contextEngineId) + scopedPDU.setComponentByPosition(1, contextName) + scopedPDU.setComponentByPosition(2) + scopedPDU.getComponentByPosition(2).setComponentByType( + pdu.tagSet, pdu, verifyConstraints=False + ) + + # 7.1.7 + msg = self._snmpMsgSpec + + # 7.1.7a + msg.setComponentByPosition( + 0, self.messageProcessingModelID, verifyConstraints=False + ) + headerData = msg.setComponentByPosition(1).getComponentByPosition(1) + + # 7.1.7b + headerData.setComponentByPosition(0, msgID, verifyConstraints=False) + + snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + + # 7.1.7c + # XXX need to coerce MIB value as it has incompatible constraints set + headerData.setComponentByPosition( + 1, snmpEngineMaxMessageSize.syntax, verifyConstraints=False + ) + + # 7.1.7d + msgFlags = 0 + if securityLevel == 1: + pass + elif securityLevel == 2: + msgFlags = msgFlags | 0x01 + elif securityLevel == 3: + msgFlags = msgFlags | 0x03 + else: + raise error.ProtocolError( + 'Unknown securityLevel %s' % securityLevel + ) + + if pdu.tagSet in rfc3411.confirmedClassPDUs: + msgFlags = msgFlags | 0x04 + + headerData.setComponentByPosition( + 2, self._msgFlags[msgFlags], verifyConstraints=False + ) + + # 7.1.7e + # XXX need to coerce MIB value as it has incompatible constraints set + headerData.setComponentByPosition(3, int(securityModel)) + + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),)) + + if securityModel in snmpEngine.securityModels: + smHandler = snmpEngine.securityModels[securityModel] + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityModel + ) + + # 7.1.9.a + if pdu.tagSet in rfc3411.unconfirmedClassPDUs: + securityEngineID = snmpEngineID + else: + if peerSnmpEngineData is None: + # Force engineID discovery (rfc3414, 4) + securityEngineID = securityName = self._emptyStr + securityLevel = 1 + # Clear possible auth&priv flags + headerData.setComponentByPosition( + 2, self._msgFlags[msgFlags & 0xfc], verifyConstraints=False + ) + # XXX + scopedPDU = self.__scopedPDU + scopedPDU.setComponentByPosition( + 0, self._emptyStr, verifyConstraints=False + ) + scopedPDU.setComponentByPosition(1, contextName) + scopedPDU.setComponentByPosition(2) + + # Use dead-empty PDU for engine-discovery report + emptyPdu = pdu.clone() + pMod.apiPDU.setDefaults(emptyPdu) + + scopedPDU.getComponentByPosition(2).setComponentByType( + emptyPdu.tagSet, emptyPdu, verifyConstraints=False + ) + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: force engineID discovery') + else: + securityEngineID = peerSnmpEngineData['securityEngineID'] + + debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: securityEngineID %r' % (securityEngineID,)) + + # 7.1.9.b + ( securityParameters, + wholeMsg ) = smHandler.generateRequestMsg( + snmpEngine, + self.messageProcessingModelID, + msg, + snmpEngineMaxMessageSize.syntax, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU + ) + + # Message size constraint verification + if len(wholeMsg) > snmpEngineMaxMessageSize.syntax: + raise error.StatusInformation(errorIndication=errind.tooBig) + + # 7.1.9.c + if pdu.tagSet in rfc3411.confirmedClassPDUs: + # XXX rfc bug? why stateReference should be created? + self._cache.pushByMsgId( + msgID, + sendPduHandle=sendPduHandle, + msgID=msgID, + snmpEngineID=snmpEngineID, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + transportDomain=transportDomain, + transportAddress=transportAddress + ) + + return ( transportDomain, + transportAddress, + wholeMsg ) + + def prepareResponseMessage( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ): + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID = snmpEngineID.syntax + + # 7.1.2.b + cachedParams = self._cache.popByStateRef(stateReference) + msgID = cachedParams['msgID'] + contextEngineId = cachedParams['contextEngineId'] + contextName = cachedParams['contextName'] + securityModel = cachedParams['securityModel'] + securityName = cachedParams['securityName'] + securityLevel = cachedParams['securityLevel'] + securityStateReference = cachedParams['securityStateReference'] + reportableFlag = cachedParams['reportableFlag'] + maxMessageSize = cachedParams['msgMaxSize'] + transportDomain = cachedParams['transportDomain'] + transportAddress = cachedParams['transportAddress'] + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % (stateReference)) + + # 7.1.3 + if statusInformation is not None and 'oid' in statusInformation: + # 7.1.3a + if pdu is not None: + requestID = pdu.getComponentByPosition(0) + pduType = pdu.tagSet + else: + pduType = None + + # 7.1.3b + if pdu is None and not reportableFlag or \ + pduType is not None and \ + pduType not in rfc3411.confirmedClassPDUs: + raise error.StatusInformation( + errorIndication = errind.loopTerminated + ) + + # 7.1.3c + reportPDU = rfc1905.ReportPDU() + pMod.apiPDU.setVarBinds( + reportPDU, + ((statusInformation['oid'], statusInformation['val']),) + ) + pMod.apiPDU.setErrorStatus(reportPDU, 0) + pMod.apiPDU.setErrorIndex(reportPDU, 0) + if pdu is None: + pMod.apiPDU.setRequestID(reportPDU, 0) + else: + pMod.apiPDU.setRequestID(reportPDU, requestID) + + # 7.1.3d.1 + if 'securityLevel' in statusInformation: + securityLevel = statusInformation['securityLevel'] + else: + securityLevel = 1 + + # 7.1.3d.2 + if 'contextEngineId' in statusInformation: + contextEngineId = statusInformation['contextEngineId'] + else: + contextEngineId = snmpEngineID + + # 7.1.3d.3 + if 'contextName' in statusInformation: + contextName = statusInformation['contextName'] + else: + contextName = "" + + # 7.1.3e + pdu = reportPDU + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation) + # 7.1.4 + if not contextEngineId: + contextEngineId = snmpEngineID # XXX impl-dep manner + + # 7.1.5 + if not contextName: + contextName = self._emptyStr + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) + + # 7.1.6 + scopedPDU = self.__scopedPDU + scopedPDU.setComponentByPosition(0, contextEngineId) + scopedPDU.setComponentByPosition(1, contextName) + scopedPDU.setComponentByPosition(2) + scopedPDU.getComponentByPosition(2).setComponentByType( + pdu.tagSet, pdu, verifyConstraints=False + ) + + # 7.1.7 + msg = self._snmpMsgSpec + + # 7.1.7a + msg.setComponentByPosition( + 0, self.messageProcessingModelID, verifyConstraints=False + ) + + headerData = msg.setComponentByPosition(1).getComponentByPosition(1) + + # 7.1.7b + headerData.setComponentByPosition( + 0, msgID, verifyConstraints=False + ) + + snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + + # 7.1.7c + # XXX need to coerce MIB value as it has incompatible constraints set + headerData.setComponentByPosition( + 1, snmpEngineMaxMessageSize.syntax, verifyConstraints=False + ) + + # 7.1.7d + msgFlags = 0 + if securityLevel == 1: + pass + elif securityLevel == 2: + msgFlags = msgFlags | 0x01 + elif securityLevel == 3: + msgFlags = msgFlags | 0x03 + else: + raise error.ProtocolError( + 'Unknown securityLevel %s' % securityLevel + ) + + if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed? + msgFlags = msgFlags | 0x04 + + headerData.setComponentByPosition( + 2, self._msgFlags[msgFlags], verifyConstraints=False + ) + + # 7.1.7e + headerData.setComponentByPosition( + 3, securityModel, verifyConstraints=False + ) + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),)) + + if securityModel in snmpEngine.securityModels: + smHandler = snmpEngine.securityModels[securityModel] + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityModel + ) + + # 7.1.8a + try: + ( securityParameters, + wholeMsg ) = smHandler.generateResponseMsg( + snmpEngine, + self.messageProcessingModelID, + msg, + snmpEngineMaxMessageSize.syntax, + securityModel, + snmpEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ) + except error.StatusInformation: + # 7.1.8.b + raise + + debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: SM finished') + + # Message size constraint verification + if len(wholeMsg) > min(snmpEngineMaxMessageSize.syntax, maxMessageSize): + raise error.StatusInformation(errorIndication=errind.tooBig) + + return ( transportDomain, transportAddress, wholeMsg ) + + # 7.2.1 + + def prepareDataElements( + self, + snmpEngine, + transportDomain, + transportAddress, + wholeMsg + ): + # 7.2.2 + try: + msg, restOfwholeMsg = decoder.decode( + wholeMsg, asn1Spec=self._snmpMsgSpec + ) + except PyAsn1Error: + debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (sys.exc_info()[1],)) + snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') + snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 + raise error.StatusInformation( + errorIndication = errind.parseError + ) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) + + # 7.2.3 + headerData = msg.getComponentByPosition(1) + msgVersion = messageProcessingModel = msg.getComponentByPosition(0) + msgID = headerData.getComponentByPosition(0) + msgFlags, = headerData.getComponentByPosition(2).asNumbers() + maxMessageSize = headerData.getComponentByPosition(1) + securityModel = headerData.getComponentByPosition(3) + securityParameters = msg.getComponentByPosition(2) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (msgVersion, msgID, securityModel)) + + # 7.2.4 + if securityModel not in snmpEngine.securityModels: + snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpUnknownSecurityModels') + snmpUnknownSecurityModels.syntax = snmpUnknownSecurityModels.syntax + 1 + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityModel + ) + + # 7.2.5 + if msgFlags & 0x03 == 0x00: + securityLevel = 1 + elif (msgFlags & 0x03) == 0x01: + securityLevel = 2 + elif (msgFlags & 0x03) == 0x03: + securityLevel = 3 + else: + snmpInvalidMsgs = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInvalidMsgs') + snmpInvalidMsgs.syntax = snmpInvalidMsgs.syntax + 1 + raise error.StatusInformation( + errorIndication = errind.invalidMsg + ) + + if msgFlags & 0x04: + reportableFlag = 1 + else: + reportableFlag = 0 + + # 7.2.6 + smHandler = snmpEngine.securityModels[securityModel] + try: + ( securityEngineID, + securityName, + scopedPDU, + maxSizeResponseScopedPDU, + securityStateReference ) = smHandler.processIncomingMsg( + snmpEngine, + messageProcessingModel, + maxMessageSize, + securityParameters, + securityModel, + securityLevel, + wholeMsg, + msg + ) + debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded') + except error.StatusInformation: + statusInformation, origTraceback = sys.exc_info()[1:3] + debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM failed, statusInformation %s' % statusInformation) + if 'errorIndication' in statusInformation: + # 7.2.6a + if 'oid' in statusInformation: + # 7.2.6a1 + securityStateReference = statusInformation[ + 'securityStateReference' + ] + contextEngineId = statusInformation['contextEngineId'] + contextName = statusInformation['contextName'] + if 'scopedPDU' in statusInformation: + scopedPDU = statusInformation['scopedPDU'] + pdu = scopedPDU.getComponentByPosition(2).getComponent() + else: + pdu = None + maxSizeResponseScopedPDU = statusInformation[ + 'maxSizeResponseScopedPDU' + ] + securityName = None # XXX secmod cache used + + # 7.2.6a2 + stateReference = self._cache.newStateReference() + self._cache.pushByStateRef( + stateReference, + msgVersion=messageProcessingModel, + msgID=msgID, + contextEngineId=contextEngineId, + contextName=contextName, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + securityStateReference=securityStateReference, + reportableFlag=reportableFlag, + msgMaxSize=maxMessageSize, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, + transportDomain=transportDomain, + transportAddress=transportAddress + ) + + # 7.2.6a3 + try: + snmpEngine.msgAndPduDsp.returnResponsePdu( + snmpEngine, + 3, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + 1, + pdu, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ) + except error.StatusInformation: + pass + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: error reported') + # 7.2.6b + if sys.version_info[0] <= 2: + raise statusInformation + else: + try: + raise statusInformation.with_traceback(origTraceback) + finally: + # Break cycle between locals and traceback object + # (seems to be irrelevant on Py3 but just in case) + del origTraceback + else: + # Sniff for engineIDs + k = (transportDomain, transportAddress) + if k not in self.__engineIDs: + contextEngineId, contextName, pdus = scopedPDU + pdu = pdus.getComponent() + # Here we assume that authentic/default EngineIDs + # come only in the course of engine-to-engine communication. + if pdu.tagSet in rfc3411.internalClassPDUs: + self.__engineIDs[k] = { + 'securityEngineID': securityEngineID, + 'contextEngineId': contextEngineId, + 'contextName': contextName + } + + expireAt = self.__expirationTimer + 300 + if expireAt not in self.__engineIDsExpQueue: + self.__engineIDsExpQueue[expireAt] = [] + self.__engineIDsExpQueue[expireAt].append(k) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: cache securityEngineID %r for %r %r' % (securityEngineID, transportDomain, transportAddress)) + + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + snmpEngineID = snmpEngineID.syntax + + # 7.2.7 XXX PDU would be parsed here? + contextEngineId, contextName, pdu = scopedPDU + pdu = pdu.getComponent() # PDUs + + # 7.2.8 + pduVersion = api.protoVersion2c + + # 7.2.9 + pduType = pdu.tagSet + + # 7.2.10 + if pduType in rfc3411.responseClassPDUs or \ + pduType in rfc3411.internalClassPDUs: + # 7.2.10a + try: + cachedReqParams = self._cache.popByMsgId(msgID) + except error.ProtocolError: + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.dataMismatch + ) + # 7.2.10b + sendPduHandle = cachedReqParams['sendPduHandle'] + else: + sendPduHandle = None + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID)) + + # 7.2.11 + if pduType in rfc3411.internalClassPDUs: + # 7.2.11a + varBinds = pMod.apiPDU.getVarBinds(pdu) + if varBinds: + statusInformation = error.StatusInformation( + errorIndication=_snmpErrors.get( + varBinds[0][0], 'errorReportReceived' + ), + oid=varBinds[0][0], + val=varBinds[0][1], + sendPduHandle=sendPduHandle + ) + + # 7.2.11b (incomplete implementation) + + # 7.2.11c + smHandler.releaseStateInformation(securityStateReference) + + # 7.2.11d + stateReference = None + + # 7.2.11e XXX may need to pass Reports up to app in some cases... + raise statusInformation + + statusInformation = None # no errors ahead + + # 7.2.12 + if pduType in rfc3411.responseClassPDUs: + # 7.2.12a -> noop + + # 7.2.12b + if securityModel != cachedReqParams['securityModel'] or \ + securityName != cachedReqParams['securityName'] or \ + securityLevel != cachedReqParams['securityLevel'] or \ + contextEngineId != cachedReqParams['contextEngineId'] or \ + contextName != cachedReqParams['contextName']: + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.dataMismatch + ) + + # 7.2.12c + smHandler.releaseStateInformation(securityStateReference) + stateReference = None + + # 7.2.12d + return ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) + + # 7.2.13 + if pduType in rfc3411.confirmedClassPDUs: + # 7.2.13a + if securityEngineID != snmpEngineID: + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.engineIDMismatch + ) + + # 7.2.13b + stateReference = self._cache.newStateReference() + self._cache.pushByStateRef( + stateReference, + msgVersion=messageProcessingModel, + msgID=msgID, + contextEngineId=contextEngineId, + contextName=contextName, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + securityStateReference=securityStateReference, + reportableFlag=reportableFlag, + msgMaxSize=maxMessageSize, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, + transportDomain=transportDomain, + transportAddress=transportAddress + ) + + debug.logger & debug.flagMP and debug.logger('prepareDataElements: new stateReference %s' % stateReference) + + # 7.2.13c + return ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) + + # 7.2.14 + if pduType in rfc3411.unconfirmedClassPDUs: + # Pass new stateReference to let app browse request details + stateReference = self._cache.newStateReference() + + # This is not specified explicitly in RFC + smHandler.releaseStateInformation(securityStateReference) + + return ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + pdu, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) + + smHandler.releaseStateInformation(securityStateReference) + raise error.StatusInformation( + errorIndication = errind.unsupportedPDUtype + ) + + def __expireEnginesInfo(self): + if self.__expirationTimer in self.__engineIDsExpQueue: + for engineKey in self.__engineIDsExpQueue[self.__expirationTimer]: + del self.__engineIDs[engineKey] + debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %s' % (engineKey,)) + del self.__engineIDsExpQueue[self.__expirationTimer] + self.__expirationTimer = self.__expirationTimer + 1 + + def receiveTimerTick(self, snmpEngine, timeNow): + self.__expireEnginesInfo() + AbstractMessageProcessingModel.receiveTimerTick( + self, snmpEngine, timeNow + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/proxy/rfc2576.py python-pysnmp4-4.2.2/pysnmp/proto/proxy/rfc2576.py --- python-pysnmp4-4.1.9a/pysnmp/proto/proxy/rfc2576.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/proxy/rfc2576.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,295 @@ +# PDU v1/v2c two-way proxy +from pysnmp.proto import rfc1905, rfc3411, error +from pysnmp.proto.api import v1, v2c +from pysnmp import debug + +# 2.1.1 + +__v1ToV2ValueMap = { + v1.Integer.tagSet: v2c.Integer32(), + v1.OctetString.tagSet: v2c.OctetString(), + v1.Null.tagSet: v2c.Null(), + v1.ObjectIdentifier.tagSet: v2c.ObjectIdentifier(), + v1.IpAddress.tagSet: v2c.IpAddress(), + v1.Counter.tagSet: v2c.Counter32(), + v1.Gauge.tagSet: v2c.Gauge32(), + v1.TimeTicks.tagSet: v2c.TimeTicks(), + v1.Opaque.tagSet: v2c.Opaque() + } + +__v2ToV1ValueMap = { # XXX do not re-create same-type items? + v2c.Integer32.tagSet: v1.Integer(), + v2c.OctetString.tagSet: v1.OctetString(), + v2c.Null.tagSet: v1.Null(), + v2c.ObjectIdentifier.tagSet: v1.ObjectIdentifier(), + v2c.IpAddress.tagSet: v1.IpAddress(), + v2c.Counter32.tagSet: v1.Counter(), + v2c.Gauge32.tagSet: v1.Gauge(), + v2c.TimeTicks.tagSet: v1.TimeTicks(), + v2c.Opaque.tagSet: v1.Opaque() + } + +# PDU map + +__v1ToV2PduMap = { + v1.GetRequestPDU.tagSet: v2c.GetRequestPDU(), + v1.GetNextRequestPDU.tagSet: v2c.GetNextRequestPDU(), + v1.SetRequestPDU.tagSet: v2c.SetRequestPDU(), + v1.GetResponsePDU.tagSet: v2c.ResponsePDU(), + v1.TrapPDU.tagSet: v2c.SNMPv2TrapPDU() + } + +__v2ToV1PduMap = { + v2c.GetRequestPDU.tagSet: v1.GetRequestPDU(), + v2c.GetNextRequestPDU.tagSet: v1.GetNextRequestPDU(), + v2c.SetRequestPDU.tagSet: v1.SetRequestPDU(), + v2c.ResponsePDU.tagSet: v1.GetResponsePDU(), + v2c.SNMPv2TrapPDU.tagSet: v1.TrapPDU(), + v2c.GetBulkRequestPDU.tagSet: v1.GetNextRequestPDU() # 4.1.1 + } + +# Trap map + +__v1ToV2TrapMap = { + 0: (1,3,6,1,6,3,1,1,5,1), + 1: (1,3,6,1,6,3,1,1,5,2), + 2: (1,3,6,1,6,3,1,1,5,3), + 3: (1,3,6,1,6,3,1,1,5,4), + 4: (1,3,6,1,6,3,1,1,5,5), + 5: (1,3,6,1,6,3,1,1,5,6) + } + +__v2ToV1TrapMap = { + (1,3,6,1,6,3,1,1,5,1): 0, + (1,3,6,1,6,3,1,1,5,2): 1, + (1,3,6,1,6,3,1,1,5,3): 2, + (1,3,6,1,6,3,1,1,5,4): 3, + (1,3,6,1,6,3,1,1,5,5): 4, + (1,3,6,1,6,3,1,1,5,6): 5 + } + +# 4.3 + +__v2ToV1ErrorMap = { + 0: 0, + 1: 1, + 5: 5, + 10: 3, + 9: 3, + 7: 3, + 8: 3, + 12: 3, + 6: 2, + 17: 2, + 11: 2, + 18: 2, + 13: 5, + 14: 5, + 15: 5, + 16: 2 + } + +__zeroInt = v1.Integer(0) + +def v1ToV2(v1Pdu, origV2Pdu=None): + pduType = v1Pdu.tagSet + v2Pdu = __v1ToV2PduMap[pduType].clone() + + debug.logger & debug.flagPrx and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint()) + + v2VarBinds = [] + + # 3.1 + if pduType in rfc3411.notificationClassPDUs: + # 3.1.1 + sysUpTime = v1.apiTrapPDU.getTimeStamp(v1Pdu) + + # 3.1.2 + genericTrap = v1.apiTrapPDU.getGenericTrap(v1Pdu) + if genericTrap == 6: + snmpTrapOIDParam = v1.apiTrapPDU.getEnterprise(v1Pdu) + (0,) + \ + (v1.apiTrapPDU.getSpecificTrap(v1Pdu),) + + # 3.1.3 + else: + snmpTrapOIDParam = v2c.ObjectIdentifier( + __v1ToV2TrapMap[genericTrap] + ) + + # 3.1.4 (XXX snmpTrapCommunity.0 is missing here) + v2VarBinds.append((v2c.apiTrapPDU.sysUpTime, sysUpTime)) + v2VarBinds.append((v2c.apiTrapPDU.snmpTrapOID, snmpTrapOIDParam)) + v2VarBinds.append( + (v2c.apiTrapPDU.snmpTrapAddress, v1.apiTrapPDU.getAgentAddr(v1Pdu)) + ) + v2VarBinds.append((v2c.apiTrapPDU.snmpTrapCommunity, v2c.OctetString(""))) + v2VarBinds.append((v2c.apiTrapPDU.snmpTrapEnterprise, + v1.apiTrapPDU.getEnterprise(v1Pdu))) + + varBinds = v1.apiTrapPDU.getVarBinds(v1Pdu) + else: + varBinds = v1.apiPDU.getVarBinds(v1Pdu) + + # Translate Var-Binds + for oid, v1Val in varBinds: + # 2.1.1.11 + if v1Val.tagSet == v1.NetworkAddress.tagSet: + v1Val = v1Val.getComponent() + v2VarBinds.append( + (oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val)) + ) + + if pduType in rfc3411.responseClassPDUs: + # 4.1.2.2.1&2 + errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu)) + errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu)) + if errorStatus == 2: # noSuchName + if origV2Pdu.tagSet == v2c.GetNextRequestPDU.tagSet: + v2VarBinds[errorIndex-1] = ( + v2VarBinds[errorIndex-1][0], rfc1905.endOfMibView + ) + else: + v2VarBinds[errorIndex-1] = ( + v2VarBinds[errorIndex-1][0], rfc1905.noSuchObject + ) + # one-to-one mapping + v2c.apiPDU.setErrorStatus(v2Pdu, errorStatus) + v2c.apiPDU.setErrorIndex(v2Pdu, errorIndex) + + # 4.1.2.1 --> no-op + + if pduType not in rfc3411.notificationClassPDUs: + v2c.apiPDU.setRequestID(v2Pdu, int(v1.apiPDU.getRequestID(v1Pdu))) + + v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds) + + debug.logger & debug.flagPrx and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint()) + + return v2Pdu + +def v2ToV1(v2Pdu, origV1Pdu=None): + debug.logger & debug.flagPrx and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint()) + + pduType = v2Pdu.tagSet + + if pduType in __v2ToV1PduMap: + v1Pdu = __v2ToV1PduMap[pduType].clone() + else: + raise error.ProtocolError('Unsupported PDU type') + + v2VarBinds = v2c.apiPDU.getVarBinds(v2Pdu) + v1VarBinds = [] + + # 3.2 + if pduType in rfc3411.notificationClassPDUs: + # 3.2.1 + (snmpTrapOID, snmpTrapOIDParam) = v2VarBinds[1] + if snmpTrapOID != v2c.apiTrapPDU.snmpTrapOID: + raise error.ProtocolError('Second OID not snmpTrapOID') + + if snmpTrapOIDParam in __v2ToV1TrapMap: + for oid, val in v2VarBinds: + if oid == v2c.apiTrapPDU.snmpTrapEnterprise: + v1.apiTrapPDU.setEnterprise(v1Pdu, val) + break + else: + # snmpTraps + v1.apiTrapPDU.setEnterprise(v1Pdu, (1, 3, 6, 1, 6, 3, 1, 1, 5)) + else: + if snmpTrapOIDParam[-2] == 0: + v1.apiTrapPDU.setEnterprise(v1Pdu, snmpTrapOIDParam[:-2]) + else: + v1.apiTrapPDU.setEnterprise(v1Pdu, snmpTrapOIDParam[:-1]) + + # 3.2.2 + for oid, val in v2VarBinds: + # snmpTrapAddress + if oid == v2c.apiTrapPDU.snmpTrapAddress: + v1.apiTrapPDU.setAgentAddr(v1Pdu, val) + break + else: + v1.apiTrapPDU.setAgentAddr(v1Pdu, v1.apiTrapPDU.agentAddress) + + # 3.2.3 + if snmpTrapOIDParam in __v2ToV1TrapMap: + v1.apiTrapPDU.setGenericTrap(v1Pdu, __v2ToV1TrapMap[snmpTrapOIDParam]) + else: + v1.apiTrapPDU.setGenericTrap(v1Pdu, 6) + + # 3.2.4 + if snmpTrapOIDParam in __v2ToV1TrapMap: + v1.apiTrapPDU.setSpecificTrap(v1Pdu, __zeroInt) + else: + v1.apiTrapPDU.setSpecificTrap(v1Pdu, snmpTrapOIDParam[-1]) + + # 3.2.5 + v1.apiTrapPDU.setTimeStamp(v1Pdu, v2VarBinds[0][1]) + + __v2VarBinds = [] + for oid, val in v2VarBinds[2:]: + if oid in __v2ToV1TrapMap or \ + oid in (v2c.apiTrapPDU.sysUpTime, + v2c.apiTrapPDU.snmpTrapAddress, + v2c.apiTrapPDU.snmpTrapEnterprise): + continue + __v2VarBinds.append((oid, val)) + v2VarBinds = __v2VarBinds; + + # 3.2.6 --> done below + + else: + v1.apiPDU.setErrorStatus(v1Pdu, __zeroInt) + v1.apiPDU.setErrorIndex(v1Pdu, __zeroInt) + + if pduType in rfc3411.responseClassPDUs: + idx = len(v2VarBinds)-1 + while idx >= 0: + # 4.1.2.1 + oid, val = v2VarBinds[idx] + if v2c.Counter64.tagSet == val.tagSet: + if origV1Pdu.tagSet == v1.GetRequestPDU.tagSet: + v1.apiPDU.setErrorStatus(v1Pdu, 2) + v1.apiPDU.setErrorIndex(v1Pdu, idx+1) + break + elif origV1Pdu.tagSet == v1.GetNextRequestPDU.tagSet: + raise error.StatusInformation(idx=idx, pdu=v2Pdu) + else: + raise error.ProtocolError('Counter64 on the way') + + # 4.1.2.2.1&2 + if isinstance(val, v2c.Null): + v1.apiPDU.setErrorStatus(v1Pdu, 2) + v1.apiPDU.setErrorIndex(v1Pdu, idx+1) + + idx = idx - 1 + + # 4.1.2.3.1 + v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu) + if v2ErrorStatus: + v1.apiPDU.setErrorStatus( + v1Pdu, __v2ToV1ErrorMap[v2ErrorStatus] + ) + v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu)) + + # Translate Var-Binds + if pduType in rfc3411.responseClassPDUs and \ + v1.apiPDU.getErrorStatus(v1Pdu): + v1VarBinds = v1.apiPDU.getVarBinds(origV1Pdu) + else: + for oid, v2Val in v2VarBinds: + v1VarBinds.append( + (oid, __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val)) + ) + + if pduType in rfc3411.notificationClassPDUs: + v1.apiTrapPDU.setVarBinds(v1Pdu, v1VarBinds) + else: + v1.apiPDU.setVarBinds(v1Pdu, v1VarBinds) + + v1.apiPDU.setRequestID( + v1Pdu, v2c.apiPDU.getRequestID(v2Pdu) + ) + + debug.logger & debug.flagPrx and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint()) + + return v1Pdu diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/rfc1155.py python-pysnmp4-4.2.2/pysnmp/proto/rfc1155.py --- python-pysnmp4-4.1.9a/pysnmp/proto/rfc1155.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/rfc1155.py 2011-11-08 14:45:55.000000000 +0000 @@ -0,0 +1,102 @@ +from pyasn1.type import univ, tag, constraint, namedtype +from pyasn1.error import PyAsn1Error +from pysnmp.proto import error + +class IpAddress(univ.OctetString): + tagSet = univ.OctetString.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) + ) + subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( + 4, 4 + ) + + def prettyIn(self, value): + if isinstance(value, str) and len(value) != 4: + try: + value = [ int(x) for x in value.split('.') ] + 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, 4294967295 + ) + +class NetworkAddress(univ.Choice): + componentType = namedtype.NamedTypes( + namedtype.NamedType('internet', IpAddress()) + ) + +class Gauge(univ.Integer): + tagSet = univ.Integer.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) + ) + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + 0, 4294967295 + ) + +class TimeTicks(univ.Integer): + tagSet = univ.Integer.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) + ) + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + 0, 4294967295 + ) + +class Opaque(univ.OctetString): + tagSet = univ.OctetString.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) + ) + +class ObjectName(univ.ObjectIdentifier): pass + +class TypeCoercionHackMixIn: # XXX + # Reduce ASN1 type check to simple tag check as SMIv2 objects may + # not be constraints-compatible with those used in SNMP PDU. + def _verifyComponent(self, idx, value): + componentType = self._componentType + if componentType: + if idx >= len(componentType): + raise PyAsn1Error( + 'Component type error out of range' + ) + t = componentType[idx].getType() + if not t.getTagSet().isSuperTagSetOf(value.getTagSet()): + raise PyAsn1Error('Component type error %r vs %r' % (t, value)) + +class SimpleSyntax(TypeCoercionHackMixIn, univ.Choice): + componentType = namedtype.NamedTypes( + namedtype.NamedType('number', univ.Integer()), + namedtype.NamedType('string', univ.OctetString()), + namedtype.NamedType('object', univ.ObjectIdentifier()), + namedtype.NamedType('empty', univ.Null()) + ) + +class ApplicationSyntax(TypeCoercionHackMixIn, univ.Choice): + componentType = namedtype.NamedTypes( + namedtype.NamedType('address', NetworkAddress()), + namedtype.NamedType('counter', Counter()), + namedtype.NamedType('gauge', Gauge()), + namedtype.NamedType('ticks', TimeTicks()), + namedtype.NamedType('arbitrary', Opaque()) + ) + +class ObjectSyntax(univ.Choice): + componentType = namedtype.NamedTypes( + namedtype.NamedType('simple', SimpleSyntax()), + namedtype.NamedType('application-wide', ApplicationSyntax()) + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/rfc1157.py python-pysnmp4-4.2.2/pysnmp/proto/rfc1157.py --- python-pysnmp4-4.1.9a/pysnmp/proto/rfc1157.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/rfc1157.py 2011-01-19 18:44:43.000000000 +0000 @@ -0,0 +1,64 @@ +from pyasn1.type import univ, tag, namedtype, namedval +from pysnmp.proto import rfc1155 + +class VarBind(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('name', rfc1155.ObjectName()), + namedtype.NamedType('value', rfc1155.ObjectSyntax()) + ) +class VarBindList(univ.SequenceOf): + componentType = VarBind() + +class _RequestBase(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('request-id', univ.Integer()), + namedtype.NamedType('error-status', univ.Integer(namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5)))), + namedtype.NamedType('error-index', univ.Integer()), + namedtype.NamedType('variable-bindings', VarBindList()) + ) + +class GetRequestPDU(_RequestBase): + tagSet = _RequestBase.tagSet.tagImplicitly( + tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0) + ) +class GetNextRequestPDU(_RequestBase): + tagSet = _RequestBase.tagSet.tagImplicitly( + tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1) + ) +class GetResponsePDU(_RequestBase): + tagSet = _RequestBase.tagSet.tagImplicitly( + tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2) + ) +class SetRequestPDU(_RequestBase): + tagSet = _RequestBase.tagSet.tagImplicitly( + tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3) + ) + +class TrapPDU(univ.Sequence): + tagSet = univ.Sequence.tagSet.tagImplicitly( + tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 4) + ) + componentType = namedtype.NamedTypes( + namedtype.NamedType('enterprise', univ.ObjectIdentifier()), + namedtype.NamedType('agent-addr', rfc1155.NetworkAddress()), + namedtype.NamedType('generic-trap', univ.Integer().clone(namedValues=namedval.NamedValues(('coldStart', 0), ('warmStart', 1), ('linkDown', 2), ('linkUp', 3), ('authenticationFailure', 4), ('egpNeighborLoss', 5), ('enterpriseSpecific', 6)))), + namedtype.NamedType('specific-trap', univ.Integer()), + namedtype.NamedType('time-stamp', rfc1155.TimeTicks()), + namedtype.NamedType('variable-bindings', VarBindList()) + ) + +class PDUs(univ.Choice): + componentType = namedtype.NamedTypes( + namedtype.NamedType('get-request', GetRequestPDU()), + namedtype.NamedType('get-next-request', GetNextRequestPDU()), + namedtype.NamedType('get-response', GetResponsePDU()), + namedtype.NamedType('set-request', SetRequestPDU()), + namedtype.NamedType('trap', TrapPDU()) + ) + +class Message(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType('version', univ.Integer(namedValues = namedval.NamedValues(('version-1', 0)))), + namedtype.NamedType('community', univ.OctetString()), + namedtype.NamedType('data', PDUs()) + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/rfc1902.py python-pysnmp4-4.2.2/pysnmp/proto/rfc1902.py --- python-pysnmp4-4.1.9a/pysnmp/proto/rfc1902.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/rfc1902.py 2011-11-07 07:51:49.000000000 +0000 @@ -0,0 +1,213 @@ +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( + -2147483648, 2147483647 + ) + +class Integer32(univ.Integer): + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + -2147483648, 2147483647 + ) + +class OctetString(univ.OctetString): + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueSizeConstraint( + 0, 65535 + ) + # rfc1902 uses a notion of "fixed length string" what might mean + # having zero-range size constraint applied. The following is + # supposed to be used for setting and querying this property. + + fixedLength = None + + def setFixedLength(self, value): + self.fixedLength = value + return self + + def isFixedLength(self): + return self.fixedLength is not None + + def getFixedLength(self): + return self.fixedLength + +class IpAddress(univ.OctetString): + tagSet = univ.OctetString.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) + ) + subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( + 4, 4 + ) + fixedLength = 4 + + 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, 4294967295 + ) + +class Gauge32(univ.Integer): + tagSet = univ.Integer.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) + ) + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + 0, 4294967295 + ) + +class Unsigned32(univ.Integer): + tagSet = univ.Integer.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) + ) + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + 0, 4294967295 + ) + +class TimeTicks(univ.Integer): + tagSet = univ.Integer.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) + ) + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + 0, 4294967295 + ) + +class Opaque(univ.OctetString): + tagSet = univ.OctetString.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) + ) + +class Counter64(univ.Integer): + tagSet = univ.Integer.tagSet.tagImplicitly( + tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x06) + ) + subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( + 0, 18446744073709551615 + ) + +class Bits(univ.OctetString): + namedValues = namedval.NamedValues() + def __init__(self, value=None, tagSet=None, subtypeSpec=None, + namedValues=None): + if namedValues is None: + self.__namedValues = self.namedValues + else: + self.__namedValues = namedValues + univ.OctetString.__init__( + self, value, tagSet, subtypeSpec + ) + + def prettyIn(self, bits): + 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) + if v is None: + raise error.ProtocolError( + 'Unknown named bit %s' % bit + ) + d, m = divmod(v, 8) + if d >= len(octets): + octets.extend([0] * (d - len(octets) + 1)) + octets[d] = octets[d] | 0x01 << (7-m) + return univ.OctetString.prettyIn(self, octets) + + def prettyOut(self, value): + names = [] + ints = self.__class__(value).asNumbers() + i = 0 + while i < len(ints): + v = ints[i] + j = 7 + while j >= 0: + if v & (0x01< noop + + # 4.3.3 + for pduType in pduTypes: + k = (contextEngineId, pduType) + if k in self.__appsRegistration: + raise error.ProtocolError( + 'Duplicate registration %s/%s' % (contextEngineId, pduType) + ) + + # 4.3.4 + self.__appsRegistration[k] = processPdu + + debug.logger & debug.flagDsp and debug.logger('registerContextEngineId: contextEngineId %r pduTypes %s' % (contextEngineId, pduTypes)) + # 4.4.1 + def unregisterContextEngineId(self, contextEngineId, pduTypes): + """Unregister application with dispatcher""" + # 4.3.4 + if contextEngineId is None: + # Default to local snmpEngineId + contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + + for pduType in pduTypes: + k = (contextEngineId, pduType) + if k in self.__appsRegistration: + del self.__appsRegistration[k] + + debug.logger & debug.flagDsp and debug.logger('unregisterContextEngineId: contextEngineId %r pduTypes %s' % (contextEngineId, pduTypes)) + + def getRegisteredApp(self, contextEngineId, pduType): + k = (contextEngineId, pduType) + if k in self.__appsRegistration: + return self.__appsRegistration[k] + k = ( null, pduType ) + if k in self.__appsRegistration: + return self.__appsRegistration[k] # wildcard + + # Dispatcher <-> application API + + # 4.1.1 + + def sendPdu( + self, + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + expectResponse, + timeout=0, # timeout expressed in dispatcher ticks + cbFun=None, + cbCtx=None + ): + """PDU dispatcher -- prepare and serialize a request or notification""" + # 4.1.1.2 + k = int(messageProcessingModel) + if k in snmpEngine.messageProcessingSubsystems: + mpHandler = snmpEngine.messageProcessingSubsystems[k] + else: + raise error.StatusInformation( + errorIndication=errind.unsupportedMsgProcessingModel + ) + + debug.logger & debug.flagDsp and debug.logger('sendPdu: securityName %s, PDU\n%s' % (securityName, PDU.prettyPrint())) + + # 4.1.1.3 + sendPduHandle = self.__sendPduHandle() + if expectResponse: + self.__cache.add( + sendPduHandle, + messageProcessingModel=messageProcessingModel, + sendPduHandle=sendPduHandle, + timeout=timeout+snmpEngine.transportDispatcher.getTimerTicks(), + cbFun=cbFun, + cbCtx=cbCtx + ) + debug.logger & debug.flagDsp and debug.logger('sendPdu: current time in ticks %d' % (snmpEngine.transportDispatcher.getTimerTicks(),)) + + debug.logger & debug.flagDsp and debug.logger('sendPdu: new sendPduHandle %s, timeout %s, cbFun %s' % (sendPduHandle, timeout, cbFun)) + + # 4.1.1.4 & 4.1.1.5 + try: + ( destTransportDomain, + destTransportAddress, + outgoingMessage ) = mpHandler.prepareOutgoingMessage( + snmpEngine, + transportDomain, + transportAddress, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + expectResponse, + sendPduHandle + ) + debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded') + except error.StatusInformation: +# XXX is it still needed here? +# self.releaseStateInformation(snmpEngine, sendPduHandle, messageProcessingModel) + raise + + # 4.1.1.6 + if snmpEngine.transportDispatcher is None: + raise error.PySnmpError('Transport dispatcher not set') + snmpEngine.transportDispatcher.sendMessage( + outgoingMessage, destTransportDomain, destTransportAddress + ) + + # Update cache with orignal req params (used for retrying) + if expectResponse: + self.__cache.update( + sendPduHandle, + transportDomain=transportDomain, + transportAddress=transportAddress, + securityModel=securityModel, + securityName=securityName, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + pduVersion=pduVersion, + PDU=PDU + ) + + return sendPduHandle + + # 4.1.2.1 + def returnResponsePdu( + self, + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ): + """PDU dispatcher -- prepare and serialize a response""" + # Extract input values and initialize defaults + k = int(messageProcessingModel) + if k in snmpEngine.messageProcessingSubsystems: + mpHandler = snmpEngine.messageProcessingSubsystems[k] + else: + raise error.StatusInformation( + errorIndication=errind.unsupportedMsgProcessingModel + ) + + debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: PDU %s' % (PDU and PDU.prettyPrint() or "",)) + + # 4.1.2.2 + try: + ( destTransportDomain, + destTransportAddress, + outgoingMessage ) = mpHandler.prepareResponseMessage( + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ) + debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded') + except error.StatusInformation: + # 4.1.2.3 + raise + + # Handle oversized messages XXX transport constrains? + snmpEngineMaxMessageSize, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') + if snmpEngineMaxMessageSize.syntax and \ + len(outgoingMessage) > snmpEngineMaxMessageSize.syntax: + snmpSilentDrops, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') + snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 + raise error.MessageTooBigError() + + # 4.1.2.4 + snmpEngine.transportDispatcher.sendMessage( + outgoingMessage, + destTransportDomain, + destTransportAddress + ) + + # 4.2.1 + def receiveMessage( + self, + snmpEngine, + transportDomain, + transportAddress, + wholeMsg + ): + """Message dispatcher -- de-serialize message into PDU""" + # 4.2.1.1 + snmpInPkts, = self.mibInstrumController.mibBuilder.importSymbols( + '__SNMPv2-MIB', 'snmpInPkts' + ) + snmpInPkts.syntax = snmpInPkts.syntax + 1 + + # 4.2.1.2 + try: + 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 null # n.b the whole buffer gets dropped + + debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion) + + messageProcessingModel = msgVersion + + k = int(messageProcessingModel) + if k in snmpEngine.messageProcessingSubsystems: + mpHandler = snmpEngine.messageProcessingSubsystems[k] + else: + snmpInBadVersions, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadVersions') + snmpInBadVersions.syntax = snmpInBadVersions.syntax + 1 + return restOfWholeMsg + + # 4.2.1.3 -- no-op + + # 4.2.1.4 + try: + ( messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + pduType, + sendPduHandle, + maxSizeResponseScopedPDU, + statusInformation, + stateReference ) = mpHandler.prepareDataElements( + snmpEngine, + transportDomain, + transportAddress, + wholeMsg + ) + debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded') + 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 + debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP failed, statusInformation %s' % statusInformation) + self.__expireRequest( + statusInformation['sendPduHandle'], + self.__cache.pop(statusInformation['sendPduHandle']), + snmpEngine, + statusInformation + ) + return restOfWholeMsg + + debug.logger & debug.flagDsp and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint()) + + # 4.2.2 + if sendPduHandle is None: + # 4.2.2.1 (request or notification) + + debug.logger & debug.flagDsp and debug.logger('receiveMessage: pduType %s' % pduType) + # 4.2.2.1.1 + processPdu = self.getRegisteredApp(contextEngineId, pduType) + + # 4.2.2.1.2 + if processPdu is None: + # 4.2.2.1.2.a + snmpUnknownPDUHandlers, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownPDUHandlers') + snmpUnknownPDUHandlers.syntax = snmpUnknownPDUHandlers.syntax+1 + + # 4.2.2.1.2.b + statusInformation = { + 'errorIndication': errind.unknownPDUHandler, + 'oid': snmpUnknownPDUHandlers.name, + 'val': snmpUnknownPDUHandlers.syntax + } + + debug.logger & debug.flagDsp and debug.logger('receiveMessage: unhandled PDU type') + + # XXX fails on unknown PDU + + try: + ( destTransportDomain, + destTransportAddress, + outgoingMessage ) = mpHandler.prepareResponseMessage( + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference, + statusInformation + ) + except error.StatusInformation: + debug.logger & debug.flagDsp and debug.logger('receiveMessage: report failed, statusInformation %s' % sys.exc_info()[1]) + return restOfWholeMsg + + # 4.2.2.1.2.c + try: + snmpEngine.transportDispatcher.sendMessage( + outgoingMessage, + destTransportDomain, + destTransportAddress + ) + except PySnmpError: # XXX + pass + + debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded') + + # 4.2.2.1.2.d + return restOfWholeMsg + else: + # Pass transport info to app + if stateReference is not None: + self.__transportInfo[stateReference] = ( + transportDomain, transportAddress + ) + # 4.2.2.1.3 + processPdu( + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + maxSizeResponseScopedPDU, + stateReference + ) + if stateReference is not None: + del self.__transportInfo[stateReference] + debug.logger & debug.flagDsp and debug.logger('receiveMessage: processPdu succeeded') + return restOfWholeMsg + else: + # 4.2.2.2 (response) + + # 4.2.2.2.1 + cachedParams = self.__cache.pop(sendPduHandle) + + # 4.2.2.2.2 + if cachedParams is None: + snmpUnknownPDUHandlers, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownPDUHandlers') + snmpUnknownPDUHandlers.syntax = snmpUnknownPDUHandlers.syntax+1 + return restOfWholeMsg + + debug.logger & debug.flagDsp and debug.logger('receiveMessage: cache read by sendPduHandle %s' % sendPduHandle) + + # 4.2.2.2.3 + # no-op ? XXX + + # 4.2.2.2.4 + processResponsePdu = cachedParams['cbFun'] + processResponsePdu( + snmpEngine, + messageProcessingModel, + securityModel, + securityName, + securityLevel, + contextEngineId, + contextName, + pduVersion, + PDU, + statusInformation, + cachedParams['sendPduHandle'], + cachedParams['cbCtx'] + ) + debug.logger & debug.flagDsp and debug.logger('receiveMessage: processResponsePdu succeeded') + return restOfWholeMsg + + def releaseStateInformation( + self, snmpEngine, sendPduHandle, messageProcessingModel + ): + k = int(messageProcessingModel) + if k in snmpEngine.messageProcessingSubsystems: + mpHandler = snmpEngine.messageProcessingSubsystems[k] + mpHandler.releaseStateInformation(sendPduHandle) + + # Cache expiration stuff + + def __expireRequest(self, cacheKey, cachedParams, snmpEngine, + statusInformation=None): + timeNow = snmpEngine.transportDispatcher.getTimerTicks() + timeoutAt = cachedParams['timeout'] + + if statusInformation is None and timeNow < timeoutAt: + return + + processResponsePdu = cachedParams['cbFun'] + + debug.logger & debug.flagDsp and debug.logger('__expireRequest: req cachedParams %s' % cachedParams) + + # Fail timed-out requests + if not statusInformation: + statusInformation = error.StatusInformation( + errorIndication=errind.requestTimedOut + ) + self.releaseStateInformation( + snmpEngine, + cachedParams['sendPduHandle'], + cachedParams['messageProcessingModel'] + ) + processResponsePdu( + snmpEngine, + None, + None, + None, + None, + None, + None, + None, + None, + statusInformation, + cachedParams['sendPduHandle'], + cachedParams['cbCtx'] + ) + return 1 + + def receiveTimerTick(self, snmpEngine, timeNow): + self.__cache.expire(self.__expireRequest, snmpEngine) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/base.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/base.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/base.py 2011-02-11 08:10:32.000000000 +0000 @@ -0,0 +1,61 @@ +from pysnmp.proto.secmod import cache +from pysnmp.proto import error + +class AbstractSecurityModel: + securityModelID = None + def __init__(self): + self._cache = cache.Cache() + + def processIncomingMsg( + self, + snmpEngine, + messageProcessingModel, + maxMessageSize, + securityParameters, + securityModel, + securityLevel, + wholeMsg, + msg, + ): + raise error.ProtocolError( + 'Security model %s not implemented' % self + ) + + def generateRequestMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + ): + raise error.ProtocolError( + 'Security model %s not implemented' % self + ) + + def generateResponseMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ): + raise error.ProtocolError( + 'Security model %s not implemented' % self + ) + + def releaseStateInformation(self, stateReference): + self._cache.pop(stateReference) + + def receiveTimerTick(self, snmpEngine, timeNow): + pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/cache.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/cache.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/cache.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/cache.py 2011-02-11 08:10:27.000000000 +0000 @@ -0,0 +1,23 @@ +from pysnmp import nextid +from pysnmp.proto import error + +class Cache: + __stateReference = nextid.Integer(0xffffff) + def __init__(self): + self.__cacheEntries = {} + + def push(self, **securityData): + stateReference = self.__stateReference() + self.__cacheEntries[stateReference] = securityData + return stateReference + + def pop(self, stateReference): + if stateReference in self.__cacheEntries: + securityData = self.__cacheEntries[stateReference] + else: + raise error.ProtocolError( + 'Cache miss for stateReference=%s at %s' % + (stateReference, self) + ) + del self.__cacheEntries[stateReference] + return securityData diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/eso/priv/aes192.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/eso/priv/aes192.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/eso/priv/aes192.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/eso/priv/aes192.py 2011-01-16 23:59:10.000000000 +0000 @@ -0,0 +1,27 @@ +# AES 192/256 bit encryption (Internet draft) +# http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 +from pysnmp.proto.secmod.rfc3826.priv import aes +from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha +from pysnmp.proto.secmod.rfc3414 import localkey + +class Aes192(aes.Aes): + serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol + keySize = 24 + + # 3.1.2.1 + def localizeKey(self, authProtocol, privKey, snmpEngineID): + if authProtocol == hmacmd5.HmacMd5.serviceID: + localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) + localPrivKey = localPrivKey + localkey.localizeKeyMD5( + localPrivKey, snmpEngineID + ) + elif authProtocol == hmacsha.HmacSha.serviceID: + localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) + localPrivKey = localPrivKey + localkey.localizeKeySHA( + localPrivKey, snmpEngineID + ) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + return localPrivKey[:24] diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/eso/priv/aes256.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/eso/priv/aes256.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/eso/priv/aes256.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/eso/priv/aes256.py 2011-01-16 23:59:10.000000000 +0000 @@ -0,0 +1,27 @@ +# AES 192/256 bit encryption (Internet draft) +# http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 +from pysnmp.proto.secmod.rfc3826.priv import aes +from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha +from pysnmp.proto.secmod.rfc3414 import localkey + +class Aes256(aes.Aes): + serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol + keySize = 32 + + # 3.1.2.1 + def localizeKey(self, authProtocol, privKey, snmpEngineID): + if authProtocol == hmacmd5.HmacMd5.serviceID: + localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) + localPrivKey = localPrivKey + localkey.localizeKeyMD5( + localPrivKey, snmpEngineID + ) + elif authProtocol == hmacsha.HmacSha.serviceID: + localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) + localPrivKey = localPrivKey + localkey.localizeKeySHA( + localPrivKey, snmpEngineID + ) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + return localPrivKey[:32] diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/eso/priv/des3.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/eso/priv/des3.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/eso/priv/des3.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/eso/priv/des3.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,143 @@ +# Reeder 3DES-EDE for USM (Internet draft) +# http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt +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 +from pyasn1.compat.octets import null + +try: + from Crypto.Cipher import DES3 +except ImportError: + DES3 = None + +random.seed() + +# 5.1.1 + +class Des3(base.AbstractEncryptionService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol + _localInt = random.randrange(0, 0xffffffff) + + def hashPassphrase(self, authProtocol, privKey): + if authProtocol == hmacmd5.HmacMd5.serviceID: + return localkey.hashPassphraseMD5(privKey) + elif authProtocol == hmacsha.HmacSha.serviceID: + return localkey.hashPassphraseSHA(privKey) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + + def localizeKey(self, authProtocol, privKey, snmpEngineID): + if authProtocol == hmacmd5.HmacMd5.serviceID: + localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) + localPrivKey = localPrivKey + localkey.localizeKeyMD5( + localPrivKey, snmpEngineID + ) + elif authProtocol == hmacsha.HmacSha.serviceID: + localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) + localPrivKey = localPrivKey + localkey.localizeKeySHA( + localPrivKey, snmpEngineID + ) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + return localPrivKey[:32] # key+IV + + # 5.1.1.1 + def __getEncryptionKey(self, privKey, snmpEngineBoots): + # 5.1.1.1.1 + des3Key = privKey[:24] + preIV = privKey[24:32] + + securityEngineBoots = int(snmpEngineBoots) + + salt = [ + securityEngineBoots>>24&0xff, + securityEngineBoots>>16&0xff, + securityEngineBoots>>8&0xff, + securityEngineBoots&0xff, + self._localInt>>24&0xff, + self._localInt>>16&0xff, + self._localInt>>8&0xff, + self._localInt&0xff + ] + if self._localInt == 0xffffffff: + self._localInt = 0 + else: + self._localInt = self._localInt + 1 + + # salt not yet hashed XXX + + return des3Key.asOctets(), \ + univ.OctetString(salt).asOctets(), \ + univ.OctetString(map(lambda x,y:x^y, salt, preIV.asNumbers())).asOctets() + + def __getDecryptionKey(self, privKey, salt): + 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): + if DES3 is None: + raise error.StatusInformation( + errorIndication=errind.encryptionError + ) + + snmpEngineBoots, snmpEngineTime, salt = privParameters + + des3Key, salt, iv = self.__getEncryptionKey( + encryptKey, snmpEngineBoots + ) + + des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) + + privParameters = univ.OctetString(salt) + + plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets() + cipherblock = iv + ciphertext = null + while plaintext: + cipherblock = des3Obj.encrypt( + univ.OctetString(map(lambda x,y:x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(plaintext[:8]).asNumbers())) + ) + ciphertext = ciphertext + cipherblock + plaintext = plaintext[8:] + + return univ.OctetString(ciphertext), privParameters + + # 5.1.1.3 + def decryptData(self, decryptKey, privParameters, encryptedData): + if DES3 is None: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + snmpEngineBoots, snmpEngineTime, salt = privParameters + + if len(salt) != 8: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + des3Key, iv = self.__getDecryptionKey(decryptKey, salt) + + if len(encryptedData) % 8 != 0: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) + + plaintext = null + ciphertext = encryptedData.asOctets() + cipherblock = iv + while ciphertext: + plaintext = plaintext + univ.OctetString(map(lambda x,y: x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(des3Obj.decrypt(ciphertext[:8])).asNumbers())).asOctets() + cipherblock = ciphertext[:8] + ciphertext = ciphertext[8:] + + return plaintext diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc2576.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc2576.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc2576.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc2576.py 2012-04-13 19:04:59.000000000 +0000 @@ -0,0 +1,265 @@ +# SNMP v1 & v2c security models implementation +from pyasn1.codec.ber import encoder +from pysnmp.proto.secmod import base +from pysnmp.carrier.asynsock.dgram import udp, udp6 +from pysnmp.smi.error import NoSuchInstanceError +from pysnmp.proto import errind, error +from pysnmp import debug + +class SnmpV1SecurityModel(base.AbstractSecurityModel): + securityModelID = 1 + # According to rfc2576, community name <-> contextEngineId/contextName + # mapping is up to MP module for notifications but belongs to secmod + # responsibility for other PDU types. Since I do not yet understand + # the reason for this de-coupling, I've moved this code from MP-scope + # in here. + + def generateRequestMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineId, + securityName, + securityLevel, + scopedPDU + ): + msg, = globalData + contextEngineId, contextName, pdu = scopedPDU + + # rfc2576: 5.2.3 + ( snmpCommunityName, + snmpCommunitySecurityName, + snmpCommunityContextEngineId, + snmpCommunityContextName, + snmpCommunityTransportTag ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-COMMUNITY-MIB', + 'snmpCommunityName', + 'snmpCommunitySecurityName', + 'snmpCommunityContextEngineID', + 'snmpCommunityContextName', + 'snmpCommunityTransportTag' + ) + nextMibNode = snmpCommunitySecurityName + while 1: + try: + nextMibNode = snmpCommunitySecurityName.getNextNodeWithValue( + nextMibNode.name, securityName + ) + except NoSuchInstanceError: + break + + instId = nextMibNode.name[len(snmpCommunitySecurityName.name):] + mibNode = snmpCommunityContextEngineId.getNode( + snmpCommunityContextEngineId.name + instId + ) + if mibNode.syntax != contextEngineId: + continue + mibNode = snmpCommunityContextName.getNode( + snmpCommunityContextName.name + instId + ) + if mibNode.syntax != contextName: + continue + mibNode = snmpCommunityName.getNode( + snmpCommunityName.name + instId + ) + securityParameters = mibNode.syntax + + # XXX snmpCommunityTransportTag matching should probably be here + + debug.logger & debug.flagSM and debug.logger('generateRequestMsg: using community %r for securityName %r, contextEngineId %r contextName %r' % (securityParameters, securityName, contextEngineId, contextName)) + + msg.setComponentByPosition(1, securityParameters) + msg.setComponentByPosition(2) + msg.getComponentByPosition(2).setComponentByType( + pdu.tagSet, pdu, verifyConstraints=False + ) + + debug.logger & debug.flagMP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),)) + + wholeMsg = encoder.encode(msg) + return ( securityParameters, wholeMsg ) + + raise error.StatusInformation( + errorIndication = errind.unknownCommunityName + ) + + def generateResponseMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ): + # rfc2576: 5.2.2 + msg, = globalData + contextEngineId, contextName, pdu = scopedPDU + cachedSecurityData = self._cache.pop(securityStateReference) + communityName = cachedSecurityData['communityName'] + + debug.logger & debug.flagSM and debug.logger('generateResponseMsg: recovered community %r by securityStateReference %s' % (communityName, securityStateReference)) + + msg.setComponentByPosition(1, communityName) + msg.setComponentByPosition(2) + msg.getComponentByPosition(2).setComponentByType( + pdu.tagSet, pdu, verifyConstraints=False + ) + + debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),)) + + wholeMsg = encoder.encode(msg) + return ( communityName, wholeMsg ) + + def processIncomingMsg( + self, + snmpEngine, + messageProcessingModel, + maxMessageSize, + securityParameters, + securityModel, + securityLevel, + wholeMsg, + msg + ): + # rfc2576: 5.2.1 + ( communityName, srcTransport, destTransport ) = securityParameters + ( snmpCommunityName, + snmpCommunitySecurityName, + snmpCommunityContextEngineId, + snmpCommunityContextName, + snmpCommunityTransportTag ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( + 'SNMP-COMMUNITY-MIB', + 'snmpCommunityName', + 'snmpCommunitySecurityName', + 'snmpCommunityContextEngineID', + 'snmpCommunityContextName', + 'snmpCommunityTransportTag' + ) + nextMibNode = snmpCommunityName + addrToTagMap = {} # cache to save on inner loop + while 1: + try: + nextMibNode = snmpCommunityName.getNextNodeWithValue( + nextMibNode.name, communityName + ) + except NoSuchInstanceError: + snmpInBadCommunityNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadCommunityNames') + snmpInBadCommunityNames.syntax = snmpInBadCommunityNames.syntax+1 + raise error.StatusInformation( + errorIndication = errind.unknownCommunityName + ) + + instId = nextMibNode.name[len(snmpCommunityName.name):] + + # snmpCommunityTransportTag matching + mibNode = snmpCommunityTransportTag.getNode( + snmpCommunityTransportTag.name + instId + ) + if mibNode.syntax: + if not addrToTagMap: + # Build a cache of addr->tag map + ( snmpTargetAddrTDomain, + snmpTargetAddrTAddress, + snmpTargetAddrTagList ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', 'snmpTargetAddrTAddress', 'snmpTargetAddrTagList') + __nextMibNode = snmpTargetAddrTagList + while 1: + try: + __nextMibNode = snmpTargetAddrTagList.getNextNode( + __nextMibNode.name + ) + except NoSuchInstanceError: + break + __instId = __nextMibNode.name[ + len(snmpTargetAddrTagList.name): + ] + targetAddrTDomain = snmpTargetAddrTDomain.getNode( + snmpTargetAddrTDomain.name + __instId + ).syntax + targetAddrTAddress = snmpTargetAddrTAddress.getNode( + snmpTargetAddrTAddress.name + __instId + ).syntax + + targetAddrTDomain = tuple(targetAddrTDomain) + + if targetAddrTDomain[:len(udp.snmpUDPDomain)] == udp.snmpUDPDomain: + SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') + targetAddrTAddress = tuple( + SnmpUDPAddress(targetAddrTAddress) + ) + elif targetAddrTDomain[:len(udp6.snmpUDP6Domain)] == udp6.snmpUDP6Domain: + TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') + targetAddrTAddress = tuple( + TransportAddressIPv6(targetAddrTAddress) + ) + targetAddr = targetAddrTDomain, targetAddrTAddress + targetAddrTagList = snmpTargetAddrTagList.getNode( + snmpTargetAddrTagList.name + __instId + ).syntax + if targetAddr not in addrToTagMap: + addrToTagMap[targetAddr] = {} + for tag in targetAddrTagList.asOctets().split(): + addrToTagMap[targetAddr][tag] = 1 + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: address-to-tag map %s' % addrToTagMap) + + # XXX snmpTargetAddrTMask matching not implemented + + if srcTransport in addrToTagMap: + 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 + else: + continue + break + + communityName = snmpCommunityName.getNode( + snmpCommunityName.name + instId + ) + securityName = snmpCommunitySecurityName.getNode( + snmpCommunitySecurityName.name + instId + ) + contextEngineId = snmpCommunityContextEngineId.getNode( + snmpCommunityContextEngineId.name + instId + ) + contextName = snmpCommunityContextName.getNode( + snmpCommunityContextName.name + instId + ) + snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: looked up securityName %r contextEngineId %r contextName %r by communityName %r' % (securityName.syntax, contextEngineId.syntax, contextName.syntax, communityName.syntax)) + + stateReference = self._cache.push( + communityName=communityName.syntax + ) + + securityEngineID = snmpEngineID.syntax + securityName = securityName.syntax + scopedPDU = ( + contextEngineId.syntax, contextName.syntax, + msg.getComponentByPosition(2).getComponent() + ) + maxSizeResponseScopedPDU = maxMessageSize - 128 + securityStateReference = stateReference + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: generated maxSizeResponseScopedPDU %s securityStateReference %s' % (maxSizeResponseScopedPDU, securityStateReference)) + + return ( securityEngineID, + securityName, + scopedPDU, + maxSizeResponseScopedPDU, + securityStateReference ) + +class SnmpV2cSecurityModel(SnmpV1SecurityModel): + securityModelID = 2 + +# XXX +# contextEngineId/contextName goes to globalData diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/base.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/base.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/base.py 2011-01-17 00:14:55.000000000 +0000 @@ -0,0 +1,18 @@ +from pysnmp.proto import errind, error + +class AbstractAuthenticationService: + serviceID = None + + def hashPassphrase(self, authKey): + raise error.ProtocolError(errind.noAuthentication) + + def localizeKey(self, authKey, snmpEngineID): + raise error.ProtocolError(errind.noAuthentication) + + # 7.2.4.1 + def authenticateOutgoingMsg(self, authKey, wholeMsg): + raise error.ProtocolError(errind.noAuthentication) + + # 7.2.4.2 + def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + raise error.ProtocolError(errind.noAuthentication) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,116 @@ +try: + from hashlib import md5 +except ImportError: + import md5 + md5 = md5.new +from pyasn1.type import univ +from pysnmp.proto.secmod.rfc3414.auth import base +from pysnmp.proto.secmod.rfc3414 import localkey +from pysnmp.proto import errind, error + +_twelveZeros = univ.OctetString((0,)*12).asOctets() +_fortyEightZeros = (0,)*48 + +# rfc3414: 6.2.4 + +class HmacMd5(base.AbstractAuthenticationService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol + __ipad = [0x36]*64 + __opad = [0x5C]*64 + + def hashPassphrase(self, authKey): + return localkey.hashPassphraseMD5(authKey) + + def localizeKey(self, authKey, snmpEngineID): + return localkey.localizeKeyMD5(authKey, snmpEngineID) + + # 6.3.1 + def authenticateOutgoingMsg(self, authKey, wholeMsg): + # Here we expect calling secmod to indicate where the digest + # should be in the substrate. Also, it pre-sets digest placeholder + # so we hash wholeMsg out of the box. + # Yes, that's ugly but that's rfc... + l = wholeMsg.find(_twelveZeros) + if l == -1: + raise error.ProtocolError('Cant locate digest placeholder') + wholeHead = wholeMsg[:l] + wholeTail = wholeMsg[l+12:] + + # 6.3.1.1 + + # 6.3.1.2a + extendedAuthKey = authKey.asNumbers() + _fortyEightZeros + + # 6.3.1.2b --> noop + + # 6.3.1.2c + k1 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__ipad) + ) + + # 6.3.1.2d --> noop + + # 6.3.1.2e + k2 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__opad) + ) + + # 6.3.1.3 + d1 = md5(k1.asOctets()+wholeMsg).digest() + + # 6.3.1.4 + d2 = md5(k2.asOctets()+d1).digest() + mac = d2[:12] + + # 6.3.1.5 & 6 + return wholeHead + mac + wholeTail + + # 6.3.2 + def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + # 6.3.2.1 & 2 + if len(authParameters) != 12: + raise error.StatusInformation( + errorIndication=errind.authenticationError + ) + + # 6.3.2.3 + l = wholeMsg.find(authParameters.asOctets()) + if l == -1: + raise error.ProtocolError('Cant locate digest in wholeMsg') + wholeHead = wholeMsg[:l] + wholeTail = wholeMsg[l+12:] + authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail + + # 6.3.2.4a + extendedAuthKey = authKey.asNumbers() + _fortyEightZeros + + # 6.3.2.4b --> noop + + # 6.3.2.4c + k1 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__ipad) + ) + + # 6.3.2.4d --> noop + + # 6.3.2.4e + k2 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__opad) + ) + + # 6.3.2.5a + d1 = md5(k1.asOctets()+authenticatedWholeMsg).digest() + + # 6.3.2.5b + d2 = md5(k2.asOctets()+d1).digest() + + # 6.3.2.5c + mac = d2[:12] + + # 6.3.2.6 + if mac != authParameters: + raise error.StatusInformation( + errorIndication=errind.authenticationFailure + ) + + return authenticatedWholeMsg diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,115 @@ +try: + from hashlib import sha1 +except ImportError: + import sha + sha1 = sha.new +from pyasn1.type import univ +from pysnmp.proto.secmod.rfc3414.auth import base +from pysnmp.proto.secmod.rfc3414 import localkey +from pysnmp.proto import errind, error + +_twelveZeros = univ.OctetString((0,)*12).asOctets() +_fortyFourZeros = (0,)*44 + +# 7.2.4 + +class HmacSha(base.AbstractAuthenticationService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol + __ipad = [0x36]*64 + __opad = [0x5C]*64 + + def hashPassphrase(self, authKey): + return localkey.hashPassphraseSHA(authKey) + + def localizeKey(self, authKey, snmpEngineID): + return localkey.localizeKeySHA(authKey, snmpEngineID) + + # 7.3.1 + def authenticateOutgoingMsg(self, authKey, wholeMsg): + # 7.3.1.1 + # Here we expect calling secmod to indicate where the digest + # should be in the substrate. Also, it pre-sets digest placeholder + # so we hash wholeMsg out of the box. + # Yes, that's ugly but that's rfc... + l = wholeMsg.find(_twelveZeros) + if l == -1: + raise error.ProtocolError('Cant locate digest placeholder') + wholeHead = wholeMsg[:l] + wholeTail = wholeMsg[l+12:] + + # 7.3.1.2a + extendedAuthKey = authKey.asNumbers() + _fortyFourZeros + + # 7.3.1.2b -- noop + + # 7.3.1.2c + k1 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__ipad) + ) + + # 7.3.1.2d -- noop + + # 7.3.1.2e + k2 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__opad) + ) + + # 7.3.1.3 + d1 = sha1(k1.asOctets()+wholeMsg).digest() + + # 7.3.1.4 + d2 = sha1(k2.asOctets()+d1).digest() + mac = d2[:12] + + # 7.3.1.5 & 6 + return wholeHead + mac + wholeTail + + # 7.3.2 + def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + # 7.3.2.1 & 2 + if len(authParameters) != 12: + raise error.StatusInformation( + errorIndication=errind.authenticationError + ) + + # 7.3.2.3 + l = wholeMsg.find(authParameters.asOctets()) + if l == -1: + raise error.ProtocolError('Cant locate digest in wholeMsg') + wholeHead = wholeMsg[:l] + wholeTail = wholeMsg[l+12:] + authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail + + # 7.3.2.4a + extendedAuthKey = authKey.asNumbers() + _fortyFourZeros + + # 7.3.2.4b --> noop + + # 7.3.2.4c + k1 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__ipad) + ) + + # 7.3.2.4d --> noop + + # 7.3.2.4e + k2 = univ.OctetString( + map(lambda x,y: x^y, extendedAuthKey, self.__opad) + ) + + # 7.3.2.5a + d1 = sha1(k1.asOctets()+authenticatedWholeMsg).digest() + + # 7.3.2.5b + d2 = sha1(k2.asOctets()+d1).digest() + + # 7.3.2.5c + mac = d2[:12] + + # 7.3.2.6 + if mac != authParameters: + raise error.StatusInformation( + errorIndication=errind.authenticationFailure + ) + + return authenticatedWholeMsg diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/noauth.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/noauth.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/auth/noauth.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/auth/noauth.py 2011-01-17 00:14:55.000000000 +0000 @@ -0,0 +1,18 @@ +from pysnmp.proto.secmod.rfc3414.auth import base +from pysnmp.proto import errind, error + +class NoAuth(base.AbstractAuthenticationService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol + + def hashPassphrase(self, authKey): + return + + def localizeKey(self, authKey, snmpEngineID): + return + + # 7.2.4.2 + def authenticateOutgoingMsg(self, authKey, wholeMsg): + raise error.StatusInformation(errorIndication=errind.noAuthentication) + + def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): + raise error.StatusInformation(errorIndication=errind.noAuthentication) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/__init__.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/__init__.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/__init__.py 2005-06-14 10:49:57.000000000 +0000 @@ -0,0 +1,3 @@ +from pysnmp.proto.secmod.rfc3414 import service + +SnmpUSMSecurityModel = service.SnmpUSMSecurityModel diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/localkey.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/localkey.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/localkey.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/localkey.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,64 @@ +# Convert plaintext passphrase into a localized key +try: + from hashlib import md5, sha1 +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) + ringBufferLen = len(ringBuffer) + count = 0 + mark = 0 + while count < 16384: + e = mark + 64 + if e < ringBufferLen: + md.update(ringBuffer[mark:e]) + mark = e + else: + md.update( + ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] + ) + mark = e-ringBufferLen + count = count + 1 + return md.digest() + +def localizeKeyMD5(passKey, snmpEngineId): + 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) + ringBufferLen = len(ringBuffer) + count = 0 + mark = 0 + while count < 16384: + e = mark + 64 + if e < ringBufferLen: + md.update(ringBuffer[mark:e]) + mark = e + else: + md.update( + ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] + ) + mark = e-ringBufferLen + count = count + 1 + return md.digest() + +def localizeKeySHA(passKey, snmpEngineId): + passKey = univ.OctetString(passKey).asOctets() + return sha1(passKey + snmpEngineId.asOctets()+ passKey).digest() + +def passwordToKeySHA(passphrase, snmpEngineId): + return localizeKeySHA(hashPassphraseSHA(passphrase), snmpEngineId) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/priv/base.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/priv/base.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/priv/base.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/priv/base.py 2011-01-17 00:14:55.000000000 +0000 @@ -0,0 +1,17 @@ +from pysnmp.proto import error + +class AbstractEncryptionService: + serviceID = None + + def hashPassphrase(self, authProtocol, privKey): + raise error.ProtocolError('no encryption') + + def localizeKey(self, authProtocol, privKey, snmpEngineID): + raise error.ProtocolError('no encryption') + + def encryptData(self, encryptKey, privParameters, dataToEncrypt): + raise error.ProtocolError('no encryption') + + def decryptData(self, decryptKey, privParameters, encryptedData): + raise error.ProtocolError('no encryption') + diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/priv/des.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/priv/des.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/priv/des.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/priv/des.py 2012-04-17 05:59:23.000000000 +0000 @@ -0,0 +1,135 @@ +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 + +try: + from Crypto.Cipher import DES +except ImportError: + DES = None + +random.seed() + +# 8.2.4 + +class Des(base.AbstractEncryptionService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol + if version_info < (2, 3): + _localInt = int(random.random()*0xffffffff) + else: + _localInt = random.randrange(0, 0xffffffff) + + def hashPassphrase(self, authProtocol, privKey): + if authProtocol == hmacmd5.HmacMd5.serviceID: + return localkey.hashPassphraseMD5(privKey) + elif authProtocol == hmacsha.HmacSha.serviceID: + return localkey.hashPassphraseSHA(privKey) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + + def localizeKey(self, authProtocol, privKey, snmpEngineID): + if authProtocol == hmacmd5.HmacMd5.serviceID: + localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) + elif authProtocol == hmacsha.HmacSha.serviceID: + localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + return localPrivKey[:32] # key+IV + + # 8.1.1.1 + def __getEncryptionKey(self, privKey, snmpEngineBoots): + desKey = privKey[:8] + preIV = privKey[8:16] + + securityEngineBoots = int(snmpEngineBoots) + + salt = [ + securityEngineBoots>>24&0xff, + securityEngineBoots>>16&0xff, + securityEngineBoots>>8&0xff, + securityEngineBoots&0xff, + self._localInt>>24&0xff, + self._localInt>>16&0xff, + self._localInt>>8&0xff, + self._localInt&0xff + ] + if self._localInt == 0xffffffff: + self._localInt = 0 + else: + self._localInt = self._localInt + 1 + + return desKey.asOctets(), \ + univ.OctetString(salt).asOctets(), \ + univ.OctetString(map(lambda x,y:x^y,salt,preIV.asNumbers())).asOctets() + + def __getDecryptionKey(self, privKey, salt): + return privKey[:8].asOctets(), univ.OctetString( + map(lambda x,y:x^y, salt.asNumbers(), privKey[8:16].asNumbers()) + ).asOctets() + + # 8.2.4.1 + def encryptData(self, encryptKey, privParameters, dataToEncrypt): + if DES is None: + raise error.StatusInformation( + errorIndication=errind.encryptionError + ) + + snmpEngineBoots, snmpEngineTime, salt = privParameters + + # 8.3.1.1 + desKey, salt, iv = self.__getEncryptionKey( + encryptKey, snmpEngineBoots + ) + + # 8.3.1.2 + privParameters = univ.OctetString(salt) + + # 8.1.1.2 + desObj = DES.new(desKey, DES.MODE_CBC, iv) + plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets() + ciphertext = desObj.encrypt(plaintext) + + # 8.3.1.3 & 4 + return univ.OctetString(ciphertext), privParameters + + # 8.2.4.2 + def decryptData(self, decryptKey, privParameters, encryptedData): + if DES is None: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + snmpEngineBoots, snmpEngineTime, salt = privParameters + + # 8.3.2.1 + if len(salt) != 8: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + # 8.3.2.2 noop + + # 8.3.2.3 + desKey, iv = self.__getDecryptionKey(decryptKey, salt) + + # 8.3.2.4 -> 8.1.1.3 + if len(encryptedData) % 8 != 0: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + desObj = DES.new(desKey, DES.MODE_CBC, iv) + + # 8.3.2.6 + return desObj.decrypt(encryptedData.asOctets()) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/priv/nopriv.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/priv/nopriv.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/priv/nopriv.py 2011-01-17 00:14:55.000000000 +0000 @@ -0,0 +1,16 @@ +from pysnmp.proto.secmod.rfc3414.priv import base +from pysnmp.proto import errind, error + +class NoPriv(base.AbstractEncryptionService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol + def hashPassphrase(self, authProtocol, privKey): + return + + def localizeKey(self, authProtocol, privKey, snmpEngineID): + return + + def encryptData(self, encryptKey, privParameters, dataToEncrypt): + raise error.StatusInformation(errorIndication=errind.noEncryption) + + def decryptData(self, decryptKey, privParameters, encryptedData): + raise error.StatusInformation(errorIndication=errind.noEncryption) diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/service.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/service.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3414/service.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3414/service.py 2012-04-20 19:27:35.000000000 +0000 @@ -0,0 +1,868 @@ +# 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 +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 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, 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()) + ) + +class SnmpUSMSecurityModel(AbstractSecurityModel): + securityModelID = 3 + authServices = { + hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), + hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), + noauth.NoAuth.serviceID: noauth.NoAuth() + } + privServices = { + des.Des.serviceID: des.Des(), + des3.Des3.serviceID: des3.Des3(), + aes.Aes.serviceID: aes.Aes(), + aes192.Aes192.serviceID: aes192.Aes192(), + aes256.Aes256.serviceID: aes256.Aes256(), + nopriv.NoPriv.serviceID: nopriv.NoPriv() + } + def __init__(self): + AbstractSecurityModel.__init__(self) + self.__securityParametersSpec = UsmSecurityParameters() + self.__timeline = {} + self.__timelineExpQueue = {} + self.__expirationTimer = 0 + + def __getUserInfo( + self, mibInstrumController, securityEngineID, securityName + ): + usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' + ) + tblIdx = usmUserEntry.getInstIdFromIndices( + securityEngineID, securityName + ) + # Get protocols + usmUserSecurityName = usmUserEntry.getNode( + usmUserEntry.name + (3,) + tblIdx + ).syntax + usmUserAuthProtocol = usmUserEntry.getNode( + usmUserEntry.name + (5,) + tblIdx + ).syntax + usmUserPrivProtocol = usmUserEntry.getNode( + usmUserEntry.name + (8,) + tblIdx + ).syntax + # Get keys + pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( + 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' + ) + pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( + pysnmpUsmKeyEntry.name + (1,) + tblIdx + ).syntax + pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( + pysnmpUsmKeyEntry.name + (2,) + tblIdx + ).syntax + return ( + usmUserSecurityName, # XXX function needed? + usmUserAuthProtocol, + pysnmpUsmKeyAuthLocalized, + usmUserPrivProtocol, + pysnmpUsmKeyPrivLocalized + ) + + def __cloneUserInfo( + self, mibInstrumController, securityEngineID, securityName + ): + snmpEngineID, = mibInstrumController.mibBuilder.importSymbols( + '__SNMP-FRAMEWORK-MIB', 'snmpEngineID' + ) + # Proto entry + usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( + 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' + ) + tblIdx = usmUserEntry.getInstIdFromIndices( + snmpEngineID.syntax, securityName + ) + # Get proto protocols + usmUserSecurityName = usmUserEntry.getNode( + usmUserEntry.name + (3,) + tblIdx + ) + usmUserAuthProtocol = usmUserEntry.getNode( + usmUserEntry.name + (5,) + tblIdx + ) + usmUserPrivProtocol = usmUserEntry.getNode( + usmUserEntry.name + (8,) + tblIdx + ) + # Get proto keys + pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( + 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' + ) + pysnmpUsmKeyAuth = pysnmpUsmKeyEntry.getNode( + pysnmpUsmKeyEntry.name + (3,) + tblIdx + ) + pysnmpUsmKeyPriv = pysnmpUsmKeyEntry.getNode( + pysnmpUsmKeyEntry.name + (4,) + tblIdx + ) + + # Create new row from proto values + + tblIdx = usmUserEntry.getInstIdFromIndices( + securityEngineID, securityName + ) + # New row + mibInstrumController.writeVars( + ((usmUserEntry.name + (13,) + tblIdx, 4),) + ) + # Set protocols + usmUserEntry.getNode( + usmUserEntry.name + (3,) + tblIdx + ).syntax = usmUserSecurityName.syntax + usmUserEntry.getNode( + usmUserEntry.name + (5,) + tblIdx + ).syntax = usmUserAuthProtocol.syntax + usmUserEntry.getNode( + usmUserEntry.name + (8,) + tblIdx + ).syntax = usmUserPrivProtocol.syntax + + # Localize and set keys + pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( + 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' + ) + pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( + pysnmpUsmKeyEntry.name + (1,) + tblIdx + ) + if usmUserAuthProtocol.syntax in self.authServices: + localizeKey = self.authServices[usmUserAuthProtocol.syntax].localizeKey + localAuthKey = localizeKey( + pysnmpUsmKeyAuth.syntax, + securityEngineID + ) + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedAuthProtocol + ) + if localAuthKey is not None: + pysnmpUsmKeyAuthLocalized.syntax = pysnmpUsmKeyAuthLocalized.syntax.clone(localAuthKey) + pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( + pysnmpUsmKeyEntry.name + (2,) + tblIdx + ) + if usmUserPrivProtocol.syntax in self.privServices: + localizeKey = self.privServices[usmUserPrivProtocol.syntax].localizeKey + localPrivKey = localizeKey( + usmUserAuthProtocol.syntax, + pysnmpUsmKeyPriv.syntax, + securityEngineID + ) + else: + raise error.StatusInformation( + errorIndication = errind.unsupportedPrivProtocol + ) + if localPrivKey is not None: + pysnmpUsmKeyPrivLocalized.syntax = pysnmpUsmKeyPrivLocalized.syntax.clone(localPrivKey) + return ( + usmUserSecurityName.syntax, # XXX function needed? + usmUserAuthProtocol.syntax, + pysnmpUsmKeyAuthLocalized.syntax, + usmUserPrivProtocol.syntax, + pysnmpUsmKeyPrivLocalized.syntax + ) + + def __generateRequestOrResponseMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ): + snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax + # 3.1.1 + if securityStateReference is not None: + # 3.1.1a + cachedSecurityData = self._cache.pop(securityStateReference) + usmUserName = cachedSecurityData['msgUserName'] + if 'usmUserAuthProtocol' in cachedSecurityData: + usmUserAuthProtocol = cachedSecurityData['usmUserAuthProtocol'] + else: + usmUserAuthProtocol = None + if 'usmUserAuthKeyLocalized' in cachedSecurityData: + usmUserAuthKeyLocalized = cachedSecurityData['usmUserAuthKeyLocalized'] + else: + usmUserAuthKeyLocalized = None + if 'usmUserPrivProtocol' in cachedSecurityData: + usmUserPrivProtocol = cachedSecurityData['usmUserPrivProtocol'] + else: + usmUserPrivProtocol = None + if 'usmUserPrivKeyLocalized' in cachedSecurityData: + usmUserPrivKeyLocalized = cachedSecurityData['usmUserPrivKeyLocalized'] + else: + usmUserPrivKeyLocalized = None + securityEngineID = snmpEngineID + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: user info read from cache') + elif securityName: + # 3.1.1b + try: + ( usmUserName, + usmUserAuthProtocol, + usmUserAuthKeyLocalized, + usmUserPrivProtocol, + usmUserPrivKeyLocalized ) = self.__getUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + securityEngineID, securityName + ) + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read user info') + except NoSuchInstanceError: + pysnmpUsmDiscovery, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery') + __reportUnknownName = not pysnmpUsmDiscovery.syntax + if not __reportUnknownName: + try: + ( usmUserName, + usmUserAuthProtocol, + usmUserAuthKeyLocalized, + usmUserPrivProtocol, + usmUserPrivKeyLocalized ) = self.__cloneUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + securityEngineID, + securityName + ) + except NoSuchInstanceError: + __reportUnknownName = 1 + + if __reportUnknownName: + raise error.StatusInformation( + errorIndication = errind.unknownSecurityName + ) + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info') + else: + # empty username used for engineID discovery + usmUserName = usmUserSecurityName = null + usmUserAuthProtocol = usmUserAuthKeyLocalized = None + usmUserPrivProtocol = usmUserPrivKeyLocalized = None + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use empty USM data') + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: local user usmUserName %r usmUserAuthProtocol %s usmUserPrivProtocol %s securityEngineID %r securityName %r' % (usmUserName, usmUserAuthProtocol, usmUserPrivProtocol, securityEngineID, securityName)) + + msg = globalData + + # 3.1.2 + if securityLevel == 3: + if not usmUserAuthProtocol or not usmUserPrivProtocol: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityLevel + ) + + # 3.1.3 + if securityLevel == 3 or securityLevel == 2: + if not usmUserAuthProtocol: + raise error.StatusInformation( + errorIndication = errind.unsupportedSecurityLevel + ) + + securityParameters = self.__securityParametersSpec + + scopedPDUData = msg.setComponentByPosition(3).getComponentByPosition(3) + scopedPDUData.setComponentByPosition( + 0, scopedPDU, verifyConstraints=False + ) + + # 3.1.6a + if securityStateReference is None and ( # request type check added + securityLevel == 3 or securityLevel == 2 + ): + if securityEngineID in self.__timeline: + ( snmpEngineBoots, + snmpEngineTime, + latestReceivedEngineTime, + latestUpdateTimestamp) = self.__timeline[ + securityEngineID + ] + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline') + else: + # 2.3 XXX is this correct? + snmpEngineBoots = snmpEngineTime = 0 + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: no timeline for securityEngineID %r' % (securityEngineID,)) + # 3.1.6.b + elif securityStateReference is not None: # XXX Report? + ( snmpEngineBoots, + snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') + snmpEngineBoots = snmpEngineBoots.syntax + snmpEngineTime = snmpEngineTime.syntax.clone() + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD') + # 3.1.6.c + else: + snmpEngineBoots = snmpEngineTime = 0 + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime') + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use snmpEngineBoots %s snmpEngineTime %s for securityEngineID %r' % (snmpEngineBoots, snmpEngineTime, securityEngineID)) + + # 3.1.4a + if securityLevel == 3: + if usmUserPrivProtocol in self.privServices: + privHandler = self.privServices[usmUserPrivProtocol] + else: + raise error.StatusInformation( + errorIndication = errind.encryptionError + ) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU %s' % scopedPDU.prettyPrint()) + + dataToEncrypt = encoder.encode(scopedPDU) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU encoded into %r' % (dataToEncrypt,)) + + ( encryptedData, + privParameters ) = privHandler.encryptData( + usmUserPrivKeyLocalized, + ( snmpEngineBoots, snmpEngineTime, None ), + dataToEncrypt + ) + + securityParameters.setComponentByPosition( + 5, privParameters, verifyConstraints=False + ) + scopedPDUData.setComponentByPosition( + 1, encryptedData, verifyConstraints=False + ) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU ciphered') + + # 3.1.4b + elif securityLevel == 1 or securityLevel == 2: + securityParameters.setComponentByPosition(5, '') + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint()) + + # 3.1.5 + securityParameters.setComponentByPosition( + 0, securityEngineID, verifyConstraints=False + ) + securityParameters.setComponentByPosition( + 1, snmpEngineBoots, verifyConstraints=False + ) + securityParameters.setComponentByPosition( + 2, snmpEngineTime, verifyConstraints=False + ) + + # 3.1.7 + securityParameters.setComponentByPosition( + 3, usmUserName, verifyConstraints=False + ) + + # 3.1.8a + if securityLevel == 3 or securityLevel == 2: + if usmUserAuthProtocol in self.authServices: + authHandler = self.authServices[usmUserAuthProtocol] + else: + raise error.StatusInformation( + errorIndication = errind.authenticationFailure + ) + + # extra-wild hack to facilitate BER substrate in-place re-write + securityParameters.setComponentByPosition( + 4, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + ) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) + + msg.setComponentByPosition( + 2, encoder.encode(securityParameters), verifyConstraints=False + ) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: auth outgoing msg: %s' % msg.prettyPrint()) + + wholeMsg = encoder.encode(msg) + + authenticatedWholeMsg = authHandler.authenticateOutgoingMsg( + usmUserAuthKeyLocalized, wholeMsg + ) + # 3.1.8b + else: + securityParameters.setComponentByPosition( + 4, '', verifyConstraints=False + ) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) + + msg.setComponentByPosition( + 2, encoder.encode(securityParameters), verifyConstraints=False + ) + + debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: plain outgoing msg: %s' % msg.prettyPrint()) + + authenticatedWholeMsg = encoder.encode(msg) + # 3.1.9 + return ( + msg.getComponentByPosition(2), + authenticatedWholeMsg + ) + + def generateRequestMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + ): + return self.__generateRequestOrResponseMsg( + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + None + ) + + def generateResponseMsg( + self, + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ): + return self.__generateRequestOrResponseMsg( + snmpEngine, + messageProcessingModel, + globalData, + maxMessageSize, + securityModel, + securityEngineID, + securityName, + securityLevel, + scopedPDU, + securityStateReference + ) + + # 3.2 + def processIncomingMsg( + self, + snmpEngine, + messageProcessingModel, + maxMessageSize, + securityParameters, + securityModel, + securityLevel, + wholeMsg, + msg # XXX + ): + # 3.2.9 -- moved up here to be able to report + # maxSizeResponseScopedPDU on error + # (48 - maximum SNMPv3 header length) + maxSizeResponseScopedPDU = maxMessageSize - len(securityParameters)-48 + + # 3.2.1 + try: + securityParameters, rest = decoder.decode( + securityParameters, + asn1Spec=self.__securityParametersSpec + ) + except PyAsn1Error: + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) + snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') + snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 + raise error.StatusInformation( + errorIndication=errind.parseError + ) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),)) + + # 3.2.2 + msgAuthoritativeEngineID = securityParameters.getComponentByPosition(0) + securityStateReference = self._cache.push( + msgUserName=securityParameters.getComponentByPosition(3) + ) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cache write securityStateReference %s by msgUserName %s' % (securityStateReference, securityParameters.getComponentByPosition(3))) + + scopedPduData = msg.getComponentByPosition(3) + + # Used for error reporting + contextEngineId = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax + contextName = null + + # 3.2.3 + if msgAuthoritativeEngineID not in self.__timeline: + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %r' % (msgAuthoritativeEngineID,)) + if not msgAuthoritativeEngineID: + # 3.2.3b + usmStatsUnknownEngineIDs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs') + usmStatsUnknownEngineIDs.syntax = usmStatsUnknownEngineIDs.syntax+1 + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: null securityEngineID') + pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') + if pysnmpUsmDiscoverable.syntax: + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: request EngineID discovery') + + # Report original contextName + if scopedPduData.getName() != 'plaintext': + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPduData not plaintext %s' % scopedPduData.prettyPrint()) + raise error.StatusInformation( + errorIndication = errind.unknownEngineID + ) + + # 7.2.6.a.1 + scopedPdu = scopedPduData.getComponent() + contextEngineId = scopedPdu.getComponentByPosition(0) + contextName = scopedPdu.getComponentByPosition(1) + + raise error.StatusInformation( + errorIndication = errind.unknownEngineID, + oid=usmStatsUnknownEngineIDs.name, + val=usmStatsUnknownEngineIDs.syntax, + securityStateReference=securityStateReference, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + scopedPDU=scopedPdu, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU + ) + else: + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: will not discover EngineID') + # free securityStateReference XXX + raise error.StatusInformation( + errorIndication = errind.unknownEngineID + ) + + snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax + + msgUserName = securityParameters.getComponentByPosition(3) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read from securityParams msgAuthoritativeEngineID %r msgUserName %r' % (msgAuthoritativeEngineID, msgUserName)) + + if msgUserName: + # 3.2.4 + try: + ( usmUserSecurityName, + usmUserAuthProtocol, + usmUserAuthKeyLocalized, + usmUserPrivProtocol, + usmUserPrivKeyLocalized ) = self.__getUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + msgAuthoritativeEngineID, + msgUserName + ) + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read user info from LCD') + except NoSuchInstanceError: + pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') + __reportUnknownName = not pysnmpUsmDiscoverable.syntax + if not __reportUnknownName: + try: + ( usmUserSecurityName, + usmUserAuthProtocol, + usmUserAuthKeyLocalized, + usmUserPrivProtocol, + usmUserPrivKeyLocalized ) = self.__cloneUserInfo( + snmpEngine.msgAndPduDsp.mibInstrumController, + msgAuthoritativeEngineID, + msgUserName + ) + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cloned user info') + except NoSuchInstanceError: + __reportUnknownName = 1 + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %r msgUserName %r' % (msgAuthoritativeEngineID, msgUserName)) + if __reportUnknownName: + usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') + usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 + raise error.StatusInformation( + errorIndication = errind.unknownSecurityName, + oid = usmStatsUnknownUserNames.name, + val = usmStatsUnknownUserNames.syntax, + securityStateReference=securityStateReference, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU + ) + else: + # empty username used for engineID discovery + usmUserName = usmUserSecurityName = null + usmUserAuthProtocol = usmUserAuthKeyLocalized = None + usmUserPrivProtocol = usmUserPrivKeyLocalized = None + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: now have usmUserSecurityName %s usmUserAuthProtocol %s usmUserPrivProtocol %s for msgUserName %s' % (usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, msgUserName)) + + # 3.2.11 (moved up here to let Reports be authenticated & encrypted) + self._cache.pop(securityStateReference) + securityStateReference = self._cache.push( + msgUserName=securityParameters.getComponentByPosition(3), + usmUserAuthProtocol=usmUserAuthProtocol, + usmUserAuthKeyLocalized=usmUserAuthKeyLocalized, + usmUserPrivProtocol=usmUserPrivProtocol, + usmUserPrivKeyLocalized=usmUserPrivKeyLocalized + ) + + # 3.2.5 + __reportError = 0 + if securityLevel == 3: + if not usmUserAuthProtocol or not usmUserPrivProtocol: + __reportError = 1 + elif securityLevel == 2: + if not usmUserAuthProtocol: + __reportError = 1 + if __reportError: + usmStatsUnsupportedSecLevels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnsupportedSecLevels') + usmStatsUnsupportedSecLevels.syntax = usmStatsUnsupportedSecLevels.syntax + 1 + raise error.StatusInformation( + errorIndication=errind.unsupportedSecurityLevel, + oid=usmStatsUnknownEngineIDs.name, + val=usmStatsUnknownEngineIDs.syntax, + securityStateReference=securityStateReference, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU + ) + + # 3.2.6 + if securityLevel == 3 or securityLevel == 2: + if usmUserAuthProtocol in self.authServices: + authHandler = self.authServices[usmUserAuthProtocol] + else: + raise error.StatusInformation( + errorIndication = errind.authenticationFailure + ) + try: + authenticatedWholeMsg = authHandler.authenticateIncomingMsg( + usmUserAuthKeyLocalized, + securityParameters.getComponentByPosition(4), + wholeMsg + ) + except error.StatusInformation: + usmStatsWrongDigests, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsWrongDigests') + usmStatsWrongDigests.syntax = usmStatsWrongDigests.syntax+1 + raise error.StatusInformation( + errorIndication = errind.authenticationFailure, + oid=usmStatsWrongDigests.name, + val=usmStatsWrongDigests.syntax, + securityStateReference=securityStateReference, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU + ) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authenticated') + + if msgAuthoritativeEngineID: + # 3.2.3a moved down here to execute only for authed msg + self.__timeline[msgAuthoritativeEngineID] = ( + securityParameters.getComponentByPosition(1), + securityParameters.getComponentByPosition(2), + securityParameters.getComponentByPosition(2), + int(time.time()) + ) + + expireAt = self.__expirationTimer + 300 + if expireAt not in self.__timelineExpQueue: + self.__timelineExpQueue[expireAt] = [] + self.__timelineExpQueue[expireAt].append( + msgAuthoritativeEngineID + ) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: store timeline for securityEngineID %r' % (msgAuthoritativeEngineID,)) + + # 3.2.7 + if securityLevel == 3 or securityLevel == 2: + if msgAuthoritativeEngineID == snmpEngineID: + # Authoritative SNMP engine: use local notion (SF bug #1649032) + ( snmpEngineBoots, + snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') + snmpEngineBoots = snmpEngineBoots.syntax + snmpEngineTime = snmpEngineTime.syntax.clone() + idleTime = 0 + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read snmpEngineBoots (%s), snmpEngineTime (%s) from LCD' % (snmpEngineBoots, snmpEngineTime)) + else: + # Non-authoritative SNMP engine: use cached estimates + if msgAuthoritativeEngineID in self.__timeline: + ( snmpEngineBoots, + snmpEngineTime, + latestReceivedEngineTime, + latestUpdateTimestamp ) = self.__timeline[ + msgAuthoritativeEngineID + ] + # time passed since last talk with this SNMP engine + idleTime = int(time.time())-latestUpdateTimestamp + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read timeline snmpEngineBoots %s snmpEngineTime %s for msgAuthoritativeEngineID %r, idle time %s secs' % (snmpEngineBoots, snmpEngineTime, msgAuthoritativeEngineID, idleTime)) + else: + raise error.ProtocolError('Peer SNMP engine info missing') + + msgAuthoritativeEngineBoots = securityParameters.getComponentByPosition(1) + msgAuthoritativeEngineTime = securityParameters.getComponentByPosition(2) + + # 3.2.7a + if msgAuthoritativeEngineID == snmpEngineID: + if snmpEngineBoots == 2147483647 or \ + snmpEngineBoots != msgAuthoritativeEngineBoots or \ + abs(idleTime + int(snmpEngineTime) - \ + int(msgAuthoritativeEngineTime)) > 150: + usmStatsNotInTimeWindows, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsNotInTimeWindows') + usmStatsNotInTimeWindows.syntax = usmStatsNotInTimeWindows.syntax+1 + raise error.StatusInformation( + errorIndication = errind.notInTimeWindow, + oid=usmStatsNotInTimeWindows.name, + val=usmStatsNotInTimeWindows.syntax, + securityStateReference=securityStateReference, + securityLevel=2, + contextEngineId=contextEngineId, + contextName=contextName, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU + ) + # 3.2.7b + else: + # 3.2.7b.1 + if msgAuthoritativeEngineBoots > snmpEngineBoots or \ + msgAuthoritativeEngineBoots == snmpEngineBoots and \ + msgAuthoritativeEngineTime > latestReceivedEngineTime: + self.__timeline[msgAuthoritativeEngineID] = ( + msgAuthoritativeEngineBoots, + msgAuthoritativeEngineTime, + msgAuthoritativeEngineTime, + int(time.time()) + ) + expireAt = self.__expirationTimer + 300 + if expireAt not in self.__timelineExpQueue: + self.__timelineExpQueue[expireAt] = [] + self.__timelineExpQueue[expireAt].append( + msgAuthoritativeEngineID + ) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineID %r' % (msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineID)) + + # 3.2.7b.2 + if snmpEngineBoots == 2147483647 or \ + msgAuthoritativeEngineBoots < snmpEngineBoots or \ + msgAuthoritativeEngineBoots == snmpEngineBoots and \ + abs(idleTime + int(snmpEngineTime) - \ + int(msgAuthoritativeEngineTime)) > 150: + raise error.StatusInformation( + errorIndication = errind.notInTimeWindow + ) + + # 3.2.8a + if securityLevel == 3: + if usmUserPrivProtocol in self.privServices: + privHandler = self.privServices[usmUserPrivProtocol] + else: + raise error.StatusInformation( + errorIndication = errind.decryptionError + ) + encryptedPDU = scopedPduData.getComponentByPosition(1) + if encryptedPDU is None: # no ciphertext + raise error.StatusInformation( + errorIndication = errind.decryptionError + ) + + try: + decryptedData = privHandler.decryptData( + usmUserPrivKeyLocalized, + ( securityParameters.getComponentByPosition(1), + securityParameters.getComponentByPosition(2), + securityParameters.getComponentByPosition(5) ), + encryptedPDU + ) + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: PDU deciphered into %r' % (decryptedData,)) + except error.StatusInformation: + usmStatsDecryptionErrors, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsDecryptionErrors') + usmStatsDecryptionErrors.syntax = usmStatsDecryptionErrors.syntax+1 + raise error.StatusInformation( + errorIndication = errind.decryptionError, + oid=usmStatsDecryptionErrors.name, + val=usmStatsDecryptionErrors.syntax, + securityStateReference=securityStateReference, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU + ) + scopedPduSpec = scopedPduData.setComponentByPosition(0).getComponentByPosition(0) + try: + scopedPDU, rest = decoder.decode( + decryptedData, asn1Spec=scopedPduSpec + ) + except PyAsn1Error: + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoder failed %s' % sys.exc_info()[0]) + raise error.StatusInformation( + errorIndication = errind.decryptionError + ) + else: + # 3.2.8b + scopedPDU = scopedPduData.getComponentByPosition(0) + if scopedPDU is None: # no plaintext + raise error.StatusInformation( + errorIndication = errind.decryptionError + ) + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoded %s' % scopedPDU.prettyPrint()) + + # 3.2.10 + securityName = usmUserSecurityName + + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cached msgUserName %s info by securityStateReference %s' % (msgUserName, securityStateReference)) + + # Delayed to include details + if not msgUserName and not msgAuthoritativeEngineID: + usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') + usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 + raise error.StatusInformation( + errorIndication=errind.unknownSecurityName, + oid=usmStatsUnknownUserNames.name, + val=usmStatsUnknownUserNames.syntax, + securityStateReference=securityStateReference, + securityEngineID=msgAuthoritativeEngineID, + securityLevel=securityLevel, + contextEngineId=contextEngineId, + contextName=contextName, + maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, + PDU=scopedPDU + ) + + # 3.2.12 + return ( msgAuthoritativeEngineID, + securityName, + scopedPDU, + maxSizeResponseScopedPDU, + securityStateReference ) + + def __expireTimelineInfo(self): + if self.__expirationTimer in self.__timelineExpQueue: + for engineIdKey in self.__timelineExpQueue[self.__expirationTimer]: + if engineIdKey in self.__timeline: + del self.__timeline[engineIdKey] + debug.logger & debug.flagSM and debug.logger('__expireEnginesInfo: expiring %s' % (engineIdKey,)) + del self.__timelineExpQueue[self.__expirationTimer] + self.__expirationTimer = self.__expirationTimer + 1 + + def receiveTimerTick(self, snmpEngine, timeNow): + self.__expireTimelineInfo() diff -Nru python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3826/priv/aes.py python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3826/priv/aes.py --- python-pysnmp4-4.1.9a/pysnmp/proto/secmod/rfc3826/priv/aes.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/proto/secmod/rfc3826/priv/aes.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,135 @@ +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 +from pyasn1.type import univ +from pysnmp.proto import errind, error + +try: + from Crypto.Cipher import AES +except ImportError: + AES = None + +random.seed() + +# RFC3826 + +# + +class Aes(base.AbstractEncryptionService): + serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol + keySize = 16 + _localInt = random.randrange(0, 0xffffffffffffffff) + # 3.1.2.1 + def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime): + salt = [ + self._localInt>>56&0xff, + self._localInt>>48&0xff, + self._localInt>>40&0xff, + self._localInt>>32&0xff, + self._localInt>>24&0xff, + self._localInt>>16&0xff, + self._localInt>>8&0xff, + self._localInt&0xff + ] + + if self._localInt == 0xffffffffffffffff: + self._localInt = 0 + else: + self._localInt = self._localInt + 1 + + return self.__getDecryptionKey( + privKey, snmpEngineBoots, snmpEngineTime, salt + ) + ( univ.OctetString(salt).asOctets(), ) + + def __getDecryptionKey(self, privKey, snmpEngineBoots, + snmpEngineTime, salt): + snmpEngineBoots, snmpEngineTime, salt = ( + int(snmpEngineBoots), int(snmpEngineTime), salt + ) + + iv = [ snmpEngineBoots>>24&0xff, + snmpEngineBoots>>16&0xff, + snmpEngineBoots>>8&0xff, + snmpEngineBoots&0xff, + snmpEngineTime>>24&0xff, + snmpEngineTime>>16&0xff, + snmpEngineTime>>8&0xff, + snmpEngineTime&0xff ] + salt + + return privKey[:self.keySize].asOctets(), univ.OctetString(iv).asOctets() + + def hashPassphrase(self, authProtocol, privKey): + if authProtocol == hmacmd5.HmacMd5.serviceID: + return localkey.hashPassphraseMD5(privKey) + elif authProtocol == hmacsha.HmacSha.serviceID: + return localkey.hashPassphraseSHA(privKey) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + + def localizeKey(self, authProtocol, privKey, snmpEngineID): + if authProtocol == hmacmd5.HmacMd5.serviceID: + localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) + elif authProtocol == hmacsha.HmacSha.serviceID: + localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) + else: + raise error.ProtocolError( + 'Unknown auth protocol %s' % (authProtocol,) + ) + return localPrivKey[:16] + + # 3.2.4.1 + def encryptData(self, encryptKey, privParameters, dataToEncrypt): + if AES is None: + raise error.StatusInformation( + errorIndication=errind.encryptionError + ) + + snmpEngineBoots, snmpEngineTime, salt = privParameters + + # 3.3.1.1 + aesKey, iv, salt = self.__getEncryptionKey( + encryptKey, snmpEngineBoots, snmpEngineTime + ) + + # 3.3.1.3 + aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128) + + # PyCrypto seems to require padding + dataToEncrypt = dataToEncrypt + univ.OctetString((0,) * (16-len(dataToEncrypt)%16)).asOctets() + + ciphertext = aesObj.encrypt(dataToEncrypt) + + # 3.3.1.4 + return univ.OctetString(ciphertext), univ.OctetString(salt) + + # 3.2.4.2 + def decryptData(self, decryptKey, privParameters, encryptedData): + if AES is None: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + snmpEngineBoots, snmpEngineTime, salt = privParameters + + # 3.3.2.1 + if len(salt) != 8: + raise error.StatusInformation( + errorIndication=errind.decryptionError + ) + + # 3.3.2.3 + aesKey, iv = self.__getDecryptionKey( + decryptKey, snmpEngineBoots, snmpEngineTime, salt + ) + + aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128) + + # PyCrypto seems to require padding + encryptedData = encryptedData + univ.OctetString((0,) * (16-len(encryptedData)%16)).asOctets() + + # 3.3.2.4-6 + return aesObj.decrypt(encryptedData.asOctets()) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/builder.py python-pysnmp4-4.2.2/pysnmp/smi/builder.py --- python-pysnmp4-4.1.9a/pysnmp/smi/builder.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/builder.py 2012-04-21 09:46:47.000000000 +0000 @@ -0,0 +1,352 @@ +# MIB modules loader +import os, sys, imp, struct, marshal, time +from pysnmp.smi import error +from pysnmp import debug + +if sys.version_info[0] <= 2: + import types + classTypes = (types.ClassType, type) +else: + classTypes = (type,) + +class __AbstractMibSource: + def __init__(self, srcName): + self._srcName = srcName + self.__magic = imp.get_magic() + self.__sfx = {} + self.__inited = None + for sfx, mode, typ in imp.get_suffixes(): + if typ not in self.__sfx: + self.__sfx[typ] = [] + self.__sfx[typ].append((sfx, len(sfx), mode)) + debug.logger & debug.flagBld and debug.logger('trying %s' % self) + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, self._srcName) + + def _uniqNames(self, files): + u = {} + for f in files: + if f[:9] == '__init__.': + continue + for typ in (imp.PY_SOURCE, imp.PY_COMPILED): + for sfx, sfxLen, mode in self.__sfx[typ]: + if f[-sfxLen:] == sfx: + u[f[:-sfxLen]] = None + return tuple(u.keys()) + + # MibSource API follows + + def fullPath(self, f='', sfx=''): + return self._srcName + (f and (os.sep + f + sfx) or '') + + def init(self): + if self.__inited is None: + self.__inited = self._init() + if self.__inited is self: + self.__inited = True + if self.__inited is True: + return self + else: + return self.__inited + def listdir(self): return self._listdir() + def read(self, f): + for pycSfx, pycSfxLen, pycMode in self.__sfx[imp.PY_COMPILED]: + p = os.path.join(self._srcName, f) + pycSfx + try: + pycData = self._getData(p, pycMode) + except IOError: + pycTime = -1 + else: + if self.__magic == pycData[:4]: + pycData = pycData[4:] + pycTime = struct.unpack('= pyTime: + return marshal.loads(pycData), pycSfx + if pyTime != -1: + return self._getData(p, pyMode), pySfx + + raise IOError('No suitable module found') + +class ZipMibSource(__AbstractMibSource): + def _init(self): + try: + p = __import__( + self._srcName, globals(), locals(), self._srcName.split('.') + ) + if hasattr(p, '__loader__'): + self.__loader = p.__loader__ + self._srcName = self._srcName.replace('.', os.sep) + return self + else: + # Dir relative to PYTHONPATH + return DirMibSource(os.path.split(p.__file__)[0]).init() + except ImportError: + # Dir relative to CWD + return DirMibSource(self._srcName).init() + + def _parseDosTime(self, dosdate, dostime): + t = ( ((dosdate >> 9) & 0x7f) + 1980, # year + ((dosdate >> 5) & 0x0f), # month + dosdate & 0x1f, # mday + (dostime >> 11) & 0x1f, # hour + (dostime >> 5) & 0x3f, # min + (dostime & 0x1f) * 2, # sec + -1, # wday + -1, # yday + -1 ) # dst + return time.mktime(t) + + def _listdir(self): + l = [] + for f in self.__loader._files.keys(): + d, f = os.path.split(f) + if d == self._srcName: + l.append(f) + return tuple(self._uniqNames(l)) + + def _getTimestamp(self, p): + if p in self.__loader._files: + return self._parseDosTime( + self.__loader._files[p][6], + self.__loader._files[p][5] + ) + else: + raise IOError('No file in ZIP: %s' % p) + + def _getData(self, p, mode=None): return self.__loader.get_data(p) + +class DirMibSource(__AbstractMibSource): + def _init(self): + self._srcName = os.path.normpath(self._srcName) + return self + + def _listdir(self): + try: + return self._uniqNames(os.listdir(self._srcName)) + except OSError: + return () + + def _getTimestamp(self, p): + return os.stat(p)[8] + + def _getData(self, p, mode): return open(p, mode).read() + +class MibBuilder: + loadTexts = 0 + defaultCoreMibs = 'pysnmp.smi.mibs.instances:pysnmp.smi.mibs' + defaultMiscMibs = 'pysnmp_mibs' + moduleID = 'PYSNMP_MODULE_ID' + def __init__(self): + self.lastBuildId = self._autoName = 0 + sources = [] + 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 os.environ['PYSNMP_MIB_DIRS'].split(':'): + sources.append(DirMibSource(m)) + if self.defaultMiscMibs: + for m in self.defaultMiscMibs.split(':'): + try: + sources.append(ZipMibSource(m)) + except ImportError: + pass + self.mibSymbols = {} + self.__modSeen = {} + self.__modPathsSeen = {} + self.setMibSources(*sources) + + # MIB modules management + + def setMibSources(self, *mibSources): + self.__mibSources = [ s.init() for s in mibSources ] + debug.logger & debug.flagBld and debug.logger('setMibPath: new MIB sources %s' % (self.__mibSources,)) + + def getMibSources(self): return tuple(self.__mibSources) + + # Legacy/compatibility methods (won't work for .eggs) + def setMibPath(self, *mibPaths): + self.setMibSources(*[ DirMibSource(x) for x in mibPaths ]) + + def getMibPath(self): + paths = () + for mibSource in self.getMibSources(): + if isinstance(mibSource, DirMibSource): + paths += ( mibSource.fullPath(), ) + else: + raise error.SmiError( + 'MIB source is not a plain directory: %s' % (mibSource,) + ) + return paths + + def loadModules(self, *modNames, **userCtx): + # Build a list of available modules + if not modNames: + modNames = {} + for mibSource in self.__mibSources: + for modName in mibSource.listdir(): + modNames[modName] = None + modNames = list(modNames.keys()) + if not modNames: + raise error.SmiError( + 'No MIB module to load at %s' % (self,) + ) + + for modName in modNames: + for mibSource in self.__mibSources: + debug.logger & debug.flagBld and debug.logger('loadModules: trying %s at %s' % (modName, mibSource)) + try: + modData, sfx = mibSource.read(modName) + 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) + + if modPath in self.__modPathsSeen: + debug.logger & debug.flagBld and debug.logger('loadModules: seen %s' % modPath) + break + else: + self.__modPathsSeen[modPath] = 1 + + debug.logger & debug.flagBld and debug.logger('loadModules: evaluating %s' % modPath) + + g = { 'mibBuilder': self, + 'userCtx': userCtx } + + try: + exec(modData, g) + except Exception: + del self.__modPathsSeen[modPath] + raise error.SmiError( + 'MIB module \"%s\" load error: %s' % (modPath, sys.exc_info()[1]) + ) + + self.__modSeen[modName] = modPath + + debug.logger & debug.flagBld and debug.logger('loadModules: loaded %s' % modPath) + + break + + if modName not in self.__modSeen: + raise error.SmiError( + 'MIB file \"%s\" not found in search path' % (modName and modName + ".py[co]") + ) + + return self + + def unloadModules(self, *modNames): + if not modNames: + modNames = list(self.mibSymbols.keys()) + for modName in modNames: + if modName not in self.mibSymbols: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + self.unexportSymbols(modName) + del self.__modPathsSeen[self.__modSeen[modName]] + del self.__modSeen[modName] + + debug.logger & debug.flagBld and debug.logger('unloadModules: ' % (modName)) + + return self + + def importSymbols(self, modName, *symNames, **userCtx): + if not modName: + raise error.SmiError( + 'importSymbols: empty MIB module name' + ) + r = () + for symName in symNames: + if modName not in self.mibSymbols: + self.loadModules(modName, **userCtx) + if modName not in self.mibSymbols: + raise error.SmiError( + 'No module %s loaded at %s' % (modName, self) + ) + if symName not in self.mibSymbols[modName]: + raise error.SmiError( + 'No symbol %s::%s at %s' % (modName, symName, self) + ) + r = r + (self.mibSymbols[modName][symName],) + return r + + def exportSymbols(self, modName, *anonymousSyms, **namedSyms): + if modName not in self.mibSymbols: + self.mibSymbols[modName] = {} + mibSymbols = self.mibSymbols[modName] + + for symObj in anonymousSyms: + debug.logger & debug.flagBld and debug.logger('exportSymbols: anonymous symbol %s::__pysnmp_%ld' % (modName, self._autoName)) + mibSymbols['__pysnmp_%ld' % self._autoName] = symObj + self._autoName = self._autoName + 1 + for symName, symObj in namedSyms.items(): + if symName in mibSymbols: + raise error.SmiError( + 'Symbol %s already exported at %s' % (symName, modName) + ) + + if symName != self.moduleID and \ + not isinstance(symObj, classTypes): + label = symObj.getLabel() + if label: + symName = label + else: + symObj.setLabel(symName) + + mibSymbols[symName] = symObj + + debug.logger & debug.flagBld and debug.logger('exportSymbols: symbol %s::%s' % (modName, symName)) + + self.lastBuildId = self.lastBuildId + 1 + + def unexportSymbols(self, modName, *symNames): + if modName not in self.mibSymbols: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + mibSymbols = self.mibSymbols[modName] + if not symNames: + symNames = list(mibSymbols.keys()) + for symName in symNames: + if symName not in mibSymbols: + raise error.SmiError( + 'No symbol %s::%s at %s' % (modName, symName, self) + ) + del mibSymbols[symName] + + debug.logger & debug.flagBld and debug.logger('unexportSymbols: symbol %s::%s' % (modName, symName)) + + if not self.mibSymbols[modName]: + del self.mibSymbols[modName] + + self.lastBuildId = self.lastBuildId + 1 + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/error.py python-pysnmp4-4.2.2/pysnmp/smi/error.py --- python-pysnmp4-4.1.9a/pysnmp/smi/error.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/error.py 2011-01-20 14:57:01.000000000 +0000 @@ -0,0 +1,37 @@ +from pyasn1.error import PyAsn1Error +from pysnmp.error import PySnmpError + +class SmiError(PySnmpError, PyAsn1Error): pass +class MibOperationError(SmiError): + def __init__(self, **kwargs): self.__outArgs = kwargs + def __str__(self): return '%s(%s)' % ( + self.__class__.__name__, self.__outArgs + ) + def __getitem__(self, key): return self.__outArgs[key] + def __contains__(self, key): return key in self.__outArgs + def get(self, key, defVal=None): return self.__outArgs.get(key, defVal) + def keys(self): return self.__outArgs.keys() + def update(self, d): self.__outArgs.update(d) + +# Aligned with SNMPv2 PDU error-status +class GenError(MibOperationError): pass +class NoAccessError(MibOperationError): pass +class WrongTypeError(MibOperationError): pass +class WrongValueError(MibOperationError): pass +class NoCreationError(MibOperationError): pass +class InconsistentValueError(MibOperationError): pass +class ResourceUnavailableError(MibOperationError): pass +class CommitFailedError(MibOperationError): pass +class UndoFailedError(MibOperationError): pass +class AuthorizationError(MibOperationError): pass +class NotWritableError(MibOperationError): pass +class InconsistentNameError(MibOperationError): pass + +# Aligned with SNMPv2 Var-Bind exceptions +class NoSuchObjectError(MibOperationError): pass +class NoSuchInstanceError(NoSuchObjectError): pass +class EndOfMibViewError(MibOperationError): pass + +# Row management +class RowCreationWanted(MibOperationError): pass +class RowDestructionWanted(MibOperationError): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/exval.py python-pysnmp4-4.2.2/pysnmp/smi/exval.py --- python-pysnmp4-4.1.9a/pysnmp/smi/exval.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/exval.py 2010-11-14 23:41:18.000000000 +0000 @@ -0,0 +1,6 @@ +from pysnmp.proto import rfc1905 + +noSuchObject = rfc1905.noSuchObject +noSuchInstance = rfc1905.noSuchInstance +endOfMibView = endOfMib = rfc1905.endOfMibView + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/indices.py python-pysnmp4-4.2.2/pysnmp/smi/indices.py --- python-pysnmp4-4.1.9a/pysnmp/smi/indices.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/indices.py 2011-11-07 07:50:46.000000000 +0000 @@ -0,0 +1,86 @@ +"""Ordered dictionaries classes used for indices""" +from bisect import bisect + +class OrderedDict(dict): + def __init__(self, **kwargs): + self.__keys = [] + self.__dirty = 1 + super(OrderedDict, self).__init__() + if kwargs: + self.update(kwargs) + def __setitem__(self, key, value): + if key not in self: + self.__keys.append(key) + super(OrderedDict, self).__setitem__(key, value) + self.__dirty = 1 + def __repr__(self): + if self.__dirty: self.__order() + return super(OrderedDict, self).__repr__() + def __str__(self): + if self.__dirty: self.__order() + return super(OrderedDict, self).__str__() + def __delitem__(self, key): + if super(OrderedDict, self).__contains__(key): + self.__keys.remove(key) + super(OrderedDict, self).__delitem__(key) + self.__dirty = 1 + __delattr__ = __delitem__ + def clear(self): + super(OrderedDict, self).clear() + self.__keys = [] + self.__dirty = 1 + def keys(self): + if self.__dirty: self.__order() + return list(self.__keys) + def values(self): + if self.__dirty: self.__order() + return [ self[k] for k in self.__keys ] + def items(self): + if self.__dirty: self.__order() + 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 = list(d.keys()) + l.sort(reverse=True) + self.__keysLens = tuple(l) + self.__dirty = 0 + def nextKey(self, key): + keys = list(self.keys()) + if key in self: + nextIdx = keys.index(key) + 1 + else: + nextIdx = bisect(keys, key) + if nextIdx < len(keys): + return keys[nextIdx] + else: + raise KeyError(key) + def getKeysLens(self): + if self.__dirty: self.__order() + return self.__keysLens + +class OidOrderedDict(OrderedDict): + def __init__(self, **kwargs): + self.__keysCache = {} + OrderedDict.__init__(self, **kwargs) + + def __setitem__(self, key, value): + if key not in self.__keysCache: + if isinstance(key, tuple): + self.__keysCache[key] = key + else: + self.__keysCache[key] = [ int(x) for x in key.split('.') if x ] + OrderedDict.__setitem__(self, key, value) + + def __delitem__(self, key): + if key in self.__keysCache: + del self.__keysCache[key] + OrderedDict.__delitem__(self, key) + __delattr__ = __delitem__ + + def sortingFun(self, keys): + keys.sort(key=lambda k, d=self.__keysCache: d[k]) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/__init__.py python-pysnmp4-4.2.2/pysnmp/smi/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/smi/__init__.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/__init__.py 2004-11-12 14:21:30.000000000 +0000 @@ -0,0 +1 @@ +"""SNMP SMI""" diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/instrum.py python-pysnmp4-4.2.2/pysnmp/smi/instrum.py --- python-pysnmp4-4.1.9a/pysnmp/smi/instrum.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/instrum.py 2012-04-13 19:04:42.000000000 +0000 @@ -0,0 +1,243 @@ +# MIB modules management +import sys +from pysnmp.smi import error +from pysnmp import debug + +__all__ = [ 'MibInstrumController' ] + +class MibInstrumController: + fsmReadVar = { + # ( state, status ) -> newState + ('start', 'ok'): 'readTest', + ('readTest', 'ok'): 'readGet', + ('readGet', 'ok'): 'stop', + ('*', 'err'): 'stop' + } + fsmReadVarFast = { + # ( state, status ) -> newState + ('start', 'ok'): 'readGet', + ('readGet', 'ok'): 'stop', + ('*', 'err'): 'stop' + } + fsmReadNextVar = { + # ( state, status ) -> newState + ('start', 'ok'): 'readTestNext', + ('readTestNext', 'ok'): 'readGetNext', + ('readGetNext', 'ok'): 'stop', + ('*', 'err'): 'stop' + } + fsmWriteVar = { + # ( state, status ) -> newState + ('start', 'ok'): 'writeTest', + ('writeTest', 'ok'): 'writeCommit', + ('writeCommit', 'ok'): 'writeCleanup', + ('writeCleanup', 'ok'): 'readTest', + # Do read after successful write + ('readTest', 'ok'): 'readGet', + ('readGet', 'ok'): 'stop', + # Error handling + ('writeTest', 'err'): 'writeCleanup', + ('writeCommit', 'err'): 'writeUndo', + ('writeUndo', 'ok'): 'readTest', + # Ignore read errors (removed columns) + ('readTest', 'err'): 'stop', + ('readGet', 'err'): 'stop', + ('*', 'err'): 'stop' + } + + def __init__(self, mibBuilder): + self.mibBuilder = mibBuilder + self.lastBuildId = -1 + self.lastBuildSyms = {} + + # MIB indexing + + def __indexMib(self): + # Build a tree from MIB objects found at currently loaded modules + if self.lastBuildId == self.mibBuilder.lastBuildId: + return + + ( MibScalarInstance, + MibScalar, + MibTableColumn, + MibTableRow, + MibTable, + MibTree ) = self.mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance', + 'MibScalar', + 'MibTableColumn', + 'MibTableRow', + 'MibTable', + 'MibTree' + ) + + mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') + + # + # Management Instrumentation gets organized as follows: + # + # MibTree + # | + # +----MibScalar + # | | + # | +-----MibScalarInstance + # | + # +----MibTable + # | + # +----MibTableRow + # | + # +-------MibTableColumn + # | + # +------MibScalarInstance(s) + # + # Mind you, only Managed Objects get indexed here, various MIB defs and + # constants can't be SNMP managed so we drop them. + # + scalars = {}; instances = {}; tables = {}; rows = {}; cols = {} + + # Sort by module name to give user a chance to slip-in + # custom MIB modules (that would be sorted out first) + 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 isinstance(symObj, MibTable): + tables[symObj.name] = symObj + elif isinstance(symObj, MibTableRow): + rows[symObj.name] = symObj + elif isinstance(symObj, MibTableColumn): + cols[symObj.name] = symObj + elif isinstance(symObj, MibScalarInstance): + instances[symObj.name] = symObj + elif isinstance(symObj, MibScalar): + scalars[symObj.name] = symObj + + # Detach items from each other + for symName, parentName in self.lastBuildSyms.items(): + if parentName in scalars: + scalars[parentName].unregisterSubtrees(symName) + elif parentName in cols: + cols[parentName].unregisterSubtrees(symName) + elif parentName in rows: + rows[parentName].unregisterSubtrees(symName) + else: + mibTree.unregisterSubtrees(symName) + + lastBuildSyms = {} + + # Attach Managed Objects Instances to Managed Objects + for inst in instances.values(): + if inst.typeName in scalars: + scalars[inst.typeName].registerSubtrees(inst) + elif inst.typeName in cols: + cols[inst.typeName].registerSubtrees(inst) + else: + raise error.SmiError( + 'Orphan MIB scalar instance %s at %s' % (inst, self) + ) + lastBuildSyms[inst.name] = inst.typeName + + # Attach Table Columns to Table Rows + for col in cols.values(): + rowName = col.name[:-1] # XXX + if rowName in rows: + rows[rowName].registerSubtrees(col) + else: + raise error.SmiError( + 'Orphan MIB table column %s at %s' % (col, self) + ) + lastBuildSyms[col.name] = rowName + + # Attach Table Rows to MIB tree + for row in rows.values(): + mibTree.registerSubtrees(row) + lastBuildSyms[row.name] = mibTree.name + + # Attach Tables to MIB tree + for table in tables.values(): + mibTree.registerSubtrees(table) + lastBuildSyms[table.name] = mibTree.name + + # Attach Scalars to MIB tree + for scalar in scalars.values(): + mibTree.registerSubtrees(scalar) + lastBuildSyms[scalar.name] = mibTree.name + + self.lastBuildSyms = lastBuildSyms + + self.lastBuildId = self.mibBuilder.lastBuildId + + debug.logger & debug.flagIns and debug.logger('__indexMib: rebuilt') + + # MIB instrumentation + + def flipFlopFsm(self, fsmTable, inputNameVals, acInfo): + self.__indexMib() + debug.logger & debug.flagIns and debug.logger('flipFlopFsm: inputNameVals %r' % (inputNameVals,)) + mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') + outputNameVals = [] + state, status = 'start', 'ok' + origExc = None + while 1: + k = (state, status) + if k in fsmTable: + fsmState = fsmTable[k] + else: + k = ('*', status) + if k in fsmTable: + fsmState = fsmTable[k] + else: + raise error.SmiError( + 'Unresolved FSM state %s, %s' % (state, status) + ) + debug.logger & debug.flagIns and debug.logger('flipFlopFsm: state %s status %s -> fsmState %s' % (state, status, fsmState)) + state = fsmState + status = 'ok' + if state == 'stop': + break + idx = 0 + for name, val in inputNameVals: + f = getattr(mibTree, state, None) + if f is None: + raise error.SmiError( + 'Unsupported state handler %s at %s' % (state, self) + ) + try: + # Convert to tuple to avoid ObjectName instantiation + # on subscription + rval = f(tuple(name), val, idx, acInfo) + except error.SmiError: + debug.logger & debug.flagIns and debug.logger('flipFlopFsm: fun %s failed %s for %s=%r' % (f, sys.exc_info()[1], name, val)) + if origExc is None: # Take the first exception + origExc, origTraceback = sys.exc_info()[1:3] + status = 'err' + break + else: + debug.logger & debug.flagIns and debug.logger('flipFlopFsm: fun %s suceeded for %s=%r' % (f, name, val)) + if rval is not None: + outputNameVals.append((rval[0], rval[1])) + idx = idx + 1 + if origExc: + if sys.version_info[0] <= 2: + raise origExc + else: + try: + raise origExc.with_traceback(origTraceback) + finally: + # Break cycle between locals and traceback object + # (seems to be irrelevant on Py3 but just in case) + del origTraceback + return outputNameVals + + 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, acInfo=(None, None)): + return self.flipFlopFsm(self.fsmReadVarFast, vars, acInfo) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/ASN1-ENUMERATION.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/ASN1-ENUMERATION.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/ASN1-ENUMERATION.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/ASN1-ENUMERATION.py 2011-12-05 14:54:07.000000000 +0000 @@ -0,0 +1,7 @@ +# ASN.1 types enumeration tools +from pyasn1.type import namedval + +mibBuilder.exportSymbols( + 'ASN1-ENUMERATION', + NamedValues=namedval.NamedValues + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/ASN1.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/ASN1.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/ASN1.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/ASN1.py 2011-12-05 14:54:07.000000000 +0000 @@ -0,0 +1,12 @@ +# ASN.1 objects used in SNMP +from pyasn1.type import univ +from pysnmp.proto import rfc1902 + +mibBuilder.exportSymbols( + 'ASN1', + ObjectIdentifier=univ.ObjectIdentifier, + # Instead of using base ASN,1 types we use SNMPv2 SMI ones to make + # SMI objects type-compatible with SNMP protocol values + Integer=rfc1902.Integer32, + OctetString=rfc1902.OctetString + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/ASN1-REFINEMENT.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/ASN1-REFINEMENT.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/ASN1-REFINEMENT.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/ASN1-REFINEMENT.py 2011-12-05 14:54:07.000000000 +0000 @@ -0,0 +1,11 @@ +# ASN.1 types refinement tools +from pyasn1.type import constraint + +mibBuilder.exportSymbols( + 'ASN1-REFINEMENT', + ConstraintsUnion=constraint.ConstraintsUnion, + ConstraintsIntersection=constraint.ConstraintsIntersection, + SingleValueConstraint=constraint.SingleValueConstraint, + ValueRangeConstraint=constraint.ValueRangeConstraint, + ValueSizeConstraint=constraint.ValueSizeConstraint + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py 2006-06-23 21:18:37.000000000 +0000 @@ -0,0 +1,20 @@ +( MibScalarInstance, ) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance' + ) + +( pysnmpUsmDiscoverable, + pysnmpUsmDiscovery ) = mibBuilder.importSymbols( + 'PYSNMP-USM-MIB', + 'pysnmpUsmDiscoverable', + 'pysnmpUsmDiscovery' + ) + +__pysnmpUsmDiscoverable = MibScalarInstance(pysnmpUsmDiscoverable.name, (0,), pysnmpUsmDiscoverable.syntax) +__pysnmpUsmDiscovery = MibScalarInstance(pysnmpUsmDiscovery.name, (0,), pysnmpUsmDiscovery.syntax) + +mibBuilder.exportSymbols( + "__PYSNMP-USM-MIB", + pysnmpUsmDiscoverable = __pysnmpUsmDiscoverable, + pysnmpUsmDiscovery = __pysnmpUsmDiscovery + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py 2007-02-14 07:59:20.000000000 +0000 @@ -0,0 +1,30 @@ +import time + +( MibScalarInstance, ) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance' + ) + +( snmpEngineID, + snmpEngineBoots, + snmpEngineTime, + snmpEngineMaxMessageSize ) = mibBuilder.importSymbols( + 'SNMP-FRAMEWORK-MIB', + 'snmpEngineID', + 'snmpEngineBoots', + 'snmpEngineTime', + 'snmpEngineMaxMessageSize' + ) + +__snmpEngineID = MibScalarInstance(snmpEngineID.name, (0,), snmpEngineID.syntax) +__snmpEngineBoots = MibScalarInstance(snmpEngineBoots.name, (0,), snmpEngineBoots.syntax.clone(1)) +__snmpEngineTime = MibScalarInstance(snmpEngineTime.name, (0,), snmpEngineTime.syntax.clone(int(time.time()))) +__snmpEngineMaxMessageSize = MibScalarInstance(snmpEngineMaxMessageSize.name, (0,), snmpEngineMaxMessageSize.syntax.clone(4096)) + +mibBuilder.exportSymbols( + '__SNMP-FRAMEWORK-MIB', + snmpEngineID = __snmpEngineID, + snmpEngineBoots = __snmpEngineBoots, + snmpEngineTime = __snmpEngineTime, + snmpEngineMaxMessageSize = __snmpEngineMaxMessageSize + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py 2006-06-23 21:18:37.000000000 +0000 @@ -0,0 +1,23 @@ +( MibScalarInstance, ) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance' + ) +( snmpUnknownSecurityModels, + snmpInvalidMsgs, + snmpUnknownPDUHandlers ) = mibBuilder.importSymbols( + 'SNMP-MPD-MIB', + 'snmpUnknownSecurityModels', + 'snmpInvalidMsgs', + 'snmpUnknownPDUHandlers', + ) + +__snmpUnknownSecurityModels = MibScalarInstance(snmpUnknownSecurityModels.name, (0,), snmpUnknownSecurityModels.syntax.clone(0)) +__snmpInvalidMsgs = MibScalarInstance(snmpInvalidMsgs.name, (0,), snmpInvalidMsgs.syntax.clone(0)) +__snmpUnknownPDUHandlers = MibScalarInstance(snmpUnknownPDUHandlers.name, (0,), snmpUnknownPDUHandlers.syntax.clone(0)) + +mibBuilder.exportSymbols( + '__SNMP-MPD-MIB', + snmpUnknownSecurityModels = __snmpUnknownSecurityModels, + snmpInvalidMsgs = __snmpInvalidMsgs, + snmpUnknownPDUHandlers = __snmpUnknownPDUHandlers + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py 2006-06-23 21:18:37.000000000 +0000 @@ -0,0 +1,25 @@ +( MibScalarInstance, ) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance' + ) + +( snmpTargetSpinLock, + snmpUnavailableContexts, + snmpUnknownContexts ) = mibBuilder.importSymbols( + 'SNMP-TARGET-MIB', + 'snmpTargetSpinLock', + 'snmpUnavailableContexts', + 'snmpUnknownContexts' + ) + +__snmpTargetSpinLock = MibScalarInstance(snmpTargetSpinLock.name, (0,), snmpTargetSpinLock.syntax.clone(0)) +__snmpUnavailableContexts = MibScalarInstance(snmpUnavailableContexts.name, (0,), snmpUnavailableContexts.syntax.clone(0)) +__snmpUnknownContexts = MibScalarInstance(snmpUnknownContexts.name, (0,), snmpUnknownContexts.syntax.clone(0)) + +mibBuilder.exportSymbols( + '__SNMP-TARGET-MIB', + snmpTargetSpinLock = __snmpTargetSpinLock, + snmpUnavailableContexts = __snmpUnavailableContexts, + snmpUnknownContexts = __snmpUnknownContexts + ) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py 2006-06-23 21:18:37.000000000 +0000 @@ -0,0 +1,41 @@ +( MibScalarInstance, ) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance' + ) + +( usmStatsUnsupportedSecLevels, + usmStatsNotInTimeWindows, + usmStatsUnknownUserNames, + usmStatsUnknownEngineIDs, + usmStatsWrongDigests, + usmStatsDecryptionErrors, + usmUserSpinLock ) = mibBuilder.importSymbols( + 'SNMP-USER-BASED-SM-MIB', + 'usmStatsUnsupportedSecLevels', + 'usmStatsNotInTimeWindows', + 'usmStatsUnknownUserNames', + 'usmStatsUnknownEngineIDs', + 'usmStatsWrongDigests', + 'usmStatsDecryptionErrors', + 'usmUserSpinLock' + ) + +__usmStatsUnsupportedSecLevels = MibScalarInstance(usmStatsUnsupportedSecLevels.name, (0,), usmStatsUnsupportedSecLevels.syntax.clone(0)) +__usmStatsNotInTimeWindows = MibScalarInstance(usmStatsNotInTimeWindows.name, (0,), usmStatsNotInTimeWindows.syntax.clone(0)) +__usmStatsUnknownUserNames = MibScalarInstance(usmStatsUnknownUserNames.name, (0,), usmStatsUnknownUserNames.syntax.clone(0)) +__usmStatsUnknownEngineIDs = MibScalarInstance(usmStatsUnknownEngineIDs.name, (0,), usmStatsUnknownEngineIDs.syntax.clone(0)) +__usmStatsWrongDigests = MibScalarInstance(usmStatsWrongDigests.name, (0,), usmStatsWrongDigests.syntax.clone(0)) +__usmStatsDecryptionErrors = MibScalarInstance(usmStatsDecryptionErrors.name, (0,), usmStatsDecryptionErrors.syntax.clone(0)) +__usmUserSpinLock = MibScalarInstance(usmUserSpinLock.name, (0,), usmUserSpinLock.syntax.clone(0)) + +mibBuilder.exportSymbols( + '__SNMP-USER-BASED-SM-MIB', + usmStatsUnsupportedSecLevels = __usmStatsUnsupportedSecLevels, + usmStatsNotInTimeWindows = __usmStatsNotInTimeWindows, + usmStatsUnknownUserNames = __usmStatsUnknownUserNames, + usmStatsUnknownEngineIDs = __usmStatsUnknownEngineIDs, + usmStatsWrongDigests = __usmStatsWrongDigests, + usmStatsDecryptionErrors = __usmStatsDecryptionErrors, + usmUserSpinLock = __usmUserSpinLock + ) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py 2011-11-07 07:50:47.000000000 +0000 @@ -0,0 +1,180 @@ +from sys import version +from time import time +from pysnmp import majorVersionId + +( MibScalarInstance, + TimeTicks) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance', + 'TimeTicks' + ) + +( sysDescr, + sysObjectID, + sysUpTime, + sysContact, + sysName, + sysLocation, + sysServices, + sysORLastChange, + snmpInPkts, + snmpOutPkts, + snmpInBadVersions, + snmpInBadCommunityNames, + snmpInBadCommunityUses, + snmpInASNParseErrs, + snmpInTooBigs, + snmpInNoSuchNames, + snmpInBadValues, + snmpInReadOnlys, + snmpInGenErrs, + snmpInTotalReqVars, + snmpInTotalSetVars, + snmpInGetRequests, + snmpInGetNexts, + snmpInSetRequests, + snmpInGetResponses, + snmpInTraps, + snmpOutTooBigs, + snmpOutNoSuchNames, + snmpOutBadValues, + snmpOutGenErrs, + snmpOutSetRequests, + snmpOutGetResponses, + snmpOutTraps, + snmpEnableAuthenTraps, + snmpSilentDrops, + snmpProxyDrops, + snmpTrapOID, + coldStart, + snmpSetSerialNo ) = mibBuilder.importSymbols( + 'SNMPv2-MIB', + 'sysDescr', + 'sysObjectID', + 'sysUpTime', + 'sysContact', + 'sysName', + 'sysLocation', + 'sysServices', + 'sysORLastChange', + 'snmpInPkts', + 'snmpOutPkts', + 'snmpInBadVersions', + 'snmpInBadCommunityNames', + 'snmpInBadCommunityUses', + 'snmpInASNParseErrs', + 'snmpInTooBigs', + 'snmpInNoSuchNames', + 'snmpInBadValues', + 'snmpInReadOnlys', + 'snmpInGenErrs', + 'snmpInTotalReqVars', + 'snmpInTotalSetVars', + 'snmpInGetRequests', + 'snmpInGetNexts', + 'snmpInSetRequests', + 'snmpInGetResponses', + 'snmpInTraps', + 'snmpOutTooBigs', + 'snmpOutNoSuchNames', + 'snmpOutBadValues', + 'snmpOutGenErrs', + 'snmpOutSetRequests', + 'snmpOutGetResponses', + 'snmpOutTraps', + 'snmpEnableAuthenTraps', + 'snmpSilentDrops', + 'snmpProxyDrops', + 'snmpTrapOID', + 'coldStart', + 'snmpSetSerialNo' + ) + +__sysDescr = MibScalarInstance(sysDescr.name, (0,), sysDescr.syntax.clone("PySNMP engine version %s, Python %s" % (majorVersionId, version))) +__sysObjectID = MibScalarInstance(sysObjectID.name, (0,), sysObjectID.syntax.clone((1,3,6,1,4,1,20408))) + +class SysUpTime(TimeTicks): + createdAt = time() + def clone(self, **kwargs): + if 'value' not in kwargs: + kwargs['value'] = int((time()-self.createdAt)*100) + return TimeTicks.clone(self, **kwargs) + +__sysUpTime = MibScalarInstance(sysUpTime.name, (0,), SysUpTime(0)) +__sysContact = MibScalarInstance(sysContact.name, (0,), sysContact.syntax.clone('')) +__sysName = MibScalarInstance(sysName.name, (0,), sysName.syntax.clone('')) +__sysLocation = MibScalarInstance(sysLocation.name, (0,), sysLocation.syntax.clone('')) +__sysServices = MibScalarInstance(sysServices.name, (0,), sysServices.syntax.clone(0)) +__sysORLastChange = MibScalarInstance(sysORLastChange.name, (0,), sysORLastChange.syntax.clone(0)) +__snmpInPkts = MibScalarInstance(snmpInPkts.name, (0,), snmpInPkts.syntax.clone(0)) +__snmpOutPkts = MibScalarInstance(snmpOutPkts.name, (0,), snmpOutPkts.syntax.clone(0)) +__snmpInBadVersions = MibScalarInstance(snmpInBadVersions.name, (0,), snmpInBadVersions.syntax.clone(0)) +__snmpInBadCommunityNames = MibScalarInstance(snmpInBadCommunityNames.name, (0,), snmpInBadCommunityNames.syntax.clone(0)) +__snmpInBadCommunityUses = MibScalarInstance(snmpInBadCommunityUses.name, (0,), snmpInBadCommunityUses.syntax.clone(0)) +__snmpInASNParseErrs = MibScalarInstance(snmpInASNParseErrs.name, (0,), snmpInASNParseErrs.syntax.clone(0)) +__snmpInTooBigs = MibScalarInstance(snmpInTooBigs.name, (0,), snmpInTooBigs.syntax.clone(0)) +__snmpInNoSuchNames = MibScalarInstance(snmpInNoSuchNames.name, (0,), snmpInNoSuchNames.syntax.clone(0)) +__snmpInBadValues = MibScalarInstance(snmpInBadValues.name, (0,), snmpInBadValues.syntax.clone(0)) +__snmpInReadOnlys = MibScalarInstance(snmpInReadOnlys.name, (0,), snmpInReadOnlys.syntax.clone(0)) +__snmpInGenErrs = MibScalarInstance(snmpInGenErrs.name, (0,), snmpInGenErrs.syntax.clone(0)) +__snmpInTotalReqVars = MibScalarInstance(snmpInTotalReqVars.name, (0,), snmpInTotalReqVars.syntax.clone(0)) +__snmpInTotalSetVars = MibScalarInstance(snmpInTotalSetVars.name, (0,), snmpInTotalSetVars.syntax.clone(0)) +__snmpInGetRequests = MibScalarInstance(snmpInGetRequests.name, (0,), snmpInGetRequests.syntax.clone(0)) +__snmpInGetNexts = MibScalarInstance(snmpInGetNexts.name, (0,), snmpInGetNexts.syntax.clone(0)) +__snmpInSetRequests = MibScalarInstance(snmpInSetRequests.name, (0,), snmpInSetRequests.syntax.clone(0)) +__snmpInGetResponses = MibScalarInstance(snmpInGetResponses.name, (0,), snmpInGetResponses.syntax.clone(0)) +__snmpInTraps = MibScalarInstance(snmpInTraps.name, (0,), snmpInTraps.syntax.clone(0)) +__snmpOutTooBigs = MibScalarInstance(snmpOutTooBigs.name, (0,), snmpOutTooBigs.syntax.clone(0)) +__snmpOutNoSuchNames = MibScalarInstance(snmpOutNoSuchNames.name, (0,), snmpOutNoSuchNames.syntax.clone(0)) +__snmpOutBadValues = MibScalarInstance(snmpOutBadValues.name, (0,), snmpOutBadValues.syntax.clone(0)) +__snmpOutGenErrs = MibScalarInstance(snmpOutGenErrs.name, (0,), snmpOutGenErrs.syntax.clone(0)) +__snmpOutSetRequests = MibScalarInstance(snmpOutSetRequests.name, (0,), snmpOutSetRequests.syntax.clone(0)) +__snmpOutGetResponses = MibScalarInstance(snmpOutGetResponses.name, (0,), snmpOutGetResponses.syntax.clone(0)) +__snmpOutTraps = MibScalarInstance(snmpOutTraps.name, (0,), snmpOutTraps.syntax.clone(0)) +__snmpEnableAuthenTraps = MibScalarInstance(snmpEnableAuthenTraps.name, (0,), snmpEnableAuthenTraps.syntax.clone(1)) +__snmpSilentDrops = MibScalarInstance(snmpSilentDrops.name, (0,), snmpSilentDrops.syntax.clone(0)) +__snmpProxyDrops = MibScalarInstance(snmpProxyDrops.name, (0,), snmpProxyDrops.syntax.clone(0)) +__snmpTrapOID = MibScalarInstance(snmpTrapOID.name, (0,), snmpTrapOID.syntax.clone(coldStart.name)) +__snmpSetSerialNo = MibScalarInstance(snmpSetSerialNo.name, (0,), snmpSetSerialNo.syntax.clone(0)) + +mibBuilder.exportSymbols( + "__SNMPv2-MIB", + sysDescr = __sysDescr, + sysObjectID = __sysObjectID, + sysUpTime = __sysUpTime, + sysContact = __sysContact, + sysName = __sysName, + sysLocation = __sysLocation, + sysServices = __sysServices, + sysORLastChange = __sysORLastChange, + 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, + snmpOutSetRequests = __snmpOutSetRequests, + snmpOutGetResponses = __snmpOutGetResponses, + snmpOutTraps = __snmpOutTraps, + snmpEnableAuthenTraps = __snmpEnableAuthenTraps, + snmpSilentDrops = __snmpSilentDrops, + snmpProxyDrops = __snmpProxyDrops, + snmpTrapOID = __snmpTrapOID, + snmpSetSerialNo = __snmpSetSerialNo + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py 2006-06-23 21:18:37.000000000 +0000 @@ -0,0 +1,16 @@ +( MibScalarInstance, ) = mibBuilder.importSymbols( + 'SNMPv2-SMI', + 'MibScalarInstance' + ) + +( vacmViewSpinLock, ) = mibBuilder.importSymbols( + 'SNMP-VIEW-BASED-ACM-MIB', + 'vacmViewSpinLock' + ) + +__vacmViewSpinLock = MibScalarInstance(vacmViewSpinLock.name, (0,), vacmViewSpinLock.syntax) + +mibBuilder.exportSymbols( + "__SNMP-VIEW-BASED-ACM-MIB", + vacmViewSpinLock = __vacmViewSpinLock + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/PYSNMP-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/PYSNMP-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/PYSNMP-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/PYSNMP-MIB.py 2012-04-02 16:50:10.000000000 +0000 @@ -0,0 +1,41 @@ +# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-MIB +# by libsmi2pysnmp-0.1.3 at Mon Apr 2 20:50:10 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( Bits, Integer32, ModuleIdentity, MibIdentifier, TimeTicks, enterprises, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "TimeTicks", "enterprises") + +# Objects + +pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408)).setRevisions(("2005-05-14 00:00",)) +if mibBuilder.loadTexts: pysnmp.setOrganization("pysnmp.sf.net") +if mibBuilder.loadTexts: pysnmp.setContactInfo("email: ilya@glas.net") +if mibBuilder.loadTexts: pysnmp.setDescription("Top-level infrastructure of the PySNMP project enterprise MIB tree") +pysnmpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 1)) +pysnmpExamples = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 2)) +pysnmpEnumerations = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3)) +pysnmpModuleIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1)) +pysnmpAgentOIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 2)) +pysnmpDomains = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 3)) +pysnmpNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4)) +pysnmpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 0)) +pysnmpNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 1)) +pysnmpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5)) +pysnmpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 1)) +pysnmpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 2)) +pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999)) + +# Augmentions + +# Exports + +# Module identity +mibBuilder.exportSymbols("PYSNMP-MIB", PYSNMP_MODULE_ID=pysnmp) + +# Objects +mibBuilder.exportSymbols("PYSNMP-MIB", pysnmp=pysnmp, pysnmpObjects=pysnmpObjects, pysnmpExamples=pysnmpExamples, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpDomains=pysnmpDomains, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpNotifications=pysnmpNotifications, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpConformance=pysnmpConformance, pysnmpCompliances=pysnmpCompliances, pysnmpGroups=pysnmpGroups, pysnmpExperimental=pysnmpExperimental) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/PYSNMP-USM-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/PYSNMP-USM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/PYSNMP-USM-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/PYSNMP-USM-MIB.py 2012-04-03 08:45:33.000000000 +0000 @@ -0,0 +1,67 @@ +# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-USM-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 12:45:33 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( pysnmpModuleIDs, ) = mibBuilder.importSymbols("PYSNMP-MIB", "pysnmpModuleIDs") +( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") +( usmUserEntry, ) = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") +( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks") +( RowStatus, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus") + +# Objects + +pysnmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1)).setRevisions(("2005-05-14 00:00",)) +if mibBuilder.loadTexts: pysnmpUsmMIB.setOrganization("The PySNMP project") +if mibBuilder.loadTexts: pysnmpUsmMIB.setContactInfo("E-mail: ilya@glas.net\nSubscribe: pysnmp-users-request@lists.sourceforge.net") +if mibBuilder.loadTexts: pysnmpUsmMIB.setDescription("This MIB module defines objects specific to User\nSecurity Model (USM) implementation at PySNMP.") +pysnmpUsmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1)) +pysnmpUsmCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1)) +pysnmpUsmDiscoverable = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 1), Integer().subtype(subtypeSpec=SingleValueConstraint(1,0,)).subtype(namedValues=NamedValues(("notDiscoverable", 0), ("discoverable", 1), )).clone(1)).setMaxAccess("readwrite") +if mibBuilder.loadTexts: pysnmpUsmDiscoverable.setDescription("Whether SNMP engine would support its discovery by\nresponding to unknown clients.") +pysnmpUsmDiscovery = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 2), Integer().subtype(subtypeSpec=SingleValueConstraint(1,0,)).subtype(namedValues=NamedValues(("doNotDiscover", 0), ("doDiscover", 1), )).clone(1)).setMaxAccess("readwrite") +if mibBuilder.loadTexts: pysnmpUsmDiscovery.setDescription("Whether SNMP engine would try to figure out the EngineIDs\nof its peers by sending discover requests.") +pysnmpUsmSecretTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2)) +if mibBuilder.loadTexts: pysnmpUsmSecretTable.setDescription("The table of USM users passphrases configured in the SNMP \nengine's Local Configuration Datastore (LCD).") +pysnmpUsmSecretEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1)).setIndexNames((1, "PYSNMP-USM-MIB", "pysnmpUsmSecretUserName")) +if mibBuilder.loadTexts: pysnmpUsmSecretEntry.setDescription("Information about a particular USM user credentials.") +pysnmpUsmSecretUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmSecretUserName.setDescription("The username string for which a row in this table\nrepresents a configuration.") +pysnmpUsmSecretAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 65535))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmSecretAuthKey.setDescription("User's authentication passphrase used for localized key generation.") +pysnmpUsmSecretPrivKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 65535))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmSecretPrivKey.setDescription("User's encryption passphrase used for localized key generation.") +pysnmpUsmSecretStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: pysnmpUsmSecretStatus.setDescription("Table status") +pysnmpUsmUser = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3)) +pysnmpUsmKeyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1)) +if mibBuilder.loadTexts: pysnmpUsmKeyEntry.setDescription("Information about a particular USM user credentials.") +pysnmpUsmKeyAuthLocalized = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmKeyAuthLocalized.setDescription("User's localized key used for authentication.") +pysnmpUsmKeyPrivLocalized = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmKeyPrivLocalized.setDescription("User's localized key used for encryption.") +pysnmpUsmKeyAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmKeyAuth.setDescription("User's non-localized key used for authentication.") +pysnmpUsmKeyPriv = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: pysnmpUsmKeyPriv.setDescription("User's non-localized key used for encryption.") +pysnmpUsmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2)) +pysnmpUsmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2, 1)) +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")) +pysnmpUsmKeyEntry.setIndexNames(*usmUserEntry.getIndexNames()) + +# Exports + +# Module identity +mibBuilder.exportSymbols("PYSNMP-USM-MIB", PYSNMP_MODULE_ID=pysnmpUsmMIB) + +# Objects +mibBuilder.exportSymbols("PYSNMP-USM-MIB", pysnmpUsmMIB=pysnmpUsmMIB, pysnmpUsmMIBObjects=pysnmpUsmMIBObjects, pysnmpUsmCfg=pysnmpUsmCfg, pysnmpUsmDiscoverable=pysnmpUsmDiscoverable, pysnmpUsmDiscovery=pysnmpUsmDiscovery, pysnmpUsmSecretTable=pysnmpUsmSecretTable, pysnmpUsmSecretEntry=pysnmpUsmSecretEntry, pysnmpUsmSecretUserName=pysnmpUsmSecretUserName, pysnmpUsmSecretAuthKey=pysnmpUsmSecretAuthKey, pysnmpUsmSecretPrivKey=pysnmpUsmSecretPrivKey, pysnmpUsmSecretStatus=pysnmpUsmSecretStatus, pysnmpUsmUser=pysnmpUsmUser, pysnmpUsmKeyEntry=pysnmpUsmKeyEntry, pysnmpUsmKeyAuthLocalized=pysnmpUsmKeyAuthLocalized, pysnmpUsmKeyPrivLocalized=pysnmpUsmKeyPrivLocalized, pysnmpUsmKeyAuth=pysnmpUsmKeyAuth, pysnmpUsmKeyPriv=pysnmpUsmKeyPriv, pysnmpUsmMIBConformance=pysnmpUsmMIBConformance, pysnmpUsmMIBCompliances=pysnmpUsmMIBCompliances, pysnmpUsmMIBGroups=pysnmpUsmMIBGroups) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py 2012-04-05 07:03:19.000000000 +0000 @@ -0,0 +1,90 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-COMMUNITY-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 12:47:45 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( SnmpAdminString, SnmpEngineID, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID") +( SnmpTagValue, snmpTargetAddrEntry, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetAddrEntry") +( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") +( Bits, Integer32, Integer32, IpAddress, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "Integer32", "IpAddress", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") +( RowStatus, StorageType, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType") + +# Objects + +snmpCommunityMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 18)).setRevisions(("2000-03-06 00:00","1999-05-13 00:00",)) +if mibBuilder.loadTexts: snmpCommunityMIB.setOrganization("SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpCommunityMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In msg body: subscribe snmpv3\n\nChair: Russ Mundy\n TIS Labs at Network Associates\nPostal: 3060 Washington Rd\n Glenwood MD 21738\n USA\nEmail: mundy@tislabs.com\nPhone: +1-301-854-6889\n\nCo-editor: Rob Frye\n CoSine Communications\nPostal: 1200 Bridge Parkway\n Redwood City, CA 94065\n USA\nE-mail: rfrye@cosinecom.com\nPhone: +1 703 725 1130\n\nCo-editor: David B. Levi\n Nortel Networks\nPostal: 3505 Kesterwood Drive\n Knoxville, TN 37918\nE-mail: dlevi@nortelnetworks.com\nPhone: +1 423 686 0432\n\nCo-editor: Shawn A. Routhier\n Integrated Systems Inc.\nPostal: 333 North Ave 4th Floor\n Wakefield, MA 01880\nE-mail: sar@epilogue.com\nPhone: +1 781 245 0804\n\nCo-editor: Bert Wijnen\n Lucent Technologies\nPostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nEmail: bwijnen@lucent.com\nPhone: +31-348-407-775") +if mibBuilder.loadTexts: snmpCommunityMIB.setDescription("This MIB module defines objects to help support coexistence\nbetween SNMPv1, SNMPv2c, and SNMPv3.") +snmpCommunityMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 1)) +snmpCommunityTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 1)) +if mibBuilder.loadTexts: snmpCommunityTable.setDescription("The table of community strings configured in the SNMP\nengine's Local Configuration Datastore (LCD).") +snmpCommunityEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 1, 1)).setIndexNames((1, "SNMP-COMMUNITY-MIB", "snmpCommunityIndex")) +if mibBuilder.loadTexts: snmpCommunityEntry.setDescription("Information about a particular community string.") +snmpCommunityIndex = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: snmpCommunityIndex.setDescription("The unique index value of a row in this table.") +snmpCommunityName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 2), OctetString()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunityName.setDescription("The community string for which a row in this table\nrepresents a configuration.") +snmpCommunitySecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunitySecurityName.setDescription("A human readable string representing the corresponding\nvalue of snmpCommunityName in a Security Model\nindependent format.") +snmpCommunityContextEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 4), SnmpEngineID()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunityContextEngineID.setDescription("The contextEngineID indicating the location of the\ncontext in which management information is accessed\nwhen using the community string specified by the\ncorresponding instance of snmpCommunityName.\n\nThe default value is the snmpEngineID of the entity in\nwhich this object is instantiated.") +snmpCommunityContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunityContextName.setDescription("The context in which management information is accessed\nwhen using the community string specified by the corresponding\ninstance of snmpCommunityName.") +snmpCommunityTransportTag = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 6), SnmpTagValue().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunityTransportTag.setDescription("This object specifies a set of transport endpoints\nfrom which a command responder application will accept\nmanagement requests. If a management request containing\nthis community is received on a transport endpoint other\nthan the transport endpoints identified by this object,\nthe request is deemed unauthentic.\n\nThe transports identified by this object are specified\n\nin the snmpTargetAddrTable. Entries in that table\nwhose snmpTargetAddrTagList contains this tag value\nare identified.\n\nIf the value of this object has zero-length, transport\nendpoints are not checked when authenticating messages\ncontaining this community string.") +snmpCommunityStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 7), StorageType()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunityStorageType.setDescription("The storage type for this conceptual row in the\nsnmpCommunityTable. Conceptual rows having the value\n'permanent' need not allow write-access to any\ncolumnar object in the row.") +snmpCommunityStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpCommunityStatus.setDescription("The status of this conceptual row in the snmpCommunityTable.\n\nAn entry in this table is not qualified for activation\nuntil instances of all corresponding columns have been\ninitialized, either through default values, or through\nSet operations. The snmpCommunityName and\nsnmpCommunitySecurityName objects must be explicitly set.\n\nThere is no restriction on setting columns in this table\nwhen the value of snmpCommunityStatus is active(1).") +snmpTargetAddrExtTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 2)) +if mibBuilder.loadTexts: snmpTargetAddrExtTable.setDescription("The table of mask and mms values associated with the\n\nsnmpTargetAddrTable.\n\nThe snmpTargetAddrExtTable augments the\nsnmpTargetAddrTable with a transport address mask value\nand a maximum message size value. The transport address\nmask allows entries in the snmpTargetAddrTable to define\na set of addresses instead of just a single address.\nThe maximum message size value allows the maximum\nmessage size of another SNMP entity to be configured for\nuse in SNMPv1 (and SNMPv2c) transactions, where the\nmessage format does not specify a maximum message size.") +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=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\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=ConstraintsUnion(ValueRangeConstraint(0,0),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.") +snmpTrapCommunity = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 4), OctetString()).setMaxAccess("notifyonly") +if mibBuilder.loadTexts: snmpTrapCommunity.setDescription("The value of the community string field of an SNMPv1\nmessage containing a Trap PDU which is forwarded by a\na proxy forwarder application using an SNMP version\nother than SNMPv1. The value of this object SHOULD\ncontain the value of the community string field from\nthe original SNMPv1 message containing a Trap PDU as\ngenerated by an SNMPv1 agent.") +snmpCommunityMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2)) +snmpCommunityMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 1)) +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")) +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"), ) ) +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\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 + +# Module identity +mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", PYSNMP_MODULE_ID=snmpCommunityMIB) + +# Objects +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", snmpCommunityGroup=snmpCommunityGroup, snmpProxyTrapForwardGroup=snmpProxyTrapForwardGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityMIBCompliance=snmpCommunityMIBCompliance, snmpProxyTrapForwardCompliance=snmpProxyTrapForwardCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py 2012-04-03 11:06:14.000000000 +0000 @@ -0,0 +1,115 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-FRAMEWORK-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 12:50:45 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +try: + import socket + import os +except ImportError: + pass +import time + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") +( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") +( TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention") + +# Types + +class SnmpAdminString(TextualConvention, OctetString): + displayHint = "255t" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) + +class SnmpEngineID(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(5,32) + defaultValue = [128, 0, 79, 184, 5] + try: + # Attempt to base engine ID on local IP address + defaultValue = defaultValue + [ int(x) & 0xff for x in socket.gethostbyname(socket.gethostname()).split('.') ] + except: + pass + try: + # Attempt to base engine ID on PID + defaultValue = defaultValue + [os.getpid() >> 8 & 0xff, os.getpid() & 0xff] + except: + pass + # ...in any case, use pseudo-random text ID + t = int(time.time()) + defaultValue = 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: + value = int(time.time())-self._value + return Integer32.clone(self, value, tagSet, subtypeSpec) + +class SnmpMessageProcessingModel(Integer32): + subtypeSpec = Integer32.subtypeSpec+ValueRangeConstraint(0,2147483647) + +class SnmpSecurityLevel(Integer): + subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(1,3,2,) + namedValues = NamedValues(("noAuthNoPriv", 1), ("authNoPriv", 2), ("authPriv", 3), ) + +class SnmpSecurityModel(Integer32): + subtypeSpec = Integer32.subtypeSpec+ValueRangeConstraint(0,2147483647) + + +# Objects + +snmpFrameworkMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 10)).setRevisions(("2002-10-14 00:00","1999-01-19 00:00","1997-11-20 00:00",)) +if mibBuilder.loadTexts: snmpFrameworkMIB.setOrganization("SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpFrameworkMIB.setContactInfo("WG-EMail: snmpv3@lists.tislabs.com\nSubscribe: snmpv3-request@lists.tislabs.com\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\nCo-Chair &\nCo-editor: David Harrington\n Enterasys Networks\npostal: 35 Industrial Way\n P. O. Box 5005\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nphone: +1 603-337-2614\n\nCo-editor: Randy Presuhn\n BMC Software, Inc.\npostal: 2141 North First Street\n San Jose, California 95131\n USA\nEMail: randy_presuhn@bmc.com\nphone: +1 408-546-1006\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\n\nEMail: bwijnen@lucent.com\nphone: +31 348-680-485\n ") +if mibBuilder.loadTexts: snmpFrameworkMIB.setDescription("The SNMP Management Architecture MIB\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3411;\nsee the RFC itself for full legal notices.") +snmpFrameworkAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1)) +snmpAuthProtocols = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1)) +if mibBuilder.loadTexts: snmpAuthProtocols.setDescription("Registration point for standards-track\nauthentication protocols used in SNMP Management\nFrameworks.") +snmpPrivProtocols = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2)) +if mibBuilder.loadTexts: snmpPrivProtocols.setDescription("Registration point for standards-track privacy\nprotocols used in SNMP Management Frameworks.") +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=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=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=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)) +snmpFrameworkMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 2)) + +# Augmentions + +# Groups + +snmpEngineGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 10, 3, 2, 1)).setObjects(*(("SNMP-FRAMEWORK-MIB", "snmpEngineID"), ("SNMP-FRAMEWORK-MIB", "snmpEngineBoots"), ("SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize"), ("SNMP-FRAMEWORK-MIB", "snmpEngineTime"), ) ) +if mibBuilder.loadTexts: snmpEngineGroup.setDescription("A collection of objects for identifying and\ndetermining the configuration and current timeliness\n\nvalues of an SNMP engine.") + +# Compliances + +snmpFrameworkMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 10, 3, 1, 1)).setObjects(*(("SNMP-FRAMEWORK-MIB", "snmpEngineGroup"), ) ) +if mibBuilder.loadTexts: snmpFrameworkMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP Management Framework MIB.") + +# Exports + +# Module identity +mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", PYSNMP_MODULE_ID=snmpFrameworkMIB) + +# Types +mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", SnmpAdminString=SnmpAdminString, SnmpEngineID=SnmpEngineID, SnmpEngineTime=SnmpEngineTime, SnmpMessageProcessingModel=SnmpMessageProcessingModel, SnmpSecurityLevel=SnmpSecurityLevel, SnmpSecurityModel=SnmpSecurityModel) + +# Objects +mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpFrameworkMIB=snmpFrameworkMIB, snmpFrameworkAdmin=snmpFrameworkAdmin, snmpAuthProtocols=snmpAuthProtocols, snmpPrivProtocols=snmpPrivProtocols, snmpFrameworkMIBObjects=snmpFrameworkMIBObjects, snmpEngine=snmpEngine, snmpEngineID=snmpEngineID, snmpEngineBoots=snmpEngineBoots, snmpEngineTime=snmpEngineTime, snmpEngineMaxMessageSize=snmpEngineMaxMessageSize, snmpFrameworkMIBConformance=snmpFrameworkMIBConformance, snmpFrameworkMIBCompliances=snmpFrameworkMIBCompliances, snmpFrameworkMIBGroups=snmpFrameworkMIBGroups) + +# Groups +mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpEngineGroup=snmpEngineGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpFrameworkMIBCompliance=snmpFrameworkMIBCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-MPD-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-MPD-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-MPD-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-MPD-MIB.py 2012-04-03 11:13:13.000000000 +0000 @@ -0,0 +1,56 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-MPD-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 15:13:13 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") +( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") + +# Objects + +snmpMPDMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 11)).setRevisions(("2002-10-14 00:00","1999-05-04 16:36","1997-09-30 00:00",)) +if mibBuilder.loadTexts: snmpMPDMIB.setOrganization("SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpMPDMIB.setContactInfo("WG-EMail: snmpv3@lists.tislabs.com\nSubscribe: snmpv3-request@lists.tislabs.com\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\n\nEMail: mundy@tislabs.com\nphone: +1 301-947-7107\n\nCo-Chair &\nCo-editor: David Harrington\n Enterasys Networks\npostal: 35 Industrial Way\n P. O. Box 5005\n Rochester NH 03866-5005\n USA\nEMail: dbh@enterasys.com\nphone: +1 603-337-2614\n\nCo-editor: Jeffrey Case\n SNMP Research, Inc.\npostal: 3001 Kimberlin Heights Road\n Knoxville, TN 37920-9716\n USA\nEMail: case@snmp.com\nphone: +1 423-573-1434\n\nCo-editor: Randy Presuhn\n BMC Software, Inc.\npostal: 2141 North First Street\n San Jose, CA 95131\n USA\nEMail: randy_presuhn@bmc.com\nphone: +1 408-546-1006\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nEMail: bwijnen@lucent.com\nphone: +31 348-680-485") +if mibBuilder.loadTexts: snmpMPDMIB.setDescription("The MIB for Message Processing and Dispatching\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3412;\nsee the RFC itself for full legal notices.") +snmpMPDAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 1)) +snmpMPDMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2)) +snmpMPDStats = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2, 1)) +snmpUnknownSecurityModels = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 1), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpUnknownSecurityModels.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they referenced a\nsecurityModel that was not known to or supported by\nthe SNMP engine.") +snmpInvalidMsgs = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 2), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInvalidMsgs.setDescription("The total number of packets received by the SNMP\nengine which were dropped because there were invalid\nor inconsistent components in the SNMP message.") +snmpUnknownPDUHandlers = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 3), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpUnknownPDUHandlers.setDescription("The total number of packets received by the SNMP\nengine which were dropped because the PDU contained\nin the packet could not be passed to an application\nresponsible for handling the pduType, e.g. no SNMP\napplication had registered for the proper\ncombination of the contextEngineID and the pduType.") +snmpMPDMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3)) +snmpMPDMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 1)) +snmpMPDMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 2)) + +# Augmentions + +# 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 + +# Module identity +mibBuilder.exportSymbols("SNMP-MPD-MIB", PYSNMP_MODULE_ID=snmpMPDMIB) + +# Objects +mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDMIB=snmpMPDMIB, snmpMPDAdmin=snmpMPDAdmin, snmpMPDMIBObjects=snmpMPDMIBObjects, snmpMPDStats=snmpMPDStats, snmpUnknownSecurityModels=snmpUnknownSecurityModels, snmpInvalidMsgs=snmpInvalidMsgs, snmpUnknownPDUHandlers=snmpUnknownPDUHandlers, snmpMPDMIBConformance=snmpMPDMIBConformance, snmpMPDMIBCompliances=snmpMPDMIBCompliances, snmpMPDMIBGroups=snmpMPDMIBGroups) + +# Groups +mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDGroup=snmpMPDGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDCompliance=snmpMPDCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py 2012-04-04 16:55:19.000000000 +0000 @@ -0,0 +1,95 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-NOTIFICATION-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 15:14:42 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") +( SnmpTagValue, snmpTargetBasicGroup, snmpTargetBasicGroup, snmpTargetBasicGroup, snmpTargetParamsMPModel, snmpTargetParamsName, snmpTargetParamsRowStatus, snmpTargetParamsSecurityLevel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsStorageType, snmpTargetResponseGroup, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetBasicGroup", "snmpTargetBasicGroup", "snmpTargetBasicGroup", "snmpTargetParamsMPModel", "snmpTargetParamsName", "snmpTargetParamsRowStatus", "snmpTargetParamsSecurityLevel", "snmpTargetParamsSecurityModel", "snmpTargetParamsSecurityName", "snmpTargetParamsStorageType", "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 + +snmpNotificationMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 13)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) +if mibBuilder.loadTexts: snmpNotificationMIB.setOrganization("IETF SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpNotificationMIB.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\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: snmpNotificationMIB.setDescription("This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by an SNMP entity for the generation of\nnotifications.\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.") +snmpNotifyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 1)) +snmpNotifyTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 1)) +if mibBuilder.loadTexts: snmpNotifyTable.setDescription("This table is used to select management targets which should\nreceive notifications, as well as the type of notification\nwhich should be sent to each selected management target.") +snmpNotifyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 1, 1)).setIndexNames((1, "SNMP-NOTIFICATION-MIB", "snmpNotifyName")) +if mibBuilder.loadTexts: snmpNotifyEntry.setDescription("An entry in this table selects a set of management targets\nwhich should receive notifications, as well as the type of\n\nnotification which should be sent to each selected\nmanagement target.\n\nEntries in the snmpNotifyTable are created and\ndeleted using the snmpNotifyRowStatus object.") +snmpNotifyName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: snmpNotifyName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpNotifyEntry.") +snmpNotifyTag = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 2), SnmpTagValue().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyTag.setDescription("This object contains a single tag value which is used\nto select entries in the snmpTargetAddrTable. Any entry\nin the snmpTargetAddrTable which contains a tag value\nwhich is equal to the value of an instance of this\nobject is selected. If this object contains a value\nof zero length, no entries are selected.") +snmpNotifyType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 3), Integer().subtype(subtypeSpec=SingleValueConstraint(2,1,)).subtype(namedValues=NamedValues(("trap", 1), ("inform", 2), )).clone(1)).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyType.setDescription("This object determines the type of notification to\n\nbe generated for entries in the snmpTargetAddrTable\nselected by the corresponding instance of\nsnmpNotifyTag. This value is only used when\ngenerating notifications, and is ignored when\nusing the snmpTargetAddrTable for other purposes.\n\nIf the value of this object is trap(1), then any\nmessages generated for selected rows will contain\nUnconfirmed-Class PDUs.\n\nIf the value of this object is inform(2), then any\nmessages generated for selected rows will contain\nConfirmed-Class PDUs.\n\nNote that if an SNMP entity only supports\ngeneration of Unconfirmed-Class PDUs (and not\nConfirmed-Class PDUs), then this object may be\nread-only.") +snmpNotifyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +snmpNotifyRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).") +snmpNotifyFilterProfileTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 2)) +if mibBuilder.loadTexts: snmpNotifyFilterProfileTable.setDescription("This table is used to associate a notification filter\nprofile with a particular set of target parameters.") +snmpNotifyFilterProfileEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 2, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetParamsName")) +if mibBuilder.loadTexts: snmpNotifyFilterProfileEntry.setDescription("An entry in this table indicates the name of the filter\nprofile to be used when generating notifications using\nthe corresponding entry in the snmpTargetParamsTable.\n\nEntries in the snmpNotifyFilterProfileTable are created\nand deleted using the snmpNotifyFilterProfileRowStatus\nobject.") +snmpNotifyFilterProfileName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterProfileName.setDescription("The name of the filter profile to be used when generating\nnotifications using the corresponding entry in the\nsnmpTargetAddrTable.") +snmpNotifyFilterProfileStorType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 2), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterProfileStorType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +snmpNotifyFilterProfileRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterProfileRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the\nsnmpNotifyFilterProfileRowStatus column is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until the corresponding instance of\nsnmpNotifyFilterProfileName has been set.") +snmpNotifyFilterTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 3)) +if mibBuilder.loadTexts: snmpNotifyFilterTable.setDescription("The table of filter profiles. Filter profiles are used\nto determine whether particular management targets should\nreceive particular notifications.\n\nWhen a notification is generated, it must be compared\nwith the filters associated with each management target\nwhich is configured to receive notifications, in order to\ndetermine whether it may be sent to each such management\ntarget.\n\nA more complete discussion of notification filtering\ncan be found in section 6. of [SNMP-APPL].") +snmpNotifyFilterEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 3, 1)).setIndexNames((0, "SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), (1, "SNMP-NOTIFICATION-MIB", "snmpNotifyFilterSubtree")) +if mibBuilder.loadTexts: snmpNotifyFilterEntry.setDescription("An element of a filter profile.\n\nEntries in the snmpNotifyFilterTable are created and\ndeleted using the snmpNotifyFilterRowStatus object.") +snmpNotifyFilterSubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 1), ObjectIdentifier()).setMaxAccess("noaccess") +if mibBuilder.loadTexts: snmpNotifyFilterSubtree.setDescription("The MIB subtree which, when combined with the corresponding\ninstance of snmpNotifyFilterMask, defines a family of\nsubtrees which are included in or excluded from the\nfilter profile.") +snmpNotifyFilterMask = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterMask.setDescription("The bit mask which, in combination with the corresponding\ninstance of snmpNotifyFilterSubtree, defines a family of\nsubtrees which are included in or excluded from the\nfilter profile.\n\nEach bit of this bit mask corresponds to a\nsub-identifier of snmpNotifyFilterSubtree, with the\nmost significant bit of the i-th octet of this octet\nstring value (extended if necessary, see below)\ncorresponding to the (8*i - 7)-th sub-identifier, and\nthe least significant bit of the i-th octet of this\noctet string corresponding to the (8*i)-th\nsub-identifier, where i is in the range 1 through 16.\n\nEach bit of this bit mask specifies whether or not\nthe corresponding sub-identifiers must match when\ndetermining if an OBJECT IDENTIFIER matches this\nfamily of filter subtrees; a '1' indicates that an\nexact match must occur; a '0' indicates 'wild card',\ni.e., any sub-identifier value matches.\n\nThus, the OBJECT IDENTIFIER X of an object instance\nis contained in a family of filter subtrees if, for\neach sub-identifier of the value of\nsnmpNotifyFilterSubtree, either:\n\n the i-th bit of snmpNotifyFilterMask is 0, or\n\n the i-th sub-identifier of X is equal to the i-th\n sub-identifier of the value of\n snmpNotifyFilterSubtree.\n\nIf the value of this bit mask is M bits long and\nthere are more than M sub-identifiers in the\ncorresponding instance of snmpNotifyFilterSubtree,\nthen the bit mask is extended with 1's to be the\nrequired length.\n\nNote that when the value of this object is the\nzero-length string, this extension rule results in\na mask of all-1's being used (i.e., no 'wild card'),\nand the family of filter subtrees is the one\nsubtree uniquely identified by the corresponding\ninstance of snmpNotifyFilterSubtree.") +snmpNotifyFilterType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 3), Integer().subtype(subtypeSpec=SingleValueConstraint(1,2,)).subtype(namedValues=NamedValues(("included", 1), ("excluded", 2), )).clone(1)).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterType.setDescription("This object indicates whether the family of filter subtrees\ndefined by this entry are included in or excluded from a\nfilter. A more detailed discussion of the use of this\nobject can be found in section 6. of [SNMP-APPL].") +snmpNotifyFilterStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\n\nallow write-access to any columnar objects in the row.") +snmpNotifyFilterRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 5), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpNotifyFilterRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).") +snmpNotifyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3)) +snmpNotifyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 1)) +snmpNotifyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 2)) + +# Augmentions + +# Groups + +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,\nplus filtering and read-create operations on all related\ntables.") + +# Exports + +# Module identity +mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", PYSNMP_MODULE_ID=snmpNotificationMIB) + +# Objects +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", snmpNotifyGroup=snmpNotifyGroup, snmpNotifyFilterGroup=snmpNotifyFilterGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotifyBasicCompliance=snmpNotifyBasicCompliance, snmpNotifyBasicFiltersCompliance=snmpNotifyBasicFiltersCompliance, snmpNotifyFullCompliance=snmpNotifyFullCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-PROXY-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-PROXY-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-PROXY-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-PROXY-MIB.py 2012-04-03 11:16:38.000000000 +0000 @@ -0,0 +1,73 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-PROXY-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 15:16:38 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( 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\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=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=SingleValueConstraint(1,2,4,3,)).subtype(namedValues=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\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 -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-TARGET-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-TARGET-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-TARGET-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-TARGET-MIB.py 2012-04-05 07:03:19.000000000 +0000 @@ -0,0 +1,133 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-TARGET-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:05:39 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) +from pysnmp.smi import error + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( SnmpAdminString, SnmpMessageProcessingModel, SnmpSecurityLevel, SnmpSecurityModel, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpMessageProcessingModel", "SnmpSecurityLevel", "SnmpSecurityModel") +( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") +( Bits, Counter32, Integer32, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") +( RowStatus, StorageType, TAddress, TDomain, TextualConvention, TestAndIncr, TimeInterval, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TAddress", "TDomain", "TextualConvention", "TestAndIncr", "TimeInterval") + +# Types + +class SnmpTagList(TextualConvention, OctetString): + displayHint = "255t" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) + _delimiters = (' ', '\n', '\t', '\t') + def prettyIn(self, value): + inDelim = True + for v in str(value): + if v in self._delimiters: + if inDelim: + raise error.SmiError('Leading or multiple delimiters not allowed in tag list %r' % value) + inDelim = True + else: + inDelim = False + if value and inDelim: + raise error.SmiError('Dangling delimiter not allowed in tag list %r' % value) + return OctetString.prettyIn(self, value) + +class SnmpTagValue(TextualConvention, OctetString): + displayHint = "255t" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) + _delimiters = (' ', '\n', '\t', '\t') + def prettyIn(self, value): + for v in str(value): + if v in self._delimiters: + raise error.SmiError('Delimiters not allowed in tag value') + return OctetString.prettyIn(self, value) + +# Objects + +snmpTargetMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 12)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) +if mibBuilder.loadTexts: snmpTargetMIB.setOrganization("IETF SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpTargetMIB.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\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\n Roseville, Minnesota 55113\nEMail: paul_meyer@securecomputing.com\nPhone: +1 651 628 1592\n\nCo-editor: Bob Stewart\n Retired") +if mibBuilder.loadTexts: snmpTargetMIB.setDescription("This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters used\nby an SNMP entity for the generation of SNMP messages.\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.") +snmpTargetObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 1)) +snmpTargetSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 1), TestAndIncr()).setMaxAccess("readwrite") +if mibBuilder.loadTexts: snmpTargetSpinLock.setDescription("This object is used to facilitate modification of table\nentries in the SNMP-TARGET-MIB module by multiple\nmanagers. In particular, it is useful when modifying\nthe value of the snmpTargetAddrTagList object.\n\nThe procedure for modifying the snmpTargetAddrTagList\nobject is as follows:\n\n 1. Retrieve the value of snmpTargetSpinLock and\n of snmpTargetAddrTagList.\n\n 2. Generate a new value for snmpTargetAddrTagList.\n\n 3. Set the value of snmpTargetSpinLock to the\n retrieved value, and the value of\n snmpTargetAddrTagList to the new value. If\n the set fails for the snmpTargetSpinLock\n object, go back to step 1.") +snmpTargetAddrTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 2)) +if mibBuilder.loadTexts: snmpTargetAddrTable.setDescription("A table of transport addresses to be used in the generation\nof SNMP messages.") +snmpTargetAddrEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 2, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetAddrName")) +if mibBuilder.loadTexts: snmpTargetAddrEntry.setDescription("A transport address to be used in the generation\nof SNMP operations.\n\nEntries in the snmpTargetAddrTable are created and\ndeleted using the snmpTargetAddrRowStatus object.") +snmpTargetAddrName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: snmpTargetAddrName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpTargetAddrEntry.") +snmpTargetAddrTDomain = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 2), TDomain()).setMaxAccess("readcreate") +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") +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\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=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.") +snmpTargetAddrTagList = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 6), SnmpTagList().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetAddrTagList.setDescription("This object contains a list of tag values which are\nused to select target addresses for a particular\noperation.") +snmpTargetAddrParams = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetAddrParams.setDescription("The value of this object identifies an entry in the\nsnmpTargetParamsTable. The identified entry\ncontains SNMP parameters to be used when generating\nmessages to be sent to this transport address.") +snmpTargetAddrStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetAddrStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +snmpTargetAddrRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetAddrRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the snmpTargetAddrRowStatus\ncolumn is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until the corresponding instances of\nsnmpTargetAddrTDomain, snmpTargetAddrTAddress, and\nsnmpTargetAddrParams have all been set.\n\nThe following objects may not be modified while the\nvalue of this object is active(1):\n - snmpTargetAddrTDomain\n - snmpTargetAddrTAddress\nAn attempt to set these objects while the value of\nsnmpTargetAddrRowStatus is active(1) will result in\nan inconsistentValue error.") +snmpTargetParamsTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 3)) +if mibBuilder.loadTexts: snmpTargetParamsTable.setDescription("A table of SNMP target information to be used\nin the generation of SNMP messages.") +snmpTargetParamsEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 3, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetParamsName")) +if mibBuilder.loadTexts: snmpTargetParamsEntry.setDescription("A set of SNMP target information.\n\nEntries in the snmpTargetParamsTable are created and\ndeleted using the snmpTargetParamsRowStatus object.") +snmpTargetParamsName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +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=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.") +snmpTargetParamsSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 5), SnmpSecurityLevel()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetParamsSecurityLevel.setDescription("The Level of Security to be used when generating\nSNMP messages using this entry.") +snmpTargetParamsStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 6), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetParamsStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +snmpTargetParamsRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 7), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: snmpTargetParamsRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the snmpTargetParamsRowStatus\ncolumn is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until the corresponding\nsnmpTargetParamsMPModel,\nsnmpTargetParamsSecurityModel,\nsnmpTargetParamsSecurityName,\nand snmpTargetParamsSecurityLevel have all been set.\n\nThe following objects may not be modified while the\nvalue of this object is active(1):\n - snmpTargetParamsMPModel\n - snmpTargetParamsSecurityModel\n - snmpTargetParamsSecurityName\n - snmpTargetParamsSecurityLevel\nAn attempt to set these objects while the value of\nsnmpTargetParamsRowStatus is active(1) will result in\nan inconsistentValue error.") +snmpUnavailableContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 4), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpUnavailableContexts.setDescription("The total number of packets received by the SNMP\nengine which were dropped because the context\ncontained in the message was unavailable.") +snmpUnknownContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 5), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpUnknownContexts.setDescription("The total number of packets received by the SNMP\nengine which were dropped because the context\ncontained in the message was unknown.") +snmpTargetConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3)) +snmpTargetCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 1)) +snmpTargetGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 2)) + +# Augmentions + +# 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"), ) ) +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 + +# Module identity +mibBuilder.exportSymbols("SNMP-TARGET-MIB", PYSNMP_MODULE_ID=snmpTargetMIB) + +# Types +mibBuilder.exportSymbols("SNMP-TARGET-MIB", SnmpTagList=SnmpTagList, SnmpTagValue=SnmpTagValue) + +# Objects +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", snmpTargetBasicGroup=snmpTargetBasicGroup, snmpTargetResponseGroup=snmpTargetResponseGroup, snmpTargetCommandResponderGroup=snmpTargetCommandResponderGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetCommandResponderCompliance=snmpTargetCommandResponderCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py 2012-04-03 12:12:00.000000000 +0000 @@ -0,0 +1,13 @@ +# PySNMP SMI module. Autogenerated from smidump -f python Eurocrypt +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:12:00 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( Bits, Integer32, MibIdentifier, TimeTicks, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "MibIdentifier", "TimeTicks") + +# Exports + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py 2012-04-03 13:11:59.000000000 +0000 @@ -0,0 +1,141 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USER-BASED-SM-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:13:22 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( SnmpAdminString, SnmpEngineID, snmpAuthProtocols, snmpPrivProtocols, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID", "snmpAuthProtocols", "snmpPrivProtocols") +( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") +( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") +( AutonomousType, RowPointer, RowStatus, StorageType, TextualConvention, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "AutonomousType", "RowPointer", "RowStatus", "StorageType", "TextualConvention", "TestAndIncr") + +# Types + +class KeyChange(OctetString): + pass + + +# Objects + +usmNoAuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 1)) +if mibBuilder.loadTexts: usmNoAuthProtocol.setDescription("No Authentication Protocol.") +usmHMACMD5AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 2)) +if mibBuilder.loadTexts: usmHMACMD5AuthProtocol.setDescription("The HMAC-MD5-96 Digest Authentication Protocol.") +usmHMACSHAAuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 3)) +if mibBuilder.loadTexts: usmHMACSHAAuthProtocol.setDescription("The HMAC-SHA-96 Digest Authentication Protocol.") +usmNoPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 1)) +if mibBuilder.loadTexts: usmNoPrivProtocol.setDescription("No Privacy Protocol.") +usmDESPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 2)) +if mibBuilder.loadTexts: usmDESPrivProtocol.setDescription("The CBC-DES Symmetric Encryption Protocol.") +snmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 15)).setRevisions(("2002-10-16 00:00","1999-01-20 00:00","1997-11-20 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 Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nemail: mundy@tislabs.com\n\nphone: +1 301-947-7107\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 Uri Blumenthal\n Lucent Technologies\npostal: 67 Whippany Rd.\n Whippany, NJ 07981\n USA\nemail: uri@lucent.com\nphone: +1-973-386-2163\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nemail: bwijnen@lucent.com\nphone: +31-348-480-685") +if mibBuilder.loadTexts: snmpUsmMIB.setDescription("The management information definitions for the\nSNMP User-based Security Model.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3414;\nsee the RFC itself for full legal notices.") +usmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1)) +usmStats = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1, 1)) +usmStatsUnsupportedSecLevels = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 1), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: usmStatsUnsupportedSecLevels.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they requested a\nsecurityLevel that was unknown to the SNMP engine\nor otherwise unavailable.") +usmStatsNotInTimeWindows = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 2), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: usmStatsNotInTimeWindows.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they appeared\noutside of the authoritative SNMP engine's window.") +usmStatsUnknownUserNames = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 3), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: usmStatsUnknownUserNames.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they referenced a\nuser that was not known to the SNMP engine.") +usmStatsUnknownEngineIDs = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 4), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: usmStatsUnknownEngineIDs.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they referenced an\nsnmpEngineID that was not known to the SNMP engine.") +usmStatsWrongDigests = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 5), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: usmStatsWrongDigests.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they didn't\ncontain the expected digest value.") +usmStatsDecryptionErrors = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 6), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: usmStatsDecryptionErrors.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they could not be\ndecrypted.") +usmUser = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1, 2)) +usmUserSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 2, 1), TestAndIncr()).setMaxAccess("readwrite") +if mibBuilder.loadTexts: usmUserSpinLock.setDescription("An advisory lock used to allow several cooperating\nCommand Generator Applications to coordinate their\nuse of facilities to alter secrets in the\nusmUserTable.") +usmUserTable = MibTable((1, 3, 6, 1, 6, 3, 15, 1, 2, 2)) +if mibBuilder.loadTexts: usmUserTable.setDescription("The table of users configured in the SNMP engine's\nLocal Configuration Datastore (LCD).\n\nTo create a new user (i.e., to instantiate a new\nconceptual row in this table), it is recommended to\nfollow this procedure:\n\n 1) GET(usmUserSpinLock.0) and save in sValue.\n\n 2) SET(usmUserSpinLock.0=sValue,\n usmUserCloneFrom=templateUser,\n usmUserStatus=createAndWait)\n You should use a template user to clone from\n which has the proper auth/priv protocol defined.\n\nIf the new user is to use privacy:\n\n 3) generate the keyChange value based on the secret\n privKey of the clone-from user and the secret key\n to be used for the new user. Let us call this\n pkcValue.\n 4) GET(usmUserSpinLock.0) and save in sValue.\n 5) SET(usmUserSpinLock.0=sValue,\n usmUserPrivKeyChange=pkcValue\n usmUserPublic=randomValue1)\n 6) GET(usmUserPulic) and check it has randomValue1.\n If not, repeat steps 4-6.\n\nIf the new user will never use privacy:\n\n 7) SET(usmUserPrivProtocol=usmNoPrivProtocol)\n\nIf the new user is to use authentication:\n\n 8) generate the keyChange value based on the secret\n authKey of the clone-from user and the secret key\n to be used for the new user. Let us call this\n akcValue.\n 9) GET(usmUserSpinLock.0) and save in sValue.\n 10) SET(usmUserSpinLock.0=sValue,\n usmUserAuthKeyChange=akcValue\n usmUserPublic=randomValue2)\n 11) GET(usmUserPulic) and check it has randomValue2.\n If not, repeat steps 9-11.\n\nIf the new user will never use authentication:\n\n 12) SET(usmUserAuthProtocol=usmNoAuthProtocol)\n\nFinally, activate the new user:\n\n 13) SET(usmUserStatus=active)\n\nThe new user should now be available and ready to be\nused for SNMPv3 communication. Note however that access\nto MIB data must be provided via configuration of the\nSNMP-VIEW-BASED-ACM-MIB.\n\nThe use of usmUserSpinlock is to avoid conflicts with\nanother SNMP command generator application which may\nalso be acting on the usmUserTable.") +usmUserEntry = MibTableRow((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1)).setIndexNames((0, "SNMP-USER-BASED-SM-MIB", "usmUserEngineID"), (0, "SNMP-USER-BASED-SM-MIB", "usmUserName")) +if mibBuilder.loadTexts: usmUserEntry.setDescription("A user configured in the SNMP engine's Local\nConfiguration Datastore (LCD) for the User-based\nSecurity Model.") +usmUserEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 1), SnmpEngineID()).setMaxAccess("noaccess") +if mibBuilder.loadTexts: usmUserEngineID.setDescription("An SNMP engine's administratively-unique identifier.\n\nIn a simple agent, this value is always that agent's\nown snmpEngineID value.\n\nThe value can also take the value of the snmpEngineID\nof a remote SNMP engine with which this user can\ncommunicate.") +usmUserName = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: usmUserName.setDescription("A human readable string representing the name of\nthe user.\n\nThis is the (User-based Security) Model dependent\nsecurity ID.") +# Automatically initialize this column value from index name +class UsmUserSecurityName(MibTableColumn): + def __getUsmUserName(self, name): + __usmUserEntry, = mibBuilder.importSymbols( + 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' + ) + __usmUserEngineID, __usmUserName = __usmUserEntry.getIndicesFromInstId( + name[len(self.name):] + ) + return __usmUserName + def createTest(self, name, val, idx, acInfo): + return MibTableColumn.createTest( + self, name, self.__getUsmUserName(name), idx, acInfo + ) + def createCommit(self, name, val, idx, acInfo): + return MibTableColumn.createCommit( + self, name, self.__getUsmUserName(name), idx, acInfo + ) + def createCleanup(self, name, val, idx, acInfo): + return MibTableColumn.createCleanup( + self, name, self.__getUsmUserName(name), idx, acInfo + ) + def createUndo(self, name, val, idx, acInfo): + return MibTableColumn.createUndo( + 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.") +usmUserCloneFrom = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 4), RowPointer()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserCloneFrom.setDescription("A pointer to another conceptual row in this\nusmUserTable. The user in this other conceptual\nrow is called the clone-from user.\n\nWhen a new user is created (i.e., a new conceptual\nrow is instantiated in this table), the privacy and\nauthentication parameters of the new user must be\ncloned from its clone-from user. These parameters are:\n - authentication protocol (usmUserAuthProtocol)\n - privacy protocol (usmUserPrivProtocol)\nThey will be copied regardless of what the current\nvalue is.\n\nCloning also causes the initial values of the secret\nauthentication key (authKey) and the secret encryption\n\nkey (privKey) of the new user to be set to the same\nvalues as the corresponding secrets of the clone-from\nuser to allow the KeyChange process to occur as\nrequired during user creation.\n\nThe first time an instance of this object is set by\na management operation (either at or after its\ninstantiation), the cloning process is invoked.\nSubsequent writes are successful but invoke no\naction to be taken by the receiver.\nThe cloning process fails with an 'inconsistentName'\nerror if the conceptual row representing the\nclone-from user does not exist or is not in an active\nstate when the cloning process is invoked.\n\nWhen this object is read, the ZeroDotZero OID\nis returned.") +usmUserAuthProtocol = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 5), AutonomousType().clone('1.3.6.1.6.3.10.1.1.1')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserAuthProtocol.setDescription("An indication of whether messages sent on behalf of\nthis user to/from the SNMP engine identified by\nusmUserEngineID, can be authenticated, and if so,\nthe type of authentication protocol which is used.\n\nAn instance of this object is created concurrently\nwith the creation of any other object instance for\nthe same user (i.e., as part of the processing of\nthe set operation which creates the first object\ninstance in the same conceptual row).\n\nIf an initial set operation (i.e. at row creation time)\ntries to set a value for an unknown or unsupported\nprotocol, then a 'wrongValue' error must be returned.\n\nThe value will be overwritten/set when a set operation\nis performed on the corresponding instance of\nusmUserCloneFrom.\n\nOnce instantiated, the value of such an instance of\nthis object can only be changed via a set operation to\nthe value of the usmNoAuthProtocol.\n\nIf a set operation tries to change the value of an\n\nexisting instance of this object to any value other\nthan usmNoAuthProtocol, then an 'inconsistentValue'\nerror must be returned.\n\nIf a set operation tries to set the value to the\nusmNoAuthProtocol while the usmUserPrivProtocol value\nin the same row is not equal to usmNoPrivProtocol,\nthen an 'inconsistentValue' error must be returned.\nThat means that an SNMP command generator application\nmust first ensure that the usmUserPrivProtocol is set\nto the usmNoPrivProtocol value before it can set\nthe usmUserAuthProtocol value to usmNoAuthProtocol.") +usmUserAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 6), KeyChange().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserAuthKeyChange.setDescription("An object, which when modified, causes the secret\nauthentication key used for messages sent on behalf\nof this user to/from the SNMP engine identified by\nusmUserEngineID, to be modified via a one-way\nfunction.\n\nThe associated protocol is the usmUserAuthProtocol.\nThe associated secret key is the user's secret\nauthentication key (authKey). The associated hash\nalgorithm is the algorithm used by the user's\nusmUserAuthProtocol.\n\nWhen creating a new user, it is an 'inconsistentName'\nerror for a set operation to refer to this object\nunless it is previously or concurrently initialized\nthrough a set operation on the corresponding instance\nof usmUserCloneFrom.\n\nWhen the value of the corresponding usmUserAuthProtocol\nis usmNoAuthProtocol, then a set is successful, but\neffectively is a no-op.\n\nWhen this object is read, the zero-length (empty)\nstring is returned.\n\nThe recommended way to do a key change is as follows:\n\n 1) GET(usmUserSpinLock.0) and save in sValue.\n 2) generate the keyChange value based on the old\n (existing) secret key and the new secret key,\n let us call this kcValue.\n\nIf you do the key change on behalf of another user:\n\n 3) SET(usmUserSpinLock.0=sValue,\n usmUserAuthKeyChange=kcValue\n usmUserPublic=randomValue)\n\nIf you do the key change for yourself:\n\n 4) SET(usmUserSpinLock.0=sValue,\n usmUserOwnAuthKeyChange=kcValue\n usmUserPublic=randomValue)\n\nIf you get a response with error-status of noError,\nthen the SET succeeded and the new key is active.\nIf you do not get a response, then you can issue a\nGET(usmUserPublic) and check if the value is equal\nto the randomValue you did send in the SET. If so, then\nthe key change succeeded and the new key is active\n(probably the response got lost). If not, then the SET\nrequest probably never reached the target and so you\ncan start over with the procedure above.") +usmUserOwnAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 7), KeyChange().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserOwnAuthKeyChange.setDescription("Behaves exactly as usmUserAuthKeyChange, with one\nnotable difference: in order for the set operation\nto succeed, the usmUserName of the operation\nrequester must match the usmUserName that\nindexes the row which is targeted by this\noperation.\nIn addition, the USM security model must be\nused for this operation.\n\nThe idea here is that access to this column can be\npublic, since it will only allow a user to change\nhis own secret authentication key (authKey).\nNote that this can only be done once the row is active.\n\nWhen a set is received and the usmUserName of the\nrequester is not the same as the umsUserName that\nindexes the row which is targeted by this operation,\nthen a 'noAccess' error must be returned.\n\nWhen a set is received and the security model in use\nis not USM, then a 'noAccess' error must be returned.") +usmUserPrivProtocol = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 8), AutonomousType().clone('1.3.6.1.6.3.10.1.2.1')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserPrivProtocol.setDescription("An indication of whether messages sent on behalf of\nthis user to/from the SNMP engine identified by\nusmUserEngineID, can be protected from disclosure,\nand if so, the type of privacy protocol which is used.\n\nAn instance of this object is created concurrently\nwith the creation of any other object instance for\nthe same user (i.e., as part of the processing of\nthe set operation which creates the first object\ninstance in the same conceptual row).\n\nIf an initial set operation (i.e. at row creation time)\ntries to set a value for an unknown or unsupported\nprotocol, then a 'wrongValue' error must be returned.\n\nThe value will be overwritten/set when a set operation\nis performed on the corresponding instance of\nusmUserCloneFrom.\n\nOnce instantiated, the value of such an instance of\nthis object can only be changed via a set operation to\nthe value of the usmNoPrivProtocol.\n\nIf a set operation tries to change the value of an\nexisting instance of this object to any value other\nthan usmNoPrivProtocol, then an 'inconsistentValue'\nerror must be returned.\n\nNote that if any privacy protocol is used, then you\nmust also use an authentication protocol. In other\nwords, if usmUserPrivProtocol is set to anything else\nthan usmNoPrivProtocol, then the corresponding instance\nof usmUserAuthProtocol cannot have a value of\n\nusmNoAuthProtocol. If it does, then an\n'inconsistentValue' error must be returned.") +usmUserPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 9), KeyChange().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserPrivKeyChange.setDescription("An object, which when modified, causes the secret\nencryption key used for messages sent on behalf\nof this user to/from the SNMP engine identified by\nusmUserEngineID, to be modified via a one-way\nfunction.\n\nThe associated protocol is the usmUserPrivProtocol.\nThe associated secret key is the user's secret\nprivacy key (privKey). The associated hash\nalgorithm is the algorithm used by the user's\nusmUserAuthProtocol.\n\nWhen creating a new user, it is an 'inconsistentName'\nerror for a set operation to refer to this object\nunless it is previously or concurrently initialized\nthrough a set operation on the corresponding instance\nof usmUserCloneFrom.\n\nWhen the value of the corresponding usmUserPrivProtocol\nis usmNoPrivProtocol, then a set is successful, but\neffectively is a no-op.\n\nWhen this object is read, the zero-length (empty)\nstring is returned.\nSee the description clause of usmUserAuthKeyChange for\na recommended procedure to do a key change.") +usmUserOwnPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 10), KeyChange().clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserOwnPrivKeyChange.setDescription("Behaves exactly as usmUserPrivKeyChange, with one\nnotable difference: in order for the Set operation\nto succeed, the usmUserName of the operation\nrequester must match the usmUserName that indexes\n\nthe row which is targeted by this operation.\nIn addition, the USM security model must be\nused for this operation.\n\nThe idea here is that access to this column can be\npublic, since it will only allow a user to change\nhis own secret privacy key (privKey).\nNote that this can only be done once the row is active.\n\nWhen a set is received and the usmUserName of the\nrequester is not the same as the umsUserName that\nindexes the row which is targeted by this operation,\nthen a 'noAccess' error must be returned.\n\nWhen a set is received and the security model in use\nis not USM, then a 'noAccess' error must be returned.") +usmUserPublic = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserPublic.setDescription("A publicly-readable value which can be written as part\nof the procedure for changing a user's secret\nauthentication and/or privacy key, and later read to\ndetermine whether the change of the secret was\neffected.") +usmUserStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 12), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserStorageType.setDescription("The storage type for this conceptual row.\n\nConceptual rows having the value 'permanent' must\nallow write-access at a minimum to:\n\n- usmUserAuthKeyChange, usmUserOwnAuthKeyChange\n and usmUserPublic for a user who employs\n authentication, and\n- usmUserPrivKeyChange, usmUserOwnPrivKeyChange\n and usmUserPublic for a user who employs\n privacy.\n\nNote that any user who employs authentication or\nprivacy must allow its secret(s) to be updated and\nthus cannot be 'readOnly'.\n\nIf an initial set operation tries to set the value to\n'readOnly' for a user who employs authentication or\nprivacy, then an 'inconsistentValue' error must be\nreturned. Note that if the value has been previously\nset (implicit or explicit) to any value, then the rules\nas defined in the StorageType Textual Convention apply.\n\nIt is an implementation issue to decide if a SET for\na readOnly or permanent row is accepted at all. In some\ncontexts this may make sense, in others it may not. If\na SET for a readOnly or permanent row is not accepted\nat all, then a 'wrongValue' error must be returned.") +usmUserStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 13), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: usmUserStatus.setDescription("The status of this conceptual row.\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the usmUserStatus column\nis 'notReady'.\n\nIn particular, a newly created row for a user who\nemploys authentication, cannot be made active until the\ncorresponding usmUserCloneFrom and usmUserAuthKeyChange\nhave been set.\n\nFurther, a newly created row for a user who also\nemploys privacy, cannot be made active until the\nusmUserPrivKeyChange has been set.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified,\nexcept for usmUserOwnAuthKeyChange and\nusmUserOwnPrivKeyChange. For these 2 objects, the\n\nvalue of usmUserStatus MUST be active.") +usmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2)) +usmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 1)) +usmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 2)) + +# Augmentions + +# Groups + +usmMIBBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 15, 2, 2, 1)).setObjects(*(("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownEngineIDs"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmStatsNotInTimeWindows"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownUserNames"), ("SNMP-USER-BASED-SM-MIB", "usmUserSecurityName"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnsupportedSecLevels"), ("SNMP-USER-BASED-SM-MIB", "usmStatsDecryptionErrors"), ("SNMP-USER-BASED-SM-MIB", "usmUserStatus"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserStorageType"), ("SNMP-USER-BASED-SM-MIB", "usmUserSpinLock"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserCloneFrom"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmStatsWrongDigests"), ("SNMP-USER-BASED-SM-MIB", "usmUserPublic"), ) ) +if mibBuilder.loadTexts: usmMIBBasicGroup.setDescription("A collection of objects providing for configuration\nof an SNMP engine which implements the SNMP\nUser-based Security Model.") + +# Compliances + +usmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 15, 2, 1, 1)).setObjects(*(("SNMP-USER-BASED-SM-MIB", "usmMIBBasicGroup"), ) ) +if mibBuilder.loadTexts: usmMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP-USER-BASED-SM-MIB.") + +# Exports + +# Module identity +mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", PYSNMP_MODULE_ID=snmpUsmMIB) + +# Types +mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", KeyChange=KeyChange) + +# Objects +mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmNoAuthProtocol=usmNoAuthProtocol, usmHMACMD5AuthProtocol=usmHMACMD5AuthProtocol, usmHMACSHAAuthProtocol=usmHMACSHAAuthProtocol, usmNoPrivProtocol=usmNoPrivProtocol, usmDESPrivProtocol=usmDESPrivProtocol, snmpUsmMIB=snmpUsmMIB, usmMIBObjects=usmMIBObjects, usmStats=usmStats, usmStatsUnsupportedSecLevels=usmStatsUnsupportedSecLevels, usmStatsNotInTimeWindows=usmStatsNotInTimeWindows, usmStatsUnknownUserNames=usmStatsUnknownUserNames, usmStatsUnknownEngineIDs=usmStatsUnknownEngineIDs, usmStatsWrongDigests=usmStatsWrongDigests, usmStatsDecryptionErrors=usmStatsDecryptionErrors, usmUser=usmUser, usmUserSpinLock=usmUserSpinLock, usmUserTable=usmUserTable, usmUserEntry=usmUserEntry, usmUserEngineID=usmUserEngineID, usmUserName=usmUserName, usmUserSecurityName=usmUserSecurityName, usmUserCloneFrom=usmUserCloneFrom, usmUserAuthProtocol=usmUserAuthProtocol, usmUserAuthKeyChange=usmUserAuthKeyChange, usmUserOwnAuthKeyChange=usmUserOwnAuthKeyChange, usmUserPrivProtocol=usmUserPrivProtocol, usmUserPrivKeyChange=usmUserPrivKeyChange, usmUserOwnPrivKeyChange=usmUserOwnPrivKeyChange, usmUserPublic=usmUserPublic, usmUserStorageType=usmUserStorageType, usmUserStatus=usmUserStatus, usmMIBConformance=usmMIBConformance, usmMIBCompliances=usmMIBCompliances, usmMIBGroups=usmMIBGroups) + +# Groups +mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmMIBBasicGroup=usmMIBBasicGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmMIBCompliance=usmMIBCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py 2012-04-03 12:50:04.000000000 +0000 @@ -0,0 +1,31 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USM-AES-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:50:04 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( 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") + +# Objects + +usmAesCfb128Protocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 4)) +if mibBuilder.loadTexts: usmAesCfb128Protocol.setDescription("The CFB128-AES-128 Privacy Protocol.") +snmpUsmAesMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 20)).setRevisions(("2004-06-14 00:00",)) +if mibBuilder.loadTexts: snmpUsmAesMIB.setOrganization("IETF") +if mibBuilder.loadTexts: snmpUsmAesMIB.setContactInfo("Uri Blumenthal\nLucent Technologies / Bell Labs\n67 Whippany Rd.\n14D-318\nWhippany, NJ 07981, USA\n973-386-2163\nuri@bell-labs.com\n\nFabio Maino\nAndiamo Systems, Inc.\n375 East Tasman Drive\nSan Jose, CA 95134, USA\n408-853-7530\nfmaino@andiamo.com\n\nKeith McCloghrie\nCisco Systems, Inc.\n170 West Tasman Drive\nSan Jose, CA 95134-1706, USA\n\n408-526-5260\nkzm@cisco.com") +if mibBuilder.loadTexts: snmpUsmAesMIB.setDescription("Definitions of Object Identities needed for\nthe use of AES by SNMP's User-based Security\nModel.\n\nCopyright (C) The Internet Society (2004).\n\nThis version of this MIB module is part of RFC 3826;\nsee the RFC itself for full legal notices.\nSupplementary information may be available on\nhttp://www.ietf.org/copyrights/ianamib.html.") + +# Augmentions + +# Exports + +# Module identity +mibBuilder.exportSymbols("SNMP-USM-AES-MIB", PYSNMP_MODULE_ID=snmpUsmAesMIB) + +# Objects +mibBuilder.exportSymbols("SNMP-USM-AES-MIB", usmAesCfb128Protocol=usmAesCfb128Protocol, snmpUsmAesMIB=snmpUsmAesMIB) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-CONF.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-CONF.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-CONF.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-CONF.py 2011-12-13 15:20:06.000000000 +0000 @@ -0,0 +1,71 @@ + +MibNode, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibNode') + +class ObjectGroup(MibNode): + def getObjects(self): + return getattr(self, 'objects', ()) + def setObjects(self, *args): + self.objects = args + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def asn1Print(self): + return '\ +OBJECT-GROUP\n\ + OBJECTS { %s }\n\ + DESCRIPTION \"%s\"\ +' % (', '.join([ x for x in self.getObjects() ]), self.getDescription()) + +class NotificationGroup(MibNode): + def getObjects(self): + return getattr(self, 'objects', ()) + def setObjects(self, *args): + self.objects = args + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def asn1Print(self): + return '\ +NOTIFICATION-GROUP\n\ + NOTIFICATIONS { %s }\n\ + DESCRIPTION \"%s\"\ +' % (', '.join([ x for x in self.getObjects() ]), self.getDescription()) + +class ModuleCompliance(MibNode): + def getObjects(self): + return getattr(self, 'objects', ()) + def setObjects(self, *args): + self.objects = args + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def asn1Print(self): + return '\ +MODULE-COMPLIANCE\n\ + OBJECT { %s } \n\ + DESCRIPTION \"%s\"\n\ +' % (', '.join([ x for x in self.getObjects() ]), self.getDescription()) + +class AgentCapabilities(MibNode): + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def asn1Print(self): + return '\ +AGENT-CAPABILITIES\n\ + DESCRIPTION \"%s\"\n\ +' % self.getDescription() + +mibBuilder.exportSymbols('SNMPv2-CONF', ObjectGroup=ObjectGroup, NotificationGroup=NotificationGroup, ModuleCompliance=ModuleCompliance, AgentCapabilities=AgentCapabilities) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-MIB.py 2012-04-03 12:55:45.000000000 +0000 @@ -0,0 +1,176 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMPv2-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:55:45 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( ModuleCompliance, NotificationGroup, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") +( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, TimeTicks, mib_2, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "TimeTicks", "mib-2", "snmpModules") +( DisplayString, TestAndIncr, TimeStamp, ) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TestAndIncr", "TimeStamp") + +# Objects + +system = MibIdentifier((1, 3, 6, 1, 2, 1, 1)) +sysDescr = MibScalar((1, 3, 6, 1, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysDescr.setDescription("A textual description of the entity. This value should\ninclude the full name and version identification of\nthe system's hardware type, software operating-system,\nand networking software.") +sysObjectID = MibScalar((1, 3, 6, 1, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysObjectID.setDescription("The vendor's authoritative identification of the\nnetwork management subsystem contained in the entity.\nThis value is allocated within the SMI enterprises\nsubtree (1.3.6.1.4.1) and provides an easy and\nunambiguous means for determining `what kind of box' is\nbeing managed. For example, if vendor `Flintstones,\nInc.' was assigned the subtree 1.3.6.1.4.1.424242,\nit could assign the identifier 1.3.6.1.4.1.424242.1.1\nto its `Fred Router'.") +sysUpTime = MibScalar((1, 3, 6, 1, 2, 1, 1, 3), TimeTicks()).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysUpTime.setDescription("The time (in hundredths of a second) since the\nnetwork management portion of the system was last\nre-initialized.") +sysContact = MibScalar((1, 3, 6, 1, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") +if mibBuilder.loadTexts: sysContact.setDescription("The textual identification of the contact person for\nthis managed node, together with information on how\nto contact this person. If no contact information is\nknown, the value is the zero-length string.") +sysName = MibScalar((1, 3, 6, 1, 2, 1, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") +if mibBuilder.loadTexts: sysName.setDescription("An administratively-assigned name for this managed\nnode. By convention, this is the node's fully-qualified\ndomain name. If the name is unknown, the value is\nthe zero-length string.") +sysLocation = MibScalar((1, 3, 6, 1, 2, 1, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") +if mibBuilder.loadTexts: sysLocation.setDescription("The physical location of this node (e.g., 'telephone\ncloset, 3rd floor'). If the location is unknown, the\nvalue is the zero-length string.") +sysServices = MibScalar((1, 3, 6, 1, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 127))).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysServices.setDescription("A value which indicates the set of services that this\nentity may potentially offer. The value is a sum.\n\nThis sum initially takes the value zero. Then, for\neach layer, L, in the range 1 through 7, that this node\nperforms transactions for, 2 raised to (L - 1) is added\nto the sum. For example, a node which performs only\nrouting functions would have a value of 4 (2^(3-1)).\nIn contrast, a node which is a host offering application\nservices would have a value of 72 (2^(4-1) + 2^(7-1)).\nNote that in the context of the Internet suite of\nprotocols, values should be calculated accordingly:\n\n layer functionality\n 1 physical (e.g., repeaters)\n 2 datalink/subnetwork (e.g., bridges)\n 3 internet (e.g., supports the IP)\n 4 end-to-end (e.g., supports the TCP)\n 7 applications (e.g., supports the SMTP)\n\nFor systems including OSI protocols, layers 5 and 6\nmay also be counted.") +sysORLastChange = MibScalar((1, 3, 6, 1, 2, 1, 1, 8), TimeStamp()).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysORLastChange.setDescription("The value of sysUpTime at the time of the most recent\nchange in state or value of any instance of sysORID.") +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=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.") +sysORDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 3), DisplayString()).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysORDescr.setDescription("A textual description of the capabilities identified\nby the corresponding instance of sysORID.") +sysORUpTime = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 4), TimeStamp()).setMaxAccess("readonly") +if mibBuilder.loadTexts: sysORUpTime.setDescription("The value of sysUpTime at the time this conceptual\nrow was last instantiated.") +snmp = MibIdentifier((1, 3, 6, 1, 2, 1, 11)) +snmpInPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 1), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInPkts.setDescription("The total number of messages delivered to the SNMP\nentity from the transport service.") +snmpOutPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 2), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutPkts.setDescription("The total number of SNMP Messages which were\npassed from the SNMP protocol entity to the\ntransport service.") +snmpInBadVersions = MibScalar((1, 3, 6, 1, 2, 1, 11, 3), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInBadVersions.setDescription("The total number of SNMP messages which were delivered\nto the SNMP entity and were for an unsupported SNMP\nversion.") +snmpInBadCommunityNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 4), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInBadCommunityNames.setDescription("The total number of community-based SNMP messages (for\nexample, SNMPv1) delivered to the SNMP entity which\nused an SNMP community name not known to said entity.\nAlso, implementations which authenticate community-based\nSNMP messages using check(s) in addition to matching\nthe community name (for example, by also checking\nwhether the message originated from a transport address\nallowed to use a specified community name) MAY include\nin this value the number of messages which failed the\nadditional check(s). It is strongly RECOMMENDED that\n\nthe documentation for any security model which is used\nto authenticate community-based SNMP messages specify\nthe precise conditions that contribute to this value.") +snmpInBadCommunityUses = MibScalar((1, 3, 6, 1, 2, 1, 11, 5), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInBadCommunityUses.setDescription("The total number of community-based SNMP messages (for\nexample, SNMPv1) delivered to the SNMP entity which\nrepresented an SNMP operation that was not allowed for\nthe SNMP community named in the message. The precise\nconditions under which this counter is incremented\n(if at all) depend on how the SNMP entity implements\nits access control mechanism and how its applications\ninteract with that access control mechanism. It is\nstrongly RECOMMENDED that the documentation for any\naccess control mechanism which is used to control access\nto and visibility of MIB instrumentation specify the\nprecise conditions that contribute to this value.") +snmpInASNParseErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 6), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInASNParseErrs.setDescription("The total number of ASN.1 or BER errors encountered by\nthe SNMP entity when decoding received SNMP messages.") +snmpInTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 8), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInTooBigs.setDescription("The total number of SNMP PDUs which were\ndelivered to the SNMP protocol entity and for\nwhich the value of the error-status field was\n`tooBig'.") +snmpInNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 9), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInNoSuchNames.setDescription("The total number of SNMP PDUs which were\ndelivered to the SNMP protocol entity and for\nwhich the value of the error-status field was\n`noSuchName'.") +snmpInBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 10), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInBadValues.setDescription("The total number of SNMP PDUs which were\ndelivered to the SNMP protocol entity and for\nwhich the value of the error-status field was\n`badValue'.") +snmpInReadOnlys = MibScalar((1, 3, 6, 1, 2, 1, 11, 11), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInReadOnlys.setDescription("The total number valid SNMP PDUs which were delivered\nto the SNMP protocol entity and for which the value\nof the error-status field was `readOnly'. It should\nbe noted that it is a protocol error to generate an\nSNMP PDU which contains the value `readOnly' in the\nerror-status field, as such this object is provided\nas a means of detecting incorrect implementations of\nthe SNMP.") +snmpInGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 12), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInGenErrs.setDescription("The total number of SNMP PDUs which were delivered\nto the SNMP protocol entity and for which the value\nof the error-status field was `genErr'.") +snmpInTotalReqVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 13), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInTotalReqVars.setDescription("The total number of MIB objects which have been\nretrieved successfully by the SNMP protocol entity\nas the result of receiving valid SNMP Get-Request\nand Get-Next PDUs.") +snmpInTotalSetVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 14), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInTotalSetVars.setDescription("The total number of MIB objects which have been\naltered successfully by the SNMP protocol entity as\nthe result of receiving valid SNMP Set-Request PDUs.") +snmpInGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 15), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInGetRequests.setDescription("The total number of SNMP Get-Request PDUs which\nhave been accepted and processed by the SNMP\nprotocol entity.") +snmpInGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 16), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInGetNexts.setDescription("The total number of SNMP Get-Next PDUs which have been\naccepted and processed by the SNMP protocol entity.") +snmpInSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 17), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInSetRequests.setDescription("The total number of SNMP Set-Request PDUs which\nhave been accepted and processed by the SNMP protocol\nentity.") +snmpInGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 18), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInGetResponses.setDescription("The total number of SNMP Get-Response PDUs which\nhave been accepted and processed by the SNMP protocol\nentity.") +snmpInTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 19), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpInTraps.setDescription("The total number of SNMP Trap PDUs which have been\naccepted and processed by the SNMP protocol entity.") +snmpOutTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 20), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutTooBigs.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status field was `tooBig.'") +snmpOutNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 21), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutNoSuchNames.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status was `noSuchName'.") +snmpOutBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 22), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutBadValues.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status field was `badValue'.") +snmpOutGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 24), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutGenErrs.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status field was `genErr'.") +snmpOutGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 25), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutGetRequests.setDescription("The total number of SNMP Get-Request PDUs which\nhave been generated by the SNMP protocol entity.") +snmpOutGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 26), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutGetNexts.setDescription("The total number of SNMP Get-Next PDUs which have\nbeen generated by the SNMP protocol entity.") +snmpOutSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 27), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutSetRequests.setDescription("The total number of SNMP Set-Request PDUs which\nhave been generated by the SNMP protocol entity.") +snmpOutGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 28), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutGetResponses.setDescription("The total number of SNMP Get-Response PDUs which\nhave been generated by the SNMP protocol entity.") +snmpOutTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 29), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpOutTraps.setDescription("The total number of SNMP Trap PDUs which have\nbeen generated by the SNMP protocol entity.") +snmpEnableAuthenTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 30), Integer().subtype(subtypeSpec=SingleValueConstraint(2,1,)).subtype(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ))).setMaxAccess("readwrite") +if mibBuilder.loadTexts: snmpEnableAuthenTraps.setDescription("Indicates whether the SNMP entity is permitted to\ngenerate authenticationFailure traps. The value of this\nobject overrides any configuration information; as such,\nit provides a means whereby all authenticationFailure\ntraps may be disabled.\n\nNote that it is strongly recommended that this object\nbe stored in non-volatile memory so that it remains\nconstant across re-initializations of the network\nmanagement system.") +snmpSilentDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 31), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpSilentDrops.setDescription("The total number of Confirmed Class PDUs (such as\nGetRequest-PDUs, GetNextRequest-PDUs,\nGetBulkRequest-PDUs, SetRequest-PDUs, and\nInformRequest-PDUs) delivered to the SNMP entity which\nwere silently dropped because the size of a reply\ncontaining an alternate Response Class PDU (such as a\nResponse-PDU) with an empty variable-bindings field\nwas greater than either a local constraint or the\nmaximum message size associated with the originator of\nthe request.") +snmpProxyDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 32), Counter32()).setMaxAccess("readonly") +if mibBuilder.loadTexts: snmpProxyDrops.setDescription("The total number of Confirmed Class PDUs\n(such as GetRequest-PDUs, GetNextRequest-PDUs,\nGetBulkRequest-PDUs, SetRequest-PDUs, and\nInformRequest-PDUs) delivered to the SNMP entity which\nwere silently dropped because the transmission of\nthe (possibly translated) message to a proxy target\nfailed in a manner (other than a time-out) such that\nno Response Class PDU (such as a Response-PDU) could\nbe returned.") +snmpMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 1)).setRevisions(("2002-10-16 00:00","1995-11-09 00:00","1993-04-01 00:00",)) +if mibBuilder.loadTexts: snmpMIB.setOrganization("IETF SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpMIB.setContactInfo("WG-EMail: snmpv3@lists.tislabs.com\nSubscribe: snmpv3-request@lists.tislabs.com\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\nCo-Chair: David Harrington\n Enterasys Networks\npostal: 35 Industrial Way\n P. O. Box 5005\n Rochester, NH 03866-5005\n USA\nEMail: dbh@enterasys.com\nphone: +1 603 337-2614\n\nEditor: Randy Presuhn\n BMC Software, Inc.\npostal: 2141 North First Street\n San Jose, CA 95131\n USA\nEMail: randy_presuhn@bmc.com\nphone: +1 408 546-1006") +if mibBuilder.loadTexts: snmpMIB.setDescription("The MIB module for SNMP entities.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3418;\nsee the RFC itself for full legal notices.") +snmpMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1)) +snmpTrap = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 4)) +snmpTrapOID = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 1), ObjectIdentifier()).setMaxAccess("notifyonly") +if mibBuilder.loadTexts: snmpTrapOID.setDescription("The authoritative identification of the notification\ncurrently being sent. This variable occurs as\nthe second varbind in every SNMPv2-Trap-PDU and\nInformRequest-PDU.") +snmpTrapEnterprise = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 3), ObjectIdentifier()).setMaxAccess("notifyonly") +if mibBuilder.loadTexts: snmpTrapEnterprise.setDescription("The authoritative identification of the enterprise\nassociated with the trap currently being sent. When an\nSNMP proxy agent is mapping an RFC1157 Trap-PDU\ninto a SNMPv2-Trap-PDU, this variable occurs as the\nlast varbind.") +snmpTraps = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5)) +snmpSet = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 6)) +snmpSetSerialNo = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 6, 1), TestAndIncr()).setMaxAccess("readwrite") +if mibBuilder.loadTexts: snmpSetSerialNo.setDescription("An advisory lock used to allow several cooperating\ncommand generator applications to coordinate their\nuse of the SNMP set operation.\n\nThis object is used for coarse-grain coordination.\nTo achieve fine-grain coordination, one or more similar\nobjects might be defined within each MIB group, as\nappropriate.") +snmpMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2)) +snmpMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 1)) +snmpMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 2)) + +# Augmentions + +# Notifications + +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 + +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"), ) ) +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 + +# Module identity +mibBuilder.exportSymbols("SNMPv2-MIB", PYSNMP_MODULE_ID=snmpMIB) + +# Objects +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", coldStart=coldStart, warmStart=warmStart, authenticationFailure=authenticationFailure) + +# Groups +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 -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-SMI.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-SMI.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-SMI.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-SMI.py 2012-04-13 19:04:43.000000000 +0000 @@ -0,0 +1,1080 @@ +from pysnmp.smi.indices import OidOrderedDict +from pysnmp.smi import exval, error +from pysnmp.proto import rfc1902 +from pysnmp import cache, debug +from pyasn1.error import PyAsn1Error + +( Integer, ObjectIdentifier ) = mibBuilder.importSymbols( + "ASN1", "Integer", "ObjectIdentifier" + ) +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, + ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols( + "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", + "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" + ) +# syntax of objects + +OctetString = rfc1902.OctetString +Bits = rfc1902.Bits +Integer32 = rfc1902.Integer32 +IpAddress = rfc1902.IpAddress +Counter32 = rfc1902.Counter32 +Gauge32 = rfc1902.Gauge32 +Unsigned32 = rfc1902.Unsigned32 +TimeTicks = rfc1902.TimeTicks +Opaque = rfc1902.Opaque +Counter64 = rfc1902.Counter64 + +class ExtUTCTime(OctetString): + subtypeSpec = OctetString.subtypeSpec+ConstraintsUnion(ValueSizeConstraint(11,11), ValueSizeConstraint(13,13)) + +# MIB tree foundation class + +class MibNode: + label = '' + def __init__(self, name): + self.name = name + + def __repr__(self): + return '%s(%r)' % (self.__class__.__name__, self.name) + + def getName(self): return self.name + + def getLabel(self): return self.label + def setLabel(self, label): + self.label = label + return self + + def clone(self, name=None): + myClone = self.__class__(self.name) + if name is not None: + myClone.name = name + if self.label is not None: + myClone.label = self.label + return myClone + +# definitions for information modules + +class ModuleIdentity(MibNode): + def getLastUpdated(self): + return getattr(self, 'lastUpdated', '') + def setLastUpdated(self, v): + self.lastUpdated = v + return self + def getOrganization(self): + return getattr(self, 'organization', '') + def setOrganization(self, v): + self.organization = v + return self + def getContactInfo(self): + return getattr(self, 'contactInfo', '') + def setContactInfo(self, v): + self.contactInfo = v + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def getRevisions(self): + return getattr(self, 'revisions', ()) + def setRevisions(self, args): + self.revisions = args + return self + + def asn1Print(self): + return '\ +MODULE-IDENTITY\n\ + LAST-UPDATED %s\n\ + ORGANIZATION \"%s\"\n\ + CONTACT-INFO \"%s\"\n\ + DESCRIPTION \"%s\"\n\ + %s\ +' % (self.getLastUpdated(), + self.getOrganization(), + self.getContactInfo(), + self.getDescription(), + ''.join([ "REVISION \"%s\"\n" % x for x in self.getRevisions() ])) + +class ObjectIdentity(MibNode): + def getStatus(self): + return getattr(self, 'status', 'current') + def setStatus(self, v): + self.status = v + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def getReference(self): + return getattr(self, 'reference', '') + def setReference(self, v): + self.reference = v + return self + + def asn1Print(self): + return '\ +OBJECT-IDENTITY\n\ + STATUS %s\n\ + DESCRIPTION \"%s\"\n\ + REFERENCE \"%s\"\ +' % (self.getStatus(), + self.getDescription(), + self.getReference()) + +# definition for objects + +class NotificationType(MibNode): + def getObjects(self): + return getattr(self, 'objects', ()) + def setObjects(self, *args): + self.objects = args + return self + def getStatus(self): + return getattr(self, 'status', 'current') + def setStatus(self, v): + self.status = v + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def getRevisions(self): + return getattr(self, 'revisions', ()) + def setRevisions(self, args): + self.revisions = args + return self + + def asn1Print(self): + return '\ +NOTIFICATION-TYPE\n\ + OBJECTS { %s }\n\ + STATUS %s\n\ + DESCRIPTION \"%s\"\n\ + %s\ +' % (', '.join([ x for x in self.getObjects() ]), + self.getStatus(), + self.getDescription(), + ''.join([ "REVISION \"%s\"\n" % x for x in self.getRevisions() ])) + +class MibIdentifier(MibNode): + def asn1Print(self): + return 'OBJECT IDENTIFIER' + +class ObjectType(MibNode): + maxAccess = None + def __init__(self, name, syntax=None): + MibNode.__init__(self, name) + self.syntax = syntax + + # XXX + 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(%r, %r)' % ( + self.__class__.__name__, self.name, self.syntax + ) + def getSyntax(self): + return self.syntax + def getUnits(self): + return getattr(self, 'units', '') + def setUnits(self, v): + self.units = v + return self + def getMaxAccess(self): + return getattr(self, 'maxAccess', 'not-accessible') + def setMaxAccess(self, v): + self.maxAccess = v + return self + def getStatus(self): + return getattr(self, 'status', 'current') + def setStatus(self, v): + self.status = v + return self + def getDescription(self): + return getattr(self, 'description', '') + def setDescription(self, v): + self.description = v + return self + def getReference(self): + return getattr(self, 'reference', '') + def setReference(self, v): + self.reference = v + return self + + def asn1Print(self): + return '\ +OBJECT-TYPE\n\ + SYNTAX %s\n\ + UNITS \"%s\"\n\ + MAX-ACCESS %s\n\ + STATUS %s\n\ + DESCRIPTION \"%s\"\n\ + REFERENCE \"%s\"\ +' % (self.getSyntax().__class__.__name__, + self.getUnits(), + self.getMaxAccess(), + self.getStatus(), + self.getDescription(), + self.getReference()) + +class MibTree(ObjectType): + branchVersionId = 0 # increments on tree structure change XXX + maxAccess = 'not-accessible' + def __init__(self, name, syntax=None): + ObjectType.__init__(self, name, syntax) + self._vars = OidOrderedDict() + + # Subtrees registration + + def registerSubtrees(self, *subTrees): + """Register subtrees at this tree. Subtrees are always attached + at the level of this tree, not subtrees.""" + for subTree in subTrees: + if subTree.name in self._vars: + raise error.SmiError( + 'MIB subtree %s already registered at %s' % (subTree.name, self) + ) + self._vars[subTree.name] = subTree + MibTree.branchVersionId = MibTree.branchVersionId + 1 + + def unregisterSubtrees(self, *names): + """Detach subtrees from this tree""" + for name in names: + # This may fail if you fill a table by exporting MibScalarInstances + # but later drop them through SNMP. + if name not in self._vars: + raise error.SmiError( + 'MIB subtree %s not registered at %s' % (name, self) + ) + del self._vars[name] + MibTree.branchVersionId = MibTree.branchVersionId + 1 + + # Tree traversal + + def getBranch(self, name, idx): + """Return a branch of this tree where the 'name' OID may reside""" + for keyLen in self._vars.getKeysLens(): + subName = name[:keyLen] + if subName in self._vars: + return self._vars[subName] + + raise error.NoSuchObjectError(name=name, idx=idx) + + def getNode(self, name, idx=None): + """Return tree node found by name""" + if name == self.name: + return self + else: + return self.getBranch(name, idx).getNode(name, idx) + + def getNextNode(self, name, idx=None): + """Return tree node next to name""" + try: + nextNode = self.getBranch(name, idx) + except error.NoSuchObjectError: + # Start from the beginning + 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: + return self._vars[self._vars.nextKey(name)] + except KeyError: + raise error.NoSuchObjectError(idx=idx, name=name) + else: + try: + return nextNode.getNextNode(name, idx) + except error.NoSuchObjectError: + try: + return self._vars[self._vars.nextKey(nextNode.name)] + except KeyError: + raise error.NoSuchObjectError(idx=idx, name=name) + + # MIB instrumentation + + # Read operation + + def readTest(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + if name == self.name: + if acFun: + if self.maxAccess not in ( + 'readonly', 'readwrite','readcreate' + ) or acFun(name, self.syntax, idx, 'read', acCtx): + raise error.NoAccessError(idx=idx, name=name) + else: + try: + node = self.getBranch(name, idx) + except error.NoSuchObjectError: + return # missing object is not an error here + + node.readTest(name, val, idx, (acFun, acCtx)) + + def readGet(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + try: + node = self.getBranch(name, idx) + except error.NoSuchObjectError: + return name, exval.noSuchInstance + else: + return node.readGet(name, val, idx, (acFun, acCtx)) + + # Read next operation is subtree-specific + + def readTestNext(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + nextName = name + while 1: # XXX linear search here + try: + nextName = self.getNextNode(nextName, idx).name + except error.NoSuchObjectError: + return # missing object is not an error here + try: + return self.readTest(nextName, val, idx, (acFun, acCtx)) + except error.NoAccessError: + continue + + def readGetNext(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + nextName = name + while 1: + try: + nextName = self.getNextNode(nextName, idx).name + except error.NoSuchObjectError: + return name, exval.endOfMib + try: + self.readTest(nextName, val, idx, (acFun, acCtx)) # XXX + except error.NoAccessError: + continue + else: + return self.readGet(nextName, val, idx, (acFun, acCtx)) + + # Write operation + + def writeTest(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + if name == self.name: + # Make sure variable is writable + if acFun: + if self.maxAccess not in ('readwrite', 'readcreate') or \ + acFun(name, self.syntax, idx, 'write', acCtx): + raise error.NotWritableError(idx=idx, name=name) + else: + node = self.getBranch(name, idx) + node.writeTest(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, acInfo): + (acFun, acCtx) = acInfo + self.getBranch(name, idx).writeCleanup(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): + """Scalar MIB variable. Implements access control checking.""" + maxAccess = 'readonly' + + # MIB instrumentation methods + + # Read operation + + def readTest(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + if name == self.name: + raise error.NoAccessError(idx=idx, name=name) + else: + MibTree.readTest(self, name, val, idx, (acFun, acCtx)) + # If instance exists, check permissions + if acFun: + if self.maxAccess not in ( + 'readonly', 'readwrite', 'readcreate' + ) or acFun(name, self.syntax, idx, 'read', acCtx): + raise error.NoAccessError(idx=idx, name=name) + + # Two-phase commit implementation + + def writeTest(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + if name == self.name: + raise error.NoAccessError(idx=idx, name=name) + else: + MibTree.writeTest(self, name, val, idx, (acFun, acCtx)) + # If instance exists, check permissions + if acFun: + if self.maxAccess not in ('readwrite', 'readcreate') or \ + acFun(name, self.syntax, idx, 'write', acCtx): + raise error.NotWritableError(idx=idx, name=name) + +class MibScalarInstance(MibTree): + """Scalar MIB variable instance. Implements read/write operations.""" + def __init__(self, typeName, instId, syntax): + MibTree.__init__(self, typeName+instId, syntax) + self.typeName = typeName + self.instId = instId + self.__oldSyntax = None + + def getNode(self, name, idx=None): + # Recursion terminator + if name == self.name: + return self + raise error.NoSuchInstanceError(idx=idx, name=name) + + def getNextNode(self, name, idx=None): + raise error.NoSuchInstanceError(idx=idx, name=name) + + # MIB instrumentation methods + + # Read operation + + def readTest(self, name, val, idx, acInfo): + if name != self.name: + raise error.NoSuchObjectError(idx=idx, name=name) + + 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: + debug.logger & debug.flagIns and debug.logger('readGet: %s=%r' % (self.name, self.syntax)) + return self.name, self.syntax.clone() + else: + raise error.NoSuchObjectError(idx=idx, name=name) + + # Write operation: two-phase commit + + def writeTest(self, name, val, idx, acInfo): + # Make sure write's allowed + if name == self.name: + if hasattr(self.syntax, 'smiWrite'): + self.__newSyntax = self.syntax.smiWrite(name, val, idx) + else: + self.__newSyntax = self.syntax.clone(val) + if hasattr(self.__newSyntax, 'smiRaisePendingError'): + self.__newSyntax.smiRaisePendingError() + else: + raise error.NoSuchObjectError(idx=idx, name=name) + + 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, acInfo): + debug.logger & debug.flagIns and debug.logger('writeCleanup: %s=%r' % (name, val)) + # Drop previous value + self.__newSyntax = self.__oldSyntax = None + + def writeUndo(self, name, val, idx, acInfo): + # Revive previous value + self.syntax = self.__oldSyntax + self.__newSyntax = self.__oldSyntax = None + + # Table column instance specifics + + # Create operation + + def createTest(self, name, val, idx, acInfo): + if name == self.name: + if hasattr(self.syntax, 'smiCreate'): + self.__newSyntax = self.syntax.smiCreate(name, val, idx) + else: + self.__newSyntax = self.syntax.clone(val) + else: + raise error.NoSuchObjectError(idx=idx, name=name) + 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, acInfo): + (acFun, acCtx) = acInfo + debug.logger & debug.flagIns and debug.logger('createCleanup: %s=%r' % (name, val)) + if val is not None: + self.writeCleanup(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, acInfo): + if name == self.name: + if hasattr(self.syntax, 'smiDestroy'): + self.__newSyntax = self.syntax.smiDestoy(name, val) + else: + self.__newSyntax = self.syntax.clone(val) + else: + raise error.NoSuchObjectError(idx=idx, name=name) + 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 + +class MibTableColumn(MibScalar): + """MIB table column. Manages a set of column instance variables""" + protoInstance = MibScalarInstance + def __init__(self, name, syntax): + MibScalar.__init__(self, name, syntax) + self.__createdInstances = {}; self.__destroyedInstances = {} + self.__rowOpWanted = {} + self.__valIdx = {} # column instance value to OID index + self.__valIdxId = -1 + + # No branches here, terminal OIDs only + def getBranch(self, name, idx): + if name in self._vars: + return self._vars[name] + raise error.NoSuchObjectError(name=name, idx=idx) + + def getNode(self, name, idx=None): + try: + return MibScalar.getNode(self, name, idx=None) + except error.NoSuchObjectError: + raise error.NoSuchInstanceError(idx=idx, name=name) + + def getNextNode(self, name, idx=None): + try: + return MibScalar.getNextNode(self, name, idx=None) + except error.NoSuchObjectError: + raise error.NoSuchInstanceError(idx=idx, name=name) + + def setProtoInstance(self, protoInstance): + self.protoInstance = protoInstance + + # Value to instances map + + def getNextNodeWithValue(self, name, value): + if not self.__valIdx or self.__valIdxId != self.branchVersionId: + # Build a value->oid index + node = self + while 1: + try: + node = self.getNextNode(node.name) + except error.NoSuchInstanceError: + break + if node.syntax not in self.__valIdx: + self.__valIdx[node.syntax] = OidOrderedDict() + self.__valIdx[node.syntax][node.name] = 1 + + debug.logger & debug.flagIns and debug.logger('value index rebuilt at %s, %s entries' % (self.name,len(self.__valIdx))) + + # Sync to tree version + self.__valIdxId = self.branchVersionId + + if value in self.__valIdx: + try: + return self.getNode( + self.__valIdx[value].nextKey(name) + ) + except KeyError: + raise error.NoSuchInstanceError(name=name) + else: + raise error.NoSuchInstanceError(name=name) + + # Column creation (this should probably be converted into some state + # 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, acInfo): + (acFun, acCtx) = acInfo + # Make sure creation allowed, create a new column instance but + # do not replace the old one + if name == self.name: + raise error.NoAccessError(idx=idx, name=name) + if acFun: + if val is not None and self.maxAccess != 'readcreate' or \ + acFun(name, self.syntax, idx, 'write', acCtx): + debug.logger & debug.flagACL and debug.logger('createTest: %s=%r %s at %s' % (name, val, self.maxAccess, self.name)) + raise error.NoCreationError(idx=idx, name=name) + # Create instances if either it does not yet exist (row creation) + # or a value is passed (multiple OIDs in SET PDU) + if val is None and name in self.__createdInstances: + return + self.__createdInstances[name] = self.protoInstance( + self.name, name[len(self.name):], self.syntax.clone() + ) + self.__createdInstances[name].createTest( + 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: + self._vars[name].createCommit(name, val, idx, (acFun, acCtx)) + return + self.__createdInstances[name].createCommit( + name, val, idx, (acFun, acCtx) + ) + # ...commit new column instance + self._vars[name], self.__createdInstances[name] = \ + self.__createdInstances[name], self._vars.get(name) + + def createCleanup(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + # Drop by-value index + self.__valIdx.clear() + + # Drop previous column instance + if name in self.__createdInstances: + if self.__createdInstances[name] is not None: + self.__createdInstances[name].createCleanup( + name, val, idx, (acFun, acCtx) + ) + del self.__createdInstances[name] + elif name in self._vars: + self._vars[name].createCleanup(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] + del self.__createdInstances[name] + # Remove new instance on rollback + if self._vars[name] is None: + del self._vars[name] + else: + # Catch half-created instances (hackerish) + try: + self._vars[name] == 0 + except PyAsn1Error: + del self._vars[name] + else: + self._vars[name].createUndo(name, val, idx, (acFun, acCtx)) + + # Column destruction + + 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) + if name not in self._vars: + return + if acFun: + if val is not None and self.maxAccess != 'readcreate' or \ + acFun(name, self.syntax, idx, 'write', acCtx): + raise error.NoAccessError(idx=idx, name=name) + self._vars[name].destroyTest( + 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( + name, val, idx, (acFun, acCtx) + ) + self.__destroyedInstances[name] = self._vars[name] + del self._vars[name] + + def destroyCleanup(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + # Drop by-value index + self.__valIdx.clear() + + # Drop instance copy + if name in self.__destroyedInstances: + self.__destroyedInstances[name].destroyCleanup( + name, val, idx, (acFun, acCtx) + ) + debug.logger & debug.flagIns and debug.logger('destroyCleanup: %s=%r' % (name, val)) + del self.__destroyedInstances[name] + + 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] + self._vars[name].destroyUndo( + name, val, idx, (acFun, acCtx) + ) + del self.__destroyedInstances[name] + + # Set/modify column + + def writeTest(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + # Besides common checks, request row creation on no-instance + try: + # First try the instance + MibScalar.writeTest( + self, name, val, idx, (acFun, acCtx) + ) + # ...otherwise proceed with creating new column + except (error.NoSuchObjectError, error.RowCreationWanted): + self.__rowOpWanted[name] = error.RowCreationWanted() + self.createTest(name, val, idx, (acFun, acCtx)) + except error.RowDestructionWanted: + self.__rowOpWanted[name] = error.RowDestructionWanted() + self.destroyTest(name, val, idx, (acFun, acCtx)) + if name in self.__rowOpWanted: + debug.logger & debug.flagIns and debug.logger('%s flagged by %s=%r' % (self.__rowOpWanted[name], name, val)) + raise self.__rowOpWanted[name] + + 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) + ) + return + if isinstance(self.__rowOpWanted[name], error.RowCreationWanted): + getattr(self, 'create'+subAction)( + name, val, idx, (acFun, acCtx) + ) + if isinstance(self.__rowOpWanted[name], error.RowDestructionWanted): + getattr(self, 'destroy'+subAction)( + 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, acInfo): + (acFun, acCtx) = acInfo + # Drop by-value index + self.__valIdx.clear() + + self.__delegateWrite( + 'Cleanup', name, val, idx, (acFun, acCtx) + ) + if name in self.__rowOpWanted: + e = self.__rowOpWanted[name] + del self.__rowOpWanted[name] + debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%r' % (e, name, val)) + raise e + + def writeUndo(self, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + self.__delegateWrite( + 'Undo', name, val, idx, (acFun, acCtx) + ) + if name in self.__rowOpWanted: + e = self.__rowOpWanted[name] + del self.__rowOpWanted[name] + debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%r' % (e, name, val)) + raise e + +class MibTableRow(MibTree): + """MIB table row (SMI 'Entry'). Manages a set of table columns. + Implements row creation/destruction. + """ + def __init__(self, name): + MibTree.__init__(self, name) + self.__idToIdxCache = cache.Cache() + self.__idxToIdCache = cache.Cache() + self.indexNames = () + self.augmentingRows = {} + + # Table indices resolution. Handle almost all possible rfc1902 types + # explicitly rather than by means of isSuperTypeOf() method because + # some subtypes may be implicitly tagged what renders base tag + # unavailable. + + __intBaseTag = Integer.tagSet.getBaseTag() + __strBaseTag = OctetString.tagSet.getBaseTag() + __oidBaseTag = ObjectIdentifier.tagSet.getBaseTag() + __ipaddrTagSet = IpAddress.tagSet + __bitsBaseTag = Bits.tagSet.getBaseTag() + + def setFromName(self, obj, value, impliedFlag=None): + if not value: + raise error.SmiError('Short OID for index %r' % (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('.'.join([str(x) for x in value[:4]])), value[4:] + elif baseTag == self.__strBaseTag: + # rfc1902, 7.7 + if impliedFlag: + return obj.clone(value), () + elif obj.isFixedLength(): + l = obj.getFixedLength() + return obj.clone(value[:l]), value[l:] + else: + return obj.clone(value[1:value[0]+1]), value[value[0]+1:] + elif baseTag == self.__oidBaseTag: + if impliedFlag: + return obj.clone(value), () + else: + return obj.clone(value[1:value[0]+1]), value[value[0]+1:] + # rfc2578, 7.1 + elif baseTag == self.__bitsBaseTag: + return obj.clone(value[1:value[0]+1]), value[value[0]+1:] + else: + raise error.SmiError('Unknown value type for index %r' % (obj,)) + + def getAsName(self, obj, impliedFlag=None): + baseTag = obj.getTagSet().getBaseTag() + if baseTag == self.__intBaseTag: + return (int(obj),) + elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()): + return obj.asNumbers() + elif baseTag == self.__strBaseTag: + if impliedFlag or obj.isFixedLength(): + initial = () + else: + initial = (len(obj),) + return initial + obj.asNumbers() + elif baseTag == self.__oidBaseTag: + if impliedFlag: + return tuple(obj) + else: + return (len(self.name),) + tuple(obj) + # rfc2578, 7.1 + elif baseTag == self.__bitsBaseTag: + return ( len(obj), ) + obj.asNumbers() + else: + raise error.SmiError('Unknown value type for index %r' % (obj,)) + + # Fate sharing mechanics + + def announceManagementEvent(self, action, name, val, idx, acInfo): + (acFun, acCtx) = acInfo + # Convert OID suffix into index vals + instId = name[len(self.name)+1:] + baseIndices = [] + for impliedFlag, modName, symName in self.indexNames: + mibObj, = mibBuilder.importSymbols(modName, symName) + syntax, instId = self.setFromName( + mibObj.syntax, instId, impliedFlag + ) + if self.name == mibObj.name[:-1]: + baseIndices.append((mibObj.name, syntax)) + if instId: + raise error.SmiError( + 'Excessive instance identifier sub-OIDs left at %s: %s' % + (self, instId) + ) + if not baseIndices: + return + for modName, mibSym in self.augmentingRows.keys(): + mibObj, = mibBuilder.importSymbols(modName, mibSym) + debug.logger & debug.flagIns and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) + mibObj.receiveManagementEvent( + 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 + for impliedFlag, modName, symName in self.indexNames: + mibObj, = mibBuilder.importSymbols(modName, symName) + for name, syntax in baseIndices: + if name == mibObj.name: + newSuffix = newSuffix + self.getAsName(syntax, impliedFlag) + if newSuffix: + debug.logger & debug.flagIns and debug.logger('receiveManagementEvent %s for suffix %s' % (action, newSuffix)) + self.__manageColumns(action, (), newSuffix, val, idx, + (acFun, acCtx)) + + def registerAugmentions(self, *names): + for modName, symName in names: + if (modName, symName) in self.augmentingRows: + raise error.SmiError( + 'Row %s already augmented by %s::%s' % \ + (self.name, modName, symName) + ) + self.augmentingRows[(modName, symName)] = 1 + return self + + def setIndexNames(self, *names): + for name in names: + self.indexNames = self.indexNames + (name,) + return self + + def getIndexNames(self): + return self.indexNames + + def __manageColumns(self, action, excludeName, nameSuffix, + 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: + mibObj, = mibBuilder.importSymbols(modName, symName) + syntax, instId = self.setFromName( + mibObj.syntax, instId, impliedFlag + ) + indexVals[mibObj.name] = syntax + for name, var in self._vars.items(): + if name == excludeName: + continue + if name in indexVals: + getattr(var, action)(name + nameSuffix, indexVals[name], idx, + (None, None)) + else: + getattr(var, action)(name + nameSuffix, val, idx, + (acFun, acCtx)) + debug.logger & debug.flagIns and debug.logger('__manageColumns: action %s name %s suffix %s %svalue %r' % (action, name, nameSuffix, name in indexVals and "index " or "", indexVals.get(name, val))) + + 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: + self.__manageColumns( + 'create'+subAction, name[:len(self.name)+1], + name[len(self.name)+1:], None, idx, (acFun, acCtx) + ) + self.announceManagementEvent( + 'create'+subAction, name, None, idx, (acFun, acCtx) + ) + except error.RowDestructionWanted: + self.__manageColumns( + 'destroy'+subAction, name[:len(self.name)+1], + name[len(self.name)+1:], None, idx, (acFun, acCtx) + ) + self.announceManagementEvent( + 'destroy'+subAction, name, None, 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 + + # Table row access by instance name + + def getInstName(self, colId, instId): + return self.name + (colId,) + instId + + # Table index management + + def getIndicesFromInstId(self, instId): + """Return index values for instance identification""" + if instId in self.__idToIdxCache: + return self.__idToIdxCache[instId] + indices = [] + for impliedFlag, modName, symName in self.indexNames: + mibObj, = mibBuilder.importSymbols(modName, symName) + syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag) + indices.append(syntax) # to avoid cyclic refs + if instId: + raise error.SmiError( + 'Excessive instance identifier sub-OIDs left at %s: %s' % + (self, instId) + ) + indices = tuple(indices) + self.__idToIdxCache[instId] = indices + return indices + + def getInstIdFromIndices(self, *indices): + """Return column instance identification from indices""" + if indices in self.__idxToIdCache: + return self.__idxToIdCache[indices] + idx = 0; idxLen = len(indices); instId = () + for impliedFlag, modName, symName in self.indexNames: + mibObj, = mibBuilder.importSymbols(modName, symName) + if idx < idxLen: + instId = instId + self.getAsName( + mibObj.syntax.clone(indices[idx]), impliedFlag + ) + else: + break + idx = idx + 1 + self.__idxToIdCache[indices] = instId + return instId + + # Table access by index + + def getInstNameByIndex(self, colId, *indices): + """Build column instance name from components""" + 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( + self.getInstNameByIndex(*(columnName[-1],) + indices) + ) + + return tuple(instNames) + +class MibTable(MibTree): + """MIB table. Manages a set of TableRow's""" + def __init__(self, name): + MibTree.__init__(self, name) + +zeroDotZero = ObjectIdentity((0,0)) + +#dot = MibTree() +iso = MibTree((1,)) +org = MibIdentifier(iso.name + (3,)) +dod = MibIdentifier(org.name + (6,)) +internet = MibIdentifier(dod.name + (1,)) +directory = MibIdentifier(internet.name + (1,)) +mgmt = MibIdentifier(internet.name + (2,)) +mib_2 = MibIdentifier(mgmt.name + (1,)).setLabel('mib-2') +transmission = MibIdentifier(mib_2.name + (10,)) +experimental = MibIdentifier(internet.name + (3,)) +private = MibIdentifier(internet.name + (4,)) +enterprises = MibIdentifier(private.name + (1,)) +security = MibIdentifier(internet.name + (5,)) +snmpV2 = MibIdentifier(internet.name + (6,)) + +snmpDomains = MibIdentifier(snmpV2.name + (1,)) +snmpProxys = MibIdentifier(snmpV2.name +(2,)) +snmpModules = MibIdentifier(snmpV2.name +(3,)) + +mibBuilder.exportSymbols( + 'SNMPv2-SMI', MibNode=MibNode, + Integer32=Integer32, Bits=Bits, IpAddress=IpAddress, + Counter32=Counter32, Gauge32=Gauge32, Unsigned32=Unsigned32, + TimeTicks=TimeTicks, Opaque=Opaque, Counter64=Counter64, + ExtUTCTime=ExtUTCTime, + ModuleIdentity=ModuleIdentity, ObjectIdentity=ObjectIdentity, + NotificationType=NotificationType, MibScalar=MibScalar, + MibScalarInstance=MibScalarInstance, + MibIdentifier=MibIdentifier, MibTree=MibTree, + MibTableColumn=MibTableColumn, MibTableRow=MibTableRow, + MibTable=MibTable, zeroDotZero=zeroDotZero, + iso=iso, org=org, dod=dod, internet=internet, + directory=directory, mgmt=mgmt, mib_2=mib_2, transmission=transmission, + experimental=experimental, private=private, enterprises=enterprises, + security=security, snmpV2=snmpV2, snmpDomains=snmpDomains, + snmpProxys=snmpProxys, snmpModules=snmpModules + ) + +# XXX +# getAsName/setFromName goes out of MibRow? +# revisit getNextNode() -- needs optimization diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-TC.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-TC.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-TC.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-TC.py 2011-12-13 15:19:43.000000000 +0000 @@ -0,0 +1,351 @@ +import sys +from pysnmp.smi import error +from pysnmp import debug + +OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols( + 'ASN1', 'OctetString', 'Integer', 'ObjectIdentifier' + ) +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, + ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols( + "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", + "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" + ) +Counter32, Unsigned32, TimeTicks, Counter64 = mibBuilder.importSymbols( + 'SNMPv2-SMI', 'Counter32', 'Unsigned32', 'TimeTicks', 'Counter64' + ) + +class TextualConvention: + displayHint = '' + status = 'current' + description = '' + reference = '' + bits = () + __integer = Integer() + __counter32 = Counter32() + __unsigned32 = Unsigned32() + __timeticks = TimeTicks() + __counter64 = Counter64() + __octetString = OctetString() + __objectIdentifier = ObjectIdentifier() + def getDisplayHint(self): return self.displayHint + def getStatus(self): return self.status + def getDescription(self): return self.description + def getReference(self): return self.reference + + def prettyOut(self, value): # override asn1 type method + """Implements DISPLAY-HINT evaluation""" + if self.displayHint and ( + self.__integer.isSuperTypeOf(self) or + self.__unsigned32.isSuperTypeOf(self) or + self.__timeticks.isSuperTypeOf(self) or + self.__counter32.isSuperTypeOf(self) or + self.__counter64.isSuperTypeOf(self) + ): + _ = 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 Exception: + raise error.SmiError( + 'float num evaluation error: %s' % sys.exc_info()[1] + ) + elif t == 'o': + return '0%o' % value + elif t == 'b': + v = value; r = ['B'] + while v: + r.insert(0, '%d' % (v&0x01)) + v = v>>1 + return ''.join(r) + else: + raise error.SmiError( + 'Unsupported numeric type spec: %s' % t + ) + elif self.displayHint and self.__octetString.isSuperTypeOf(self): + r = '' + v = self.__class__(value).asNumbers() + d = self.displayHint + while v and d: + # 1 + if d[0] == '*': + repeatIndicator = repeatCount = v[0] + d = d[1:]; v = v[1:] + else: + repeatCount = 1; repeatIndicator = None + + # 2 + octetLength = '' + while d and d[0] in '0123456789': + octetLength = octetLength + d[0] + d = d[1:] + try: + octetLength = int(octetLength) + except Exception: + raise error.SmiError( + 'Bad octet length: %s' % octetLength + ) + if not d: + raise error.SmiError( + 'Short octet length: %s' % self.displayHint + ) + # 3 + displayFormat = d[0] + d = d[1:] + + # 4 + if d and d[0] not in '0123456789' and d[0] != '*': + displaySep = d[0] + d = d[1:] + else: + displaySep = '' + + # 5 + if d and displaySep and repeatIndicator is not None: + repeatTerminator = d[0] + displaySep = '' + d = d[1:] + else: + repeatTerminator = None + + while repeatCount: + repeatCount = repeatCount - 1 + # 't' stands for UTF-8, does it need any special support? + if displayFormat == 'a' or displayFormat == 't': + r = r + ''.join([ chr(x) for x in v[:octetLength] ]) + elif displayFormat in ('x', 'd', 'o'): + n = 0; vv = v[:octetLength] + while vv: + n = n << 8 + try: + n = n | vv[0] + vv = vv[1:] + except Exception: + raise error.SmiError( + 'Display format eval failure: %s: %s' + % (vv, sys.exc_info()[1]) + ) + if displayFormat == 'x': + r = r + '%02x' % n + elif displayFormat == 'o': + r = r + '%03o' % n + else: + r = r + '%d' % n + else: + raise error.SmiError( + 'Unsupported display format char: %s' % \ + displayFormat + ) + if v and repeatTerminator: + r = r + repeatTerminator + v = v[octetLength:] + if v and displaySep: + r = r + displaySep + if not d: + d = self.displayHint +# if d: +# raise error.SmiError( +# 'Unparsed display hint left: %s' % d +# ) + return r + elif self.__objectIdentifier.isSuperTypeOf(self): + return self.__objectIdentifier.prettyOut(value) + elif self.__octetString.isSuperTypeOf(self): + return self.__octetString.prettyOut(value) + else: + return str(value) + +# elif self.bits: +# try: +# return self.bits[value] +# except Exception: +# raise error.SmiError( +# 'Enumeratin resolution failure for %s: %s' % (self, sys.exc_info()[1]) +# ) + +# XXX +# def prettyIn(self, value): +# # XXX parse TC syntax +# return str(value) + +class DisplayString(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) + displayHint = "255a" + +class PhysAddress(TextualConvention, OctetString): + displayHint = "1x:" + +class MacAddress(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(6,6) + displayHint = "1x:" + fixedLength = 6 + +class TruthValue(Integer, TextualConvention): + subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(1, 2) + namedValues = NamedValues(('true', 1), ('false', 2)) + +class TestAndIncr(Integer, TextualConvention): + subtypeSpec = Integer.subtypeSpec+ValueRangeConstraint(0, 2147483647) + defaultValue = 0 + def smiWrite(self, name, value, idx): + if value != self: + raise error.InconsistentValueError(idx=idx, name=name) + value = value + 1 + if value > 2147483646: + value = 0 + return self.clone(value) + +class AutonomousType(ObjectIdentifier, TextualConvention): pass +class InstancePointer(ObjectIdentifier, TextualConvention): + status = 'obsolete' +class VariablePointer(ObjectIdentifier, TextualConvention): pass +class RowPointer(ObjectIdentifier, TextualConvention): pass + +class RowStatus(Integer, TextualConvention): + """A special kind of scalar MIB variable responsible for + MIB table row creation/destruction. + """ + subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(0, 1, 2, 3, 4, 5, 6) + namedValues = NamedValues( + ('notExists', 0), ('active', 1), ('notInService', 2), ('notReady', 3), + ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6) + ) + # Known row states + stNotExists, stActive, stNotInService, stNotReady, \ + stCreateAndGo, stCreateAndWait, stDestroy = list(range(7)) + # States transition matrix (see RFC-1903) + stateMatrix = { + # (new-state, current-state) -> (error, new-state) + ( stCreateAndGo, stNotExists ): ( + error.RowCreationWanted, stActive + ), + ( stCreateAndGo, stNotReady ): ( + error.InconsistentValueError, stNotReady + ), + ( stCreateAndGo, stNotInService ): ( + error.InconsistentValueError, stNotInService + ), + ( stCreateAndGo, stActive ): ( + error.InconsistentValueError, stActive + ), + # + ( stCreateAndWait, stNotExists ): ( + error.RowCreationWanted, stActive + ), + ( stCreateAndWait, stNotReady ): ( + error.InconsistentValueError, stNotReady + ), + ( stCreateAndWait, stNotInService ): ( + error.InconsistentValueError, stNotInService + ), + ( stCreateAndWait, stActive ): ( + error.InconsistentValueError, stActive + ), + # + ( stActive, stNotExists ): ( + error.InconsistentValueError, stNotExists + ), + ( stActive, stNotReady ): ( + error.InconsistentValueError, stNotReady + ), + ( stActive, stNotInService ): ( + None, stActive + ), + ( stActive, stActive ): ( + None, stActive + ), + # + ( stNotInService, stNotExists ): ( + error.InconsistentValueError, stNotExists + ), + ( stNotInService, stNotReady ): ( + error.InconsistentValueError, stNotReady + ), + ( stNotInService, stNotInService ): ( + None, stNotInService + ), + ( stNotInService, stActive ): ( + None, stActive + ), + # + ( stDestroy, stNotExists ): ( + error.RowDestructionWanted, stNotExists + ), + ( stDestroy, stNotReady ): ( + error.RowDestructionWanted, stNotExists + ), + ( stDestroy, stNotInService ): ( + error.RowDestructionWanted, stNotExists + ), + ( stDestroy, stActive ): ( + error.RowDestructionWanted, stNotExists + ), + # This is used on instantiation + ( stNotExists, stNotExists ): ( + None, stNotExists + ) + } + defaultValue = stNotExists + pendingError = None + + def smiWrite(self, name, value, idx): + # Run through states transition matrix, resolve new instance value + err, val = self.stateMatrix.get( + (self.clone(value), int(self)), (error.MibOperationError, None) + ) + debug.logger & debug.flagIns and debug.logger('RowStatus state resolution: %s, %s -> %s, %s' % (value, int(self), err, val)) + if val is None: + val = self + else: + val = self.clone(val) + if err is not None: + err = err( + msg='Exception at row state transition %s->%s' % (self, value), + idx=idx + ) + val.smiSetPendingError(err) + return val + + def smiCreate(self, name, value, idx): + return self.smiWrite(name, value, idx) + + def smiRaisePendingError(self): + if self.pendingError: + err, self.pendingError = self.pendingError, None + raise err + def smiSetPendingError(self, err): + self.pendingError = err + +class TimeStamp(TimeTicks, TextualConvention): pass + +class TimeInterval(Integer, TextualConvention): + subtypeSpec = Integer.subtypeSpec+ValueRangeConstraint(0, 2147483647) + +class DateAndTime(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(8, 11) + displayHint = "2d-1d-1d,1d:1d:1d.1d,1a1d:1d" + +class StorageType(Integer, TextualConvention): + subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(1, 2, 3, 4, 5) + namedValues = NamedValues( + ('other', 1), ('volatile', 2), ('nonVolatile', 3), + ('permanent', 4), ('readOnly', 5) + ) + +class TDomain(ObjectIdentifier, TextualConvention): pass + +class TAddress(OctetString, TextualConvention): + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1, 255) + +mibBuilder.exportSymbols( + 'SNMPv2-TC', TextualConvention=TextualConvention, DisplayString=DisplayString, + PhysAddress=PhysAddress, MacAddress=MacAddress, TruthValue=TruthValue, + TestAndIncr=TestAndIncr, AutonomousType=AutonomousType, + InstancePointer=InstancePointer, VariablePointer=VariablePointer, + RowPointer=RowPointer, RowStatus=RowStatus, TimeStamp=TimeStamp, + TimeInterval=TimeInterval, DateAndTime=DateAndTime, StorageType=StorageType, + TDomain=TDomain, TAddress=TAddress + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-TM.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-TM.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMPv2-TM.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMPv2-TM.py 2011-12-05 14:54:08.000000000 +0000 @@ -0,0 +1,63 @@ + +( OctetString, ) = mibBuilder.importSymbols('ASN1', 'OctetString') +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( ModuleIdentity, MibIdentifier, ObjectIdentity, snmpModules, snmpDomains, snmpProxys ) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'MibIdentifier', 'ObjectIdentity', 'snmpModules', 'snmpDomains', 'snmpProxys') +( TextualConvention, ) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention') + +snmpv2tm = ModuleIdentity(snmpModules.name + (19,)).setRevisions(("2002-10-16 00:00",)) + +snmpUDPDomain = ObjectIdentity(snmpDomains.name + (1,)) + +class SnmpUDPAddress(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6) + displayHint = "1d.1d.1d.1d/2d" + + def 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 = ( + '.'.join(['%d' % x for x in ints[:4]]), ints[4] << 8 | ints[5] + ) + return self.__tuple_value[i] + +snmpCLNSDomain = ObjectIdentity(snmpDomains.name + (2,)) +snmpCONSDomain = ObjectIdentity(snmpDomains.name + (3,)) + +class SnmpOSIAddress(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 85) + displayHint = "*1x:/1x:" + +snmpDDPDomain = ObjectIdentity(snmpDomains.name + (4,)) + +class SnmpNBPAddress(OctetString, TextualConvention): + subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(3, 99) + +snmpIPXDomain = ObjectIdentity(snmpDomains.name + (5,)) + +class SnmpIPXAddress(TextualConvention, OctetString): + subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(12, 12) + displayHint = "4x.1x:1x:1x:1x:1x:1x.2d" + +rfc1157Proxy = MibIdentifier(snmpProxys.name + (1,)) +rfc1157Domain = MibIdentifier(rfc1157Proxy.name + (1,)) + +# Module identity +mibBuilder.exportSymbols("SNMPv2-TM", PYSNMP_MODULE_ID=snmpv2tm) + +mibBuilder.exportSymbols( + 'SNMPv2-TM', snmpv2tm=snmpv2tm, snmpUDPDomain=snmpUDPDomain, + SnmpUDPAddress=SnmpUDPAddress, + snmpCLNSDomain=snmpCLNSDomain, snmpCONSDomain=snmpCONSDomain, + SnmpOSIAddress=SnmpOSIAddress, snmpDDPDomain=snmpDDPDomain, + SnmpNBPAddress=SnmpNBPAddress, snmpIPXDomain=snmpIPXDomain, + SnmpIPXAddress=SnmpIPXAddress, rfc1157Proxy=rfc1157Proxy, + rfc1157Domain=rfc1157Domain + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py 2012-04-03 12:57:43.000000000 +0000 @@ -0,0 +1,111 @@ +# PySNMP SMI module. Autogenerated from smidump -f python SNMP-VIEW-BASED-ACM-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:57:42 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( SnmpAdminString, SnmpSecurityLevel, SnmpSecurityModel, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpSecurityLevel", "SnmpSecurityModel") +( 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, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TestAndIncr") + +# Objects + +snmpVacmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 16)).setRevisions(("2002-10-16 00:00","1999-01-20 00:00","1997-11-20 00:00",)) +if mibBuilder.loadTexts: snmpVacmMIB.setOrganization("SNMPv3 Working Group") +if mibBuilder.loadTexts: snmpVacmMIB.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\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: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nemail: bwijnen@lucent.com\nphone: +31-348-480-685\n\nCo-editor: Randy Presuhn\n BMC Software, Inc.\n\npostal: 2141 North First Street\n San Jose, CA 95131\n USA\nemail: randy_presuhn@bmc.com\nphone: +1 408-546-1006\n\nCo-editor: Keith McCloghrie\n Cisco Systems, Inc.\npostal: 170 West Tasman Drive\n San Jose, CA 95134-1706\n USA\nemail: kzm@cisco.com\nphone: +1-408-526-5260") +if mibBuilder.loadTexts: snmpVacmMIB.setDescription("The management information definitions for the\nView-based Access Control Model for SNMP.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3415;\nsee the RFC itself for full legal notices.") +vacmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1)) +vacmContextTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 1)) +if mibBuilder.loadTexts: vacmContextTable.setDescription("The table of locally available contexts.\n\nThis table provides information to SNMP Command\n\nGenerator applications so that they can properly\nconfigure the vacmAccessTable to control access to\nall contexts at the SNMP entity.\n\nThis table may change dynamically if the SNMP entity\nallows that contexts are added/deleted dynamically\n(for instance when its configuration changes). Such\nchanges would happen only if the management\ninstrumentation at that SNMP entity recognizes more\n(or fewer) contexts.\n\nThe presence of entries in this table and of entries\nin the vacmAccessTable are independent. That is, a\ncontext identified by an entry in this table is not\nnecessarily referenced by any entries in the\nvacmAccessTable; and the context(s) referenced by an\nentry in the vacmAccessTable does not necessarily\ncurrently exist and thus need not be identified by an\nentry in this table.\n\nThis table must be made accessible via the default\ncontext so that Command Responder applications have\na standard way of retrieving the information.\n\nThis table is read-only. It cannot be configured via\nSNMP.") +vacmContextEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 1, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmContextName")) +if mibBuilder.loadTexts: vacmContextEntry.setDescription("Information about a particular context.") +vacmContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") +if mibBuilder.loadTexts: vacmContextName.setDescription("A human readable name identifying a particular\ncontext at a particular SNMP entity.\n\nThe empty contextName (zero length) represents the\ndefault context.") +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=ValueRangeConstraint(1, 2147483647))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: vacmSecurityModel.setDescription("The Security Model, by which the vacmSecurityName\nreferenced by this entry is provided.\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=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.") +vacmGroupName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmGroupName.setDescription("The name of the group to which this entry (e.g., the\ncombination of securityModel and securityName)\nbelongs.\n\nThis groupName is used as index into the\nvacmAccessTable to select an access control policy.\nHowever, a value in this table does not imply that an\ninstance with the value exists in table vacmAccesTable.") +vacmSecurityToGroupStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmSecurityToGroupStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +vacmSecurityToGroupStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmSecurityToGroupStatus.setDescription("The status of this conceptual row.\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\n\ncorresponding instance of the vacmSecurityToGroupStatus\ncolumn is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until a value has been set for vacmGroupName.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified.") +vacmAccessTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 4)) +if mibBuilder.loadTexts: vacmAccessTable.setDescription("The table of access rights for groups.\n\nEach entry is indexed by a groupName, a contextPrefix,\na securityModel and a securityLevel. To determine\nwhether access is allowed, one entry from this table\nneeds to be selected and the proper viewName from that\nentry must be used for access control checking.\n\nTo select the proper entry, follow these steps:\n\n1) the set of possible matches is formed by the\n intersection of the following sets of entries:\n\n the set of entries with identical vacmGroupName\n the union of these two sets:\n - the set with identical vacmAccessContextPrefix\n - the set of entries with vacmAccessContextMatch\n value of 'prefix' and matching\n vacmAccessContextPrefix\n intersected with the union of these two sets:\n - the set of entries with identical\n vacmSecurityModel\n - the set of entries with vacmSecurityModel\n value of 'any'\n intersected with the set of entries with\n vacmAccessSecurityLevel value less than or equal\n to the requested securityLevel\n\n2) if this set has only one member, we're done\n otherwise, it comes down to deciding how to weight\n the preferences between ContextPrefixes,\n SecurityModels, and SecurityLevels as follows:\n a) if the subset of entries with securityModel\n matching the securityModel in the message is\n not empty, then discard the rest.\n b) if the subset of entries with\n vacmAccessContextPrefix matching the contextName\n in the message is not empty,\n then discard the rest\n c) discard all entries with ContextPrefixes shorter\n than the longest one remaining in the set\n d) select the entry with the highest securityLevel\n\nPlease note that for securityLevel noAuthNoPriv, all\ngroups are really equivalent since the assumption that\nthe securityName has been authenticated does not hold.") +vacmAccessEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 4, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextPrefix"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessSecurityModel"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessSecurityLevel")) +if mibBuilder.loadTexts: vacmAccessEntry.setDescription("An access right configured in the Local Configuration\nDatastore (LCD) authorizing access to an SNMP context.\n\nEntries in this table can use an instance value for\nobject vacmGroupName even if no entry in table\nvacmAccessSecurityToGroupTable has a corresponding\nvalue for object vacmGroupName.") +vacmAccessContextPrefix = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: vacmAccessContextPrefix.setDescription("In order to gain the access rights allowed by this\nconceptual row, a contextName must match exactly\n(if the value of vacmAccessContextMatch is 'exact')\nor partially (if the value of vacmAccessContextMatch\nis 'prefix') to the value of the instance of this\nobject.") +vacmAccessSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 2), SnmpSecurityModel()).setMaxAccess("noaccess") +if mibBuilder.loadTexts: vacmAccessSecurityModel.setDescription("In order to gain the access rights allowed by this\nconceptual row, this securityModel must be in use.") +vacmAccessSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 3), SnmpSecurityLevel()).setMaxAccess("noaccess") +if mibBuilder.loadTexts: vacmAccessSecurityLevel.setDescription("The minimum level of security required in order to\ngain the access rights allowed by this conceptual\nrow. A securityLevel of noAuthNoPriv is less than\nauthNoPriv which in turn is less than authPriv.\n\nIf multiple entries are equally indexed except for\nthis vacmAccessSecurityLevel index, then the entry\nwhich has the highest value for\nvacmAccessSecurityLevel is selected.") +vacmAccessContextMatch = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 4), Integer().subtype(subtypeSpec=SingleValueConstraint(2,1,)).subtype(namedValues=NamedValues(("exact", 1), ("prefix", 2), )).clone(1)).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmAccessContextMatch.setDescription("If the value of this object is exact(1), then all\nrows where the contextName exactly matches\nvacmAccessContextPrefix are selected.\n\nIf the value of this object is prefix(2), then all\nrows where the contextName whose starting octets\nexactly match vacmAccessContextPrefix are selected.\nThis allows for a simple form of wildcarding.") +vacmAccessReadViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmAccessReadViewName.setDescription("The value of an instance of this object identifies\nthe MIB view of the SNMP context to which this\nconceptual row authorizes read access.\n\nThe identified MIB view is that one for which the\nvacmViewTreeFamilyViewName has the same value as the\ninstance of this object; if the value is the empty\nstring or if there is no active MIB view having this\nvalue of vacmViewTreeFamilyViewName, then no access\nis granted.") +vacmAccessWriteViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmAccessWriteViewName.setDescription("The value of an instance of this object identifies\nthe MIB view of the SNMP context to which this\nconceptual row authorizes write access.\n\nThe identified MIB view is that one for which the\nvacmViewTreeFamilyViewName has the same value as the\ninstance of this object; if the value is the empty\nstring or if there is no active MIB view having this\nvalue of vacmViewTreeFamilyViewName, then no access\nis granted.") +vacmAccessNotifyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmAccessNotifyViewName.setDescription("The value of an instance of this object identifies\nthe MIB view of the SNMP context to which this\nconceptual row authorizes access for notifications.\n\nThe identified MIB view is that one for which the\nvacmViewTreeFamilyViewName has the same value as the\ninstance of this object; if the value is the empty\nstring or if there is no active MIB view having this\nvalue of vacmViewTreeFamilyViewName, then no access\nis granted.") +vacmAccessStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmAccessStorageType.setDescription("The storage type for this conceptual row.\n\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +vacmAccessStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 9), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmAccessStatus.setDescription("The status of this conceptual row.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified.") +vacmMIBViews = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1, 5)) +vacmViewSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 16, 1, 5, 1), TestAndIncr()).setMaxAccess("readwrite") +if mibBuilder.loadTexts: vacmViewSpinLock.setDescription("An advisory lock used to allow cooperating SNMP\nCommand Generator applications to coordinate their\nuse of the Set operation in creating or modifying\nviews.\n\nWhen creating a new view or altering an existing\nview, it is important to understand the potential\ninteractions with other uses of the view. The\nvacmViewSpinLock should be retrieved. The name of\nthe view to be created should be determined to be\nunique by the SNMP Command Generator application by\nconsulting the vacmViewTreeFamilyTable. Finally,\nthe named view may be created (Set), including the\nadvisory lock.\nIf another SNMP Command Generator application has\naltered the views in the meantime, then the spin\nlock's value will have changed, and so this creation\nwill fail because it will specify the wrong value for\nthe spin lock.\n\nSince this is an advisory lock, the use of this lock\nis not enforced.") +vacmViewTreeFamilyTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 5, 2)) +if mibBuilder.loadTexts: vacmViewTreeFamilyTable.setDescription("Locally held information about families of subtrees\nwithin MIB views.\n\nEach MIB view is defined by two sets of view subtrees:\n - the included view subtrees, and\n - the excluded view subtrees.\nEvery such view subtree, both the included and the\n\nexcluded ones, is defined in this table.\n\nTo determine if a particular object instance is in\na particular MIB view, compare the object instance's\nOBJECT IDENTIFIER with each of the MIB view's active\nentries in this table. If none match, then the\nobject instance is not in the MIB view. If one or\nmore match, then the object instance is included in,\nor excluded from, the MIB view according to the\nvalue of vacmViewTreeFamilyType in the entry whose\nvalue of vacmViewTreeFamilySubtree has the most\nsub-identifiers. If multiple entries match and have\nthe same number of sub-identifiers (when wildcarding\nis specified with the value of vacmViewTreeFamilyMask),\nthen the lexicographically greatest instance of\nvacmViewTreeFamilyType determines the inclusion or\nexclusion.\n\nAn object instance's OBJECT IDENTIFIER X matches an\nactive entry in this table when the number of\nsub-identifiers in X is at least as many as in the\nvalue of vacmViewTreeFamilySubtree for the entry,\nand each sub-identifier in the value of\nvacmViewTreeFamilySubtree matches its corresponding\nsub-identifier in X. Two sub-identifiers match\neither if the corresponding bit of the value of\nvacmViewTreeFamilyMask for the entry is zero (the\n'wild card' value), or if they are equal.\n\nA 'family' of subtrees is the set of subtrees defined\nby a particular combination of values of\nvacmViewTreeFamilySubtree and vacmViewTreeFamilyMask.\n\nIn the case where no 'wild card' is defined in the\nvacmViewTreeFamilyMask, the family of subtrees reduces\nto a single subtree.\n\nWhen creating or changing MIB views, an SNMP Command\nGenerator application should utilize the\nvacmViewSpinLock to try to avoid collisions. See\nDESCRIPTION clause of vacmViewSpinLock.\n\nWhen creating MIB views, it is strongly advised that\nfirst the 'excluded' vacmViewTreeFamilyEntries are\ncreated and then the 'included' entries.\n\nWhen deleting MIB views, it is strongly advised that\nfirst the 'included' vacmViewTreeFamilyEntries are\n\ndeleted and then the 'excluded' entries.\n\nIf a create for an entry for instance-level access\ncontrol is received and the implementation does not\nsupport instance-level granularity, then an\ninconsistentName error must be returned.") +vacmViewTreeFamilyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyViewName"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilySubtree")) +if mibBuilder.loadTexts: vacmViewTreeFamilyEntry.setDescription("Information on a particular family of view subtrees\nincluded in or excluded from a particular SNMP\ncontext's MIB view.\n\nImplementations must not restrict the number of\nfamilies of view subtrees for a given MIB view,\nexcept as dictated by resource constraints on the\noverall number of entries in the\nvacmViewTreeFamilyTable.\n\nIf no conceptual rows exist in this table for a given\nMIB view (viewName), that view may be thought of as\nconsisting of the empty set of view subtrees.") +vacmViewTreeFamilyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") +if mibBuilder.loadTexts: vacmViewTreeFamilyViewName.setDescription("The human readable name for a family of view subtrees.") +vacmViewTreeFamilySubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 2), ObjectIdentifier()).setMaxAccess("noaccess") +if mibBuilder.loadTexts: vacmViewTreeFamilySubtree.setDescription("The MIB subtree which when combined with the\ncorresponding instance of vacmViewTreeFamilyMask\ndefines a family of view subtrees.") +vacmViewTreeFamilyMask = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16)).clone('')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmViewTreeFamilyMask.setDescription("The bit mask which, in combination with the\ncorresponding instance of vacmViewTreeFamilySubtree,\ndefines a family of view subtrees.\n\nEach bit of this bit mask corresponds to a\nsub-identifier of vacmViewTreeFamilySubtree, with the\nmost significant bit of the i-th octet of this octet\nstring value (extended if necessary, see below)\ncorresponding to the (8*i - 7)-th sub-identifier, and\nthe least significant bit of the i-th octet of this\noctet string corresponding to the (8*i)-th\nsub-identifier, where i is in the range 1 through 16.\n\nEach bit of this bit mask specifies whether or not\nthe corresponding sub-identifiers must match when\ndetermining if an OBJECT IDENTIFIER is in this\nfamily of view subtrees; a '1' indicates that an\nexact match must occur; a '0' indicates 'wild card',\ni.e., any sub-identifier value matches.\n\nThus, the OBJECT IDENTIFIER X of an object instance\nis contained in a family of view subtrees if, for\neach sub-identifier of the value of\nvacmViewTreeFamilySubtree, either:\n\n the i-th bit of vacmViewTreeFamilyMask is 0, or\n\n the i-th sub-identifier of X is equal to the i-th\n sub-identifier of the value of\n vacmViewTreeFamilySubtree.\n\nIf the value of this bit mask is M bits long and\n\nthere are more than M sub-identifiers in the\ncorresponding instance of vacmViewTreeFamilySubtree,\nthen the bit mask is extended with 1's to be the\nrequired length.\n\nNote that when the value of this object is the\nzero-length string, this extension rule results in\na mask of all-1's being used (i.e., no 'wild card'),\nand the family of view subtrees is the one view\nsubtree uniquely identified by the corresponding\ninstance of vacmViewTreeFamilySubtree.\n\nNote that masks of length greater than zero length\ndo not need to be supported. In this case this\nobject is made read-only.") +vacmViewTreeFamilyType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 4), Integer().subtype(subtypeSpec=SingleValueConstraint(1,2,)).subtype(namedValues=NamedValues(("included", 1), ("excluded", 2), )).clone(1)).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmViewTreeFamilyType.setDescription("Indicates whether the corresponding instances of\nvacmViewTreeFamilySubtree and vacmViewTreeFamilyMask\ndefine a family of view subtrees which is included in\nor excluded from the MIB view.") +vacmViewTreeFamilyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 5), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmViewTreeFamilyStorageType.setDescription("The storage type for this conceptual row.\n\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") +vacmViewTreeFamilyStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 6), RowStatus()).setMaxAccess("readcreate") +if mibBuilder.loadTexts: vacmViewTreeFamilyStatus.setDescription("The status of this conceptual row.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified.") +vacmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2)) +vacmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 1)) +vacmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 2)) + +# Augmentions + +# 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", "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\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 + +# Module identity +mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", PYSNMP_MODULE_ID=snmpVacmMIB) + +# Objects +mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", snmpVacmMIB=snmpVacmMIB, vacmMIBObjects=vacmMIBObjects, vacmContextTable=vacmContextTable, vacmContextEntry=vacmContextEntry, vacmContextName=vacmContextName, vacmSecurityToGroupTable=vacmSecurityToGroupTable, vacmSecurityToGroupEntry=vacmSecurityToGroupEntry, vacmSecurityModel=vacmSecurityModel, vacmSecurityName=vacmSecurityName, vacmGroupName=vacmGroupName, vacmSecurityToGroupStorageType=vacmSecurityToGroupStorageType, vacmSecurityToGroupStatus=vacmSecurityToGroupStatus, vacmAccessTable=vacmAccessTable, vacmAccessEntry=vacmAccessEntry, vacmAccessContextPrefix=vacmAccessContextPrefix, vacmAccessSecurityModel=vacmAccessSecurityModel, vacmAccessSecurityLevel=vacmAccessSecurityLevel, vacmAccessContextMatch=vacmAccessContextMatch, vacmAccessReadViewName=vacmAccessReadViewName, vacmAccessWriteViewName=vacmAccessWriteViewName, vacmAccessNotifyViewName=vacmAccessNotifyViewName, vacmAccessStorageType=vacmAccessStorageType, vacmAccessStatus=vacmAccessStatus, vacmMIBViews=vacmMIBViews, vacmViewSpinLock=vacmViewSpinLock, vacmViewTreeFamilyTable=vacmViewTreeFamilyTable, vacmViewTreeFamilyEntry=vacmViewTreeFamilyEntry, vacmViewTreeFamilyViewName=vacmViewTreeFamilyViewName, vacmViewTreeFamilySubtree=vacmViewTreeFamilySubtree, vacmViewTreeFamilyMask=vacmViewTreeFamilyMask, vacmViewTreeFamilyType=vacmViewTreeFamilyType, vacmViewTreeFamilyStorageType=vacmViewTreeFamilyStorageType, vacmViewTreeFamilyStatus=vacmViewTreeFamilyStatus, vacmMIBConformance=vacmMIBConformance, vacmMIBCompliances=vacmMIBCompliances, vacmMIBGroups=vacmMIBGroups) + +# Groups +mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmBasicGroup=vacmBasicGroup) + +# Compliances +mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmMIBCompliance=vacmMIBCompliance) diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py python-pysnmp4-4.2.2/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py 2012-04-03 13:03:09.000000000 +0000 @@ -0,0 +1,140 @@ +# PySNMP SMI module. Autogenerated from smidump -f python TRANSPORT-ADDRESS-MIB +# by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:58:37 2012, +# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) + +import socket + +# Imports + +( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") +( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") +( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") +( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, TimeTicks, mib_2, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "TimeTicks", "mib-2") +( TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention") + +# Types + +class TransportAddress(OctetString): + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) + +class TransportAddressDns(TextualConvention, OctetString): + displayHint = "1a" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1,255) + +class TransportAddressIPv4(TextualConvention, OctetString): + displayHint = "1d.1d.1d.1d:2d" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(6,6) + fixedLength = 6 + + def 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 = ( + '.'.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+ValueSizeConstraint(10,10) + fixedLength = 10 + +class TransportAddressIPv6(TextualConvention, OctetString): + displayHint = "0a[2x:2x:2x:2x:2x:2x:2x:2x]0a:2d" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(18,18) + fixedLength = 18 + + def prettyIn(self, value): + 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) + + # Socket address syntax coercion + def __getitem__(self, i): + if not hasattr(self, '__tuple_value'): + self.__tuple_value = ( + socket.inet_ntop(socket.AF_INET6, self._value[:16]), + ord(self._value[16:17]) << 8 | ord(self._value[17:18]), + 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+ValueSizeConstraint(22,22) + fixedLength = 22 + +class TransportAddressLocal(TextualConvention, OctetString): + displayHint = "1a" + subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1,255) + +class TransportAddressType(Integer): + subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(12,9,14,2,7,8,0,11,1,15,16,3,4,10,6,5,13,) + namedValues = 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), ) + +class TransportDomain(ObjectIdentifier): + pass + + +# Objects + +transportAddressMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 100)).setRevisions(("2002-11-01 00:00",)) +if mibBuilder.loadTexts: transportAddressMIB.setOrganization("IETF Operations and Management Area") +if mibBuilder.loadTexts: transportAddressMIB.setContactInfo("Juergen Schoenwaelder (Editor)\nTU Braunschweig\nBueltenweg 74/75\n38106 Braunschweig, Germany\n\nPhone: +49 531 391-3289\nEMail: schoenw@ibr.cs.tu-bs.de\n\nSend comments to .") +if mibBuilder.loadTexts: transportAddressMIB.setDescription("This MIB module provides commonly used transport\naddress definitions.\n\nCopyright (C) The Internet Society (2002). This version of\nthis MIB module is part of RFC 3419; see the RFC itself for\nfull legal notices.") +transportDomains = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1)) +transportDomainUdpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 1)) +if mibBuilder.loadTexts: transportDomainUdpIpv4.setDescription("The UDP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4 for\nglobal IPv4 addresses.") +transportDomainUdpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 2)) +if mibBuilder.loadTexts: transportDomainUdpIpv6.setDescription("The UDP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6 for\nglobal IPv6 addresses.") +transportDomainUdpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 3)) +if mibBuilder.loadTexts: transportDomainUdpIpv4z.setDescription("The UDP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4z for\nscoped IPv4 addresses with a zone index.") +transportDomainUdpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 4)) +if mibBuilder.loadTexts: transportDomainUdpIpv6z.setDescription("The UDP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6z for\nscoped IPv6 addresses with a zone index.") +transportDomainTcpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 5)) +if mibBuilder.loadTexts: transportDomainTcpIpv4.setDescription("The TCP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4 for\nglobal IPv4 addresses.") +transportDomainTcpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 6)) +if mibBuilder.loadTexts: transportDomainTcpIpv6.setDescription("The TCP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6 for\nglobal IPv6 addresses.") +transportDomainTcpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 7)) +if mibBuilder.loadTexts: transportDomainTcpIpv4z.setDescription("The TCP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4z for\nscoped IPv4 addresses with a zone index.") +transportDomainTcpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 8)) +if mibBuilder.loadTexts: transportDomainTcpIpv6z.setDescription("The TCP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6z for\nscoped IPv6 addresses with a zone index.") +transportDomainSctpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 9)) +if mibBuilder.loadTexts: transportDomainSctpIpv4.setDescription("The SCTP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4 for\nglobal IPv4 addresses. This transport domain usually\nrepresents the primary address on multihomed SCTP\nendpoints.") +transportDomainSctpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 10)) +if mibBuilder.loadTexts: transportDomainSctpIpv6.setDescription("The SCTP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6 for\nglobal IPv6 addresses. This transport domain usually\nrepresents the primary address on multihomed SCTP\nendpoints.") +transportDomainSctpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 11)) +if mibBuilder.loadTexts: transportDomainSctpIpv4z.setDescription("The SCTP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4z for\nscoped IPv4 addresses with a zone index. This transport\ndomain usually represents the primary address on\nmultihomed SCTP endpoints.") +transportDomainSctpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 12)) +if mibBuilder.loadTexts: transportDomainSctpIpv6z.setDescription("The SCTP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6z for\nscoped IPv6 addresses with a zone index. This transport\ndomain usually represents the primary address on\nmultihomed SCTP endpoints.") +transportDomainLocal = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 13)) +if mibBuilder.loadTexts: transportDomainLocal.setDescription("The Posix Local IPC transport domain. The corresponding\ntransport address is of type TransportAddressLocal.\n\nThe Posix Local IPC transport domain incorporates the\nwell-known UNIX domain sockets.") +transportDomainUdpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 14)) +if mibBuilder.loadTexts: transportDomainUdpDns.setDescription("The UDP transport domain using fully qualified domain\nnames. The corresponding transport address is of type\nTransportAddressDns.") +transportDomainTcpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 15)) +if mibBuilder.loadTexts: transportDomainTcpDns.setDescription("The TCP transport domain using fully qualified domain\nnames. The corresponding transport address is of type\nTransportAddressDns.") +transportDomainSctpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 16)) +if mibBuilder.loadTexts: transportDomainSctpDns.setDescription("The SCTP transport domain using fully qualified domain\nnames. The corresponding transport address is of type\nTransportAddressDns.") + +# Augmentions + +# Exports + +# Module identity +mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", PYSNMP_MODULE_ID=transportAddressMIB) + +# Types +mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", TransportAddress=TransportAddress, TransportAddressDns=TransportAddressDns, TransportAddressIPv4=TransportAddressIPv4, TransportAddressIPv4z=TransportAddressIPv4z, TransportAddressIPv6=TransportAddressIPv6, TransportAddressIPv6z=TransportAddressIPv6z, TransportAddressLocal=TransportAddressLocal, TransportAddressType=TransportAddressType, TransportDomain=TransportDomain) + +# Objects +mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", transportAddressMIB=transportAddressMIB, transportDomains=transportDomains, transportDomainUdpIpv4=transportDomainUdpIpv4, transportDomainUdpIpv6=transportDomainUdpIpv6, transportDomainUdpIpv4z=transportDomainUdpIpv4z, transportDomainUdpIpv6z=transportDomainUdpIpv6z, transportDomainTcpIpv4=transportDomainTcpIpv4, transportDomainTcpIpv6=transportDomainTcpIpv6, transportDomainTcpIpv4z=transportDomainTcpIpv4z, transportDomainTcpIpv6z=transportDomainTcpIpv6z, transportDomainSctpIpv4=transportDomainSctpIpv4, transportDomainSctpIpv6=transportDomainSctpIpv6, transportDomainSctpIpv4z=transportDomainSctpIpv4z, transportDomainSctpIpv6z=transportDomainSctpIpv6z, transportDomainLocal=transportDomainLocal, transportDomainUdpDns=transportDomainUdpDns, transportDomainTcpDns=transportDomainTcpDns, transportDomainSctpDns=transportDomainSctpDns) + diff -Nru python-pysnmp4-4.1.9a/pysnmp/smi/view.py python-pysnmp4-4.2.2/pysnmp/smi/view.py --- python-pysnmp4-4.1.9a/pysnmp/smi/view.py 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/smi/view.py 2011-12-13 15:32:50.000000000 +0000 @@ -0,0 +1,316 @@ +# MIB modules management +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 + self.lastBuildId = -1 + + # Indexing part + + def indexMib(self): + if self.lastBuildId == self.mibBuilder.lastBuildId: + return + + debug.logger & debug.flagMIB and debug.logger('indexMib: re-indexing MIB view') + + MibScalarInstance, = self.mibBuilder.importSymbols( + 'SNMPv2-SMI', 'MibScalarInstance' + ) + + # + # Create indices + # + + # Module name -> module-scope indices + self.__mibSymbolsIdx = OrderedDict() + + # Oid <-> label indices + + # This is potentionally ambiguous mapping. Sort modules in + # ascending age for resolution + def __sortFun(x, b=self.mibBuilder): + if b.moduleID in b.mibSymbols[x]: + m = b.mibSymbols[x][b.moduleID] + r = m.getRevisions() + if r: + return r[0] + else: + return "1970-01-01 00:00" + + modNames = list(self.mibBuilder.mibSymbols.keys()) + modNames.sort(key=__sortFun) + + # Index modules names + for modName in [ '' ] + modNames: + # Modules index + self.__mibSymbolsIdx[modName] = mibMod = { + 'oidToLabelIdx': OidOrderedDict(), + 'labelToOidIdx': {}, + 'varToNameIdx': {}, + 'typeToModIdx': OrderedDict(), + 'oidToModIdx': {} + } + + if not modName: + globMibMod = mibMod + continue + + # Types & MIB vars indices + for n, v in self.mibBuilder.mibSymbols[modName].items(): + if n == self.mibBuilder.moduleID: # do not index this + continue # special symbol + if isinstance(v, classTypes): + if n in mibMod['typeToModIdx']: + raise error.SmiError( + 'Duplicate SMI type %s::%s, has %s' % \ + (modName, n, mibMod['typeToModIdx'][n]) + ) + globMibMod['typeToModIdx'][n] = modName + mibMod['typeToModIdx'][n] = modName + elif isinstance(v, instanceTypes): + if isinstance(v, MibScalarInstance): + continue + if n in mibMod['varToNameIdx']: + raise error.SmiError( + 'Duplicate MIB variable %s::%s has %s' % \ + (modName, n, mibMod['varToNameIdx'][n]) + ) + globMibMod['varToNameIdx'][n] = v.name + mibMod['varToNameIdx'][n] = v.name + # Potentionally ambiguous mapping ahead + globMibMod['oidToModIdx'][v.name] = modName + mibMod['oidToModIdx'][v.name] = modName + globMibMod['oidToLabelIdx'][v.name] = (n, ) + mibMod['oidToLabelIdx'][v.name] = (n, ) + else: + raise error.SmiError( + 'Unexpected object %s::%s' % (modName, n) + ) + + # Build oid->long-label index + oidToLabelIdx = self.__mibSymbolsIdx['']['oidToLabelIdx'] + labelToOidIdx = self.__mibSymbolsIdx['']['labelToOidIdx'] + if oidToLabelIdx: + prevOid = oidToLabelIdx.keys()[0] + else: + prevOid = () + baseLabel = () + for key in oidToLabelIdx.keys(): + keydiff = len(key) - len(prevOid) + if keydiff > 0: + baseLabel = oidToLabelIdx[prevOid] + if keydiff > 1: + baseLabel = baseLabel + key[-keydiff:-1] + if keydiff < 0: + keyLen = len(key) + i = keyLen-1 + while i: + k = key[:i] + if k in oidToLabelIdx: + baseLabel = oidToLabelIdx[k] + if i != keyLen-1: + baseLabel = baseLabel + key[i:-1] + break + i = i - 1 + # Build oid->long-label index + oidToLabelIdx[key] = baseLabel + oidToLabelIdx[key] + # Build label->oid index + labelToOidIdx[oidToLabelIdx[key]] = key + prevOid = key + + # Build module-scope oid->long-label index + for mibMod in self.__mibSymbolsIdx.values(): + for oid in mibMod['oidToLabelIdx'].keys(): + mibMod['oidToLabelIdx'][oid] = oidToLabelIdx[oid] + mibMod['labelToOidIdx'][oidToLabelIdx[oid]] = oid + + self.lastBuildId = self.mibBuilder.lastBuildId + + # Module management + + def getFirstModuleName(self): + self.indexMib() + modNames = self.__mibSymbolsIdx.keys() + if modNames: + return modNames[0] + raise error.SmiError('No modules loaded at %s' % self) + + def getNextModuleName(self, modName): + self.indexMib() + try: + return self.__mibSymbolsIdx.nextKey(modName) + except KeyError: + raise error.SmiError( + 'No module next to %s at %s' % (modName, self) + ) + + # MIB tree node management + + def __getOidLabel(self, nodeName, oidToLabelIdx, labelToOidIdx): + """getOidLabel(nodeName) -> (oid, label, suffix)""" + if not nodeName: + return nodeName, nodeName, () + if nodeName in labelToOidIdx: + return labelToOidIdx[nodeName], nodeName, () + if nodeName in oidToLabelIdx: + return nodeName, oidToLabelIdx[nodeName], () + if len(nodeName) < 2: + return nodeName, nodeName, () + oid, label, suffix = self.__getOidLabel( + nodeName[:-1], oidToLabelIdx, labelToOidIdx + ) + suffix = suffix + nodeName[-1:] + resLabel = label + tuple([ str(x) for x in suffix ]) + if resLabel in labelToOidIdx: + return labelToOidIdx[resLabel], resLabel, () + resOid = oid + suffix + if resOid in oidToLabelIdx: + return resOid, oidToLabelIdx[resOid], () + return oid, label, suffix + + def getNodeNameByOid(self, nodeName, modName=''): + self.indexMib() + if modName in self.__mibSymbolsIdx: + mibMod = self.__mibSymbolsIdx[modName] + else: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + oid, label, suffix = self.__getOidLabel( + nodeName, mibMod['oidToLabelIdx'], mibMod['labelToOidIdx'] + ) + if oid == label: + raise error.NoSuchObjectError( + str='Can\'t resolve node name %s::%s at %s' % + (modName, nodeName, self) + ) + debug.logger & debug.flagMIB and debug.logger('getNodeNameByOid: resolved %s:%s -> %s' % (modName, nodeName, label + suffix)) + return oid, label, suffix + + def getNodeNameByDesc(self, nodeName, modName=''): + self.indexMib() + if modName in self.__mibSymbolsIdx: + mibMod = self.__mibSymbolsIdx[modName] + else: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + if nodeName in mibMod['varToNameIdx']: + oid = mibMod['varToNameIdx'][nodeName] + else: + raise error.NoSuchObjectError( + str='No such symbol %s::%s at %s' % (modName, nodeName, self) + ) + debug.logger & debug.flagMIB and debug.logger('getNodeNameByDesc: resolved %s:%s -> %s' % (modName, nodeName, oid)) + return self.getNodeNameByOid(oid, modName) + + def getNodeName(self, nodeName, modName=''): + # nodeName may be either an absolute OID/label or a + # ( MIB-symbol, su, ff, ix) + try: + # First try nodeName as an OID/label + return self.getNodeNameByOid(nodeName, modName) + except error.NoSuchObjectError: + # ...on failure, try as MIB symbol + oid, label, suffix = self.getNodeNameByDesc( + nodeName[0], modName + ) + # ...with trailing suffix + return self.getNodeNameByOid( + oid + suffix + nodeName[1:], modName + ) + + def getFirstNodeName(self, modName=''): + self.indexMib() + if modName in self.__mibSymbolsIdx: + mibMod = self.__mibSymbolsIdx[modName] + else: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + if not mibMod['oidToLabelIdx']: + raise error.NoSuchObjectError( + str='No variables at MIB module %s at %s' % (modName, self) + ) + oid, label = mibMod['oidToLabelIdx'].items()[0] + return oid, label, () + + def getNextNodeName(self, nodeName, modName=''): + oid, label, suffix = self.getNodeName(nodeName, modName) + try: + return self.getNodeName( + self.__mibSymbolsIdx[modName]['oidToLabelIdx'].nextKey(oid) + suffix, modName + ) + except KeyError: + raise error.NoSuchObjectError( + str='No name next to %s::%s at %s' % (modName, nodeName, self) + ) + + def getParentNodeName(self, nodeName, modName=''): + oid, label, suffix = self.getNodeName(nodeName, modName) + if len(oid) < 2: + raise error.NoSuchObjectError( + str='No parent name for %s::%s at %s' % + (modName, nodeName, self) + ) + return oid[:-1], label[:-1], oid[-1:] + suffix + + def getNodeLocation(self, nodeName, modName=''): + oid, label, suffix = self.getNodeName(nodeName, modName) + return self.__mibSymbolsIdx['']['oidToModIdx'][oid], label[-1], suffix + + # MIB type management + + def getTypeName(self, typeName, modName=''): + self.indexMib() + if modName in self.__mibSymbolsIdx: + mibMod = self.__mibSymbolsIdx[modName] + else: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + if typeName in mibMod['typeToModIdx']: + m = mibMod['typeToModIdx'][typeName] + else: + raise error.NoSuchObjectError( + str='No such type %s::%s at %s' % (modName, typeName, self) + ) + return m, typeName + + def getFirstTypeName(self, modName=''): + self.indexMib() + if modName in self.__mibSymbolsIdx: + mibMod = self.__mibSymbolsIdx[modName] + else: + raise error.SmiError( + 'No module %s at %s' % (modName, self) + ) + if not mibMod['typeToModIdx']: + raise error.NoSuchObjectError( + str='No types at MIB module %s at %s' % (modName, self) + ) + t = mibMod['typeToModIdx'].keys()[0] + return mibMod['typeToModIdx'][t], t + + def getNextType(self, typeName, modName=''): + m, t = self.getTypeName(typeName, modName) + try: + return self.__mibSymbolsIdx[m]['typeToModIdx'].nextKey(t) + except KeyError: + raise error.NoSuchObjectError( + str='No type next to %s::%s at %s' % (modName, typeName, self) + ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/base.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/base.py 2007-09-03 07:09:36.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -"""Defines standard API to asyncore-based transport""" -try: - from sys import version_info -except ImportError: - version_info = ( 0, 0 ) # a really early version -import socket, sys -import asyncore -from pysnmp.carrier import error - -class AbstractSocketTransport(asyncore.dispatcher): - sockFamily = sockType = None - retryCount = 0; retryInterval = 0 - def __init__(self, sock=None, sockMap=None): - if sock is None: - try: - sock = socket.socket(self.sockFamily, self.sockType) - except socket.error, why: - raise error.CarrierError('socket() failed: %s' % why) - if sockMap is None: - # The socket map is managed by the AsynsockDispatcher on - # which this transport is registered, so this is a fake - # socket map to avoid registering with deafult asyncore map. - sockMap = {} - # Old asyncore doesn't allow socket_map param in constructor - if version_info < (2, 0): - # Taken from dispatcher.__init__() - self.socket = sock - self.add_channel(sockMap) - self.socket.setblocking(0) - self.connected = 1 - else: - asyncore.dispatcher.__init__(self, sock, sockMap) - - # Old asyncore doesn't allow socket_map param - if version_info < (2, 0): - def add_channel (self, sockMap=None): - if sockMap is None: - sockMap = asyncore.socket_map - sockMap[self] = self - - def del_channel (self, sockMap=None): - if sockMap is None: - sockMap = asyncore.socket_map - if sockMap.has_key(self): - del sockMap[self] - - def registerSocket(self, sockMap=None): - self.add_channel(sockMap) - - def unregisterSocket(self, sockMap=None): - self.del_channel(sockMap) - - # Public API - - def openClientMode(self, iface=None): - raise error.CarrierError('Method not implemented') - - def openServerMode(self, iface=None): - raise error.CarrierError('Method not implemented') - - def sendMessage(self, outgoingMessage, transportAddress): - raise error.CarrierError('Method not implemented') - - def registerCbFun(self, cbFun): - self._cbFun = cbFun - - def unregisterCbFun(self): - self._cbFun = None - - def closeTransport(self): - self.unregisterCbFun() - self.close() - - # asyncore API - def handle_close(self): raise error.CarrierError( - 'Transport unexpectedly closed' - ) - def handle_error(self): raise - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dgram/base.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dgram/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dgram/base.py 2007-09-20 05:38:27.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dgram/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -"""Implements asyncore-based generic DGRAM transport""" -import socket, errno -from pysnmp.carrier.asynsock.base import AbstractSocketTransport -from pysnmp.carrier import error -from pysnmp import debug - -sockErrors = { # Ignore these socket errors - errno.ESHUTDOWN: 1, - errno.ENOTCONN: 1, - errno.ECONNRESET: 0, - errno.ECONNREFUSED: 0, - errno.EAGAIN: 0, - errno.EWOULDBLOCK: 0 - } -try: - # bad FD may happen upon FD closure on n-1 select() event - sockErrors[errno.EBADFD] = 1 -except AttributeError: - # Windows sockets do not have EBADFD - pass - -class DgramSocketTransport(AbstractSocketTransport): - sockType = socket.SOCK_DGRAM - retryCount = 3; retryInterval = 1 - def __init__(self, sock=None, sockMap=None): - self.__outQueue = [] - AbstractSocketTransport.__init__(self, sock, sockMap) - - def openClientMode(self, iface=None): - if iface is not None: - try: - self.socket.bind(iface) - except socket.error, why: - raise error.CarrierError('bind() failed: %s' % (why,)) - return self - - def openServerMode(self, iface): - try: - self.socket.bind(iface) - except socket.error, why: - raise error.CarrierError('bind() failed: %s' % (why,)) - self._iface = iface - return self - - def sendMessage(self, outgoingMessage, transportAddress): - self.__outQueue.append( - (outgoingMessage, transportAddress) - ) - - # asyncore API - def handle_connect(self): pass - def writable(self): return self.__outQueue - def handle_write(self): - outgoingMessage, transportAddress = self.__outQueue.pop() - 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 sockErrors.has_key(why[0]): - debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (why,)) - else: - raise socket.error, why - - def readable(self): return 1 - def handle_read(self): - try: - incomingMessage, transportAddress = self.socket.recvfrom(65535) - debug.logger & debug.flagIO and debug.logger('handle_read: transportAddress %s incomingMessage %s' % (transportAddress, repr(incomingMessage))) - if not incomingMessage: - self.handle_close() - return - else: - self._cbFun(self, transportAddress, incomingMessage) - return - except socket.error, why: - if sockErrors.has_key(why[0]): - debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % (why,)) - sockErrors[why[0]] and self.handle_close() - return - else: - raise socket.error, why - def handle_close(self): pass # no datagram connection diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dgram/udp.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dgram/udp.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dgram/udp.py 2005-06-14 10:00:57.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dgram/udp.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -"""Implements asyncore-based UDP transport domain""" -from socket import AF_INET -from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport - -domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) - -class UdpSocketTransport(DgramSocketTransport): - sockFamily = AF_INET diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dgram/unix.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dgram/unix.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dgram/unix.py 2005-06-14 10:01:40.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dgram/unix.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -"""Implements asyncore-based UNIX transport domain""" -from os import remove -from socket import AF_UNIX -from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport - -domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) - -class UnixDgramSocketTransport(DgramSocketTransport): - sockFamily = AF_UNIX - - def closeTransport(self): - DgramSocketTransport.closeTransport(self) - try: - remove(self._iface) - except: - pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dispatch.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dispatch.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/asynsock/dispatch.py 2007-11-16 08:55:59.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/asynsock/dispatch.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -try: - from sys import version_info -except ImportError: - version_info = ( 0, 0 ) # a really early version -from time import time -from select import select -from asyncore import socket_map -from pysnmp.carrier.base import AbstractTransportDispatcher - -# Old asyncore doesn't allow socket_map param at poll -if version_info < (2, 0): - def poll(timeout, socket_map): - if not socket_map: - return - sockets = socket_map.keys() - r = filter(lambda x: x.readable(), sockets) - w = filter(lambda x: x.writable(), sockets) - - (r,w,e) = select(r, w, [], timeout) - - for x in r: - try: - x.handle_read_event() - except: - x.handle_error() - for x in w: - try: - x.handle_write_event() - except: - x.handle_error() -else: - from asyncore import poll - -class AsynsockDispatcher(AbstractTransportDispatcher): - """Implements I/O over asynchronous sockets""" - def __init__(self): - self.__sockMap = {} # use own map for MT safety - self.timeout = 1.0 - AbstractTransportDispatcher.__init__(self) - - def getSocketMap(self): return self.__sockMap - def setSocketMap(self, sockMap=socket_map): self.__sockMap = sockMap - - def registerTransport(self, tDomain, t): - AbstractTransportDispatcher.registerTransport(self, tDomain, t) - t.registerSocket(self.__sockMap) - - def unregisterTransport(self, tDomain): - self.getTransport(tDomain).unregisterSocket(self.__sockMap) - AbstractTransportDispatcher.unregisterTransport(self, tDomain) - - def transportsAreWorking(self): - for transport in self.__sockMap.values(): - if transport.writable(): - return 1 - return 0 - - def runDispatcher(self, timeout=0.0): - while self.jobsArePending() or self.transportsAreWorking(): - poll(self.timeout, self.__sockMap) - self.handleTimerTick(time()) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/base.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/base.py 2007-09-20 05:38:26.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -"""Abstract I/O dispatcher. Defines standard dispatcher API""" -from pysnmp.carrier import error - -class AbstractTransportDispatcher: - def __init__(self): - self.__transports = {} - self.__jobs = {} - self.__recvCbFun = self.__timerCbFun = None - self.__timeToGo = 0 - - def _cbFun(self, incomingTransport, transportAddress, incomingMessage): - for name, transport in self.__transports.items(): - if transport is incomingTransport: - transportDomain = name - break - else: - raise error.CarrierError( - 'Unregistered transport %s' % (incomingTransport,) - ) - if self.__recvCbFun is None: - raise error.CarrierError( - 'Receive callback not registered -- loosing incoming event' - ) - self.__recvCbFun( - self, transportDomain, transportAddress, incomingMessage - ) - - # Dispatcher API - - def registerRecvCbFun(self, recvCbFun): - if self.__recvCbFun is not None: - raise error.CarrierError( - 'Receive callback already registered: %s' % self.__recvCbFun - ) - self.__recvCbFun = recvCbFun - - def unregisterRecvCbFun(self): - self.__recvCbFun = None - - def registerTimerCbFun(self, timerCbFun): - if self.__timerCbFun is not None: - raise error.CarrierError( - 'Callback already registered: %s' % self.__timerCbFun - ) - self.__timerCbFun = timerCbFun - - def unregisterTimerCbFun(self): - self.__timerCbFun = None - - def registerTransport(self, tDomain, transport): - if self.__transports.has_key(tDomain): - raise error.CarrierError( - 'Transport %s already registered' % (tDomain,) - ) - transport.registerCbFun(self._cbFun) - self.__transports[tDomain] = transport - - def unregisterTransport(self, tDomain): - if not self.__transports.has_key(tDomain): - raise error.CarrierError( - 'Transport %s not registered' % (tDomain,) - ) - self.__transports[tDomain].unregisterCbFun() - del self.__transports[tDomain] - - def getTransport(self, transportDomain): - return self.__transports.get(transportDomain) - - def sendMessage( - self, outgoingMessage, transportDomain, transportAddress - ): - transport = self.__transports.get(transportDomain) - if transport is None: - raise error.CarrierError( - 'No suitable transport domain for %s' % (transportDomain,) - ) - transport.sendMessage(outgoingMessage, transportAddress) - - def handleTimerTick(self, timeNow): - if self.__timerCbFun and self.__timeToGo < timeNow: - self.__timerCbFun(timeNow) - self.__timeToGo = timeNow + 1 - - def jobStarted(self, jobId): - self.__jobs[jobId] = self.__jobs.get(jobId, 0) + 1 - - def jobFinished(self, jobId): - self.__jobs[jobId] = self.__jobs[jobId] - 1 - if self.__jobs[jobId] == 0: - del self.__jobs[jobId] - - def jobsArePending(self): - if self.__jobs: - return 1 - else: - return 0 - - def runDispatcher(self, timeout=0.0): - raise error.CarrierError('Method not implemented') - - def closeDispatcher(self): - for tDomain in self.__transports.keys(): - self.__transports[tDomain].closeTransport() - self.unregisterTransport(tDomain) - self.unregisterRecvCbFun() - self.unregisterTimerCbFun() diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/carrier/error.py python-pysnmp4-4.2.2/pysnmp/v4/carrier/error.py --- python-pysnmp4-4.1.9a/pysnmp/v4/carrier/error.py 2005-06-14 09:56:02.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/carrier/error.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -from pysnmp import error - -class CarrierError(error.PySnmpError): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/debug.py python-pysnmp4-4.2.2/pysnmp/v4/debug.py --- python-pysnmp4-4.1.9a/pysnmp/v4/debug.py 2006-09-29 13:14:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/debug.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -import sys -from pysnmp import error - -flagNone = 0x0000 -flagIO = 0x0001 -flagDsp = 0x0002 -flagMP = 0x0004 -flagSM = 0x0008 -flagBld = 0x0010 -flagMIB = 0x0020 -flagIns = 0x0040 -flagACL = 0x0080 -flagPrx = 0x0100 -flagAll = 0xffff - -flagMap = { - 'io': flagIO, - 'dsp': flagDsp, - 'msgproc': flagMP, - 'secmod': flagSM, - 'mibbuild': flagBld, - 'mibview': flagMIB, - 'mibinstrum': flagIns, - 'acl': flagACL, - 'proxy': flagPrx, - 'all': flagAll - } - -class Debug: - defaultPrinter = sys.stderr.write - def __init__(self, *flags): - self._flags = flagNone - self._printer = self.defaultPrinter - for f in flags: - if not flagMap.has_key(f): - raise error.PySnmpError('bad debug flag %s' % f) - self._flags = self._flags | flagMap[f] - self('debug category %s enabled' % f) - - def __str__(self): - return 'logger %s, flags %x' % (self._printer, self._flags) - - def __call__(self, msg): - self._printer('DBG: %s\n' % msg) - - def __and__(self, flag): - return self._flags & flag - - def __rand__(self, flag): - return flag & self._flags - -logger = Debug() - -def setLogger(l): - global logger - logger = l diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/config.py python-pysnmp4-4.2.2/pysnmp/v4/entity/config.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/config.py 2007-07-09 13:39:48.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/config.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,630 +0,0 @@ -# Initial SNMP engine configuration functions. During further operation, -# SNMP engine might be configured remotely (through SNMP). -import string -from pysnmp.carrier.asynsock import dispatch -from pysnmp.carrier.asynsock.dgram import udp -try: - from pysnmp.carrier.asynsock.dgram import unix - snmpLocalDomain = unix.snmpLocalDomain -except ImportError: # UNIX-specific -- may not be always available - pass -from pysnmp.proto import rfc3412 -from pysnmp.proto.secmod.rfc3414 import localkey -from pysnmp.entity import engine -from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha, noauth -from pysnmp.proto.secmod.rfc3414.priv import des, nopriv -from pysnmp.proto.secmod.rfc3826.priv import aes -from pysnmp.smi.error import NotWritableError -from pysnmp import error - -# A shortcut to popular constants - -# Transports -snmpUDPDomain = udp.snmpUDPDomain - -# Auth protocol -usmHMACMD5AuthProtocol = hmacmd5.HmacMd5.serviceID -usmHMACSHAAuthProtocol = hmacsha.HmacSha.serviceID -usmNoAuthProtocol = noauth.NoAuth.serviceID - -# Privacy protocol -usmDESPrivProtocol = des.Des.serviceID -usmAesCfb128Protocol = aes.Aes.serviceID -usmNoPrivProtocol = nopriv.NoPriv.serviceID - -def __cookV1SystemInfo(snmpEngine, securityName): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - - snmpCommunityEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') - tblIdx = snmpCommunityEntry.getInstIdFromIndices( - snmpEngineID.syntax, securityName - ) - - return snmpCommunityEntry, tblIdx, snmpEngineID - -def addV1System(snmpEngine, securityName, communityName, - contextEngineId=None, contextName=None, - transportTag=None): - snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( - snmpEngine, securityName - ) - - if contextEngineId is None: - contextEngineId = snmpEngineID.syntax - if contextName is not None: - contextName = communityName - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo'), - (snmpCommunityEntry.name + (2,) + tblIdx, communityName), - (snmpCommunityEntry.name + (3,) + tblIdx, securityName), - (snmpCommunityEntry.name + (4,) + tblIdx, contextEngineId), - (snmpCommunityEntry.name + (5,) + tblIdx, contextName), - (snmpCommunityEntry.name + (6,) + tblIdx, transportTag), - (snmpCommunityEntry.name + (7,) + tblIdx, 'nonVolatile')) - ) - -def delV1System(snmpEngine, securityName): - snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( - snmpEngine, securityName - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) - ) - -def __cookV3UserInfo(snmpEngine, securityName, contextEngineId): - if contextEngineId is None: - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpEngineID = snmpEngineID.syntax - else: - snmpEngineID = contextEngineId - - usmUserEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') - tblIdx1 = usmUserEntry.getInstIdFromIndices( - snmpEngineID, securityName - ) - - pysnmpUsmSecretEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') - tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) - - return snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 - -def addV3User(snmpEngine, securityName, - authProtocol=usmNoAuthProtocol, authKey=None, - privProtocol=usmNoPrivProtocol, privKey=None, - contextEngineId=None): - ( snmpEngineID, usmUserEntry, tblIdx1, - pysnmpUsmSecretEntry, tblIdx2 ) = __cookV3UserInfo( - snmpEngine, securityName, contextEngineId - ) - - # Load augmenting table before creating new row in base one - pysnmpUsmKeyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') - - # Load clone-from (may not be needed) - zeroDotZero, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((usmUserEntry.name + (13,) + tblIdx1, 'createAndGo'), - (usmUserEntry.name + (3,) + tblIdx1, securityName), - (usmUserEntry.name + (4,) + tblIdx1, zeroDotZero.name), - (usmUserEntry.name + (5,) + tblIdx1, authProtocol), - (usmUserEntry.name + (8,) + tblIdx1, privProtocol)) - ) - - # Localize keys - if authProtocol == usmHMACMD5AuthProtocol: - hashedAuthPassphrase = localkey.hashPassphraseMD5( - authKey and authKey or '' - ) - localAuthKey = localkey.localizeKeyMD5( - hashedAuthPassphrase, snmpEngineID - ) - elif authProtocol == usmHMACSHAAuthProtocol: - hashedAuthPassphrase = localkey.hashPassphraseSHA( - authKey and authKey or '' - ) - localAuthKey = localkey.localizeKeySHA( - hashedAuthPassphrase, snmpEngineID - ) - elif authProtocol == usmNoAuthProtocol: - hashedAuthPassphrase = localAuthKey = None - else: - raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,)) - - if privProtocol == usmDESPrivProtocol or \ - privProtocol == usmAesCfb128Protocol: - if authProtocol == usmHMACMD5AuthProtocol: - hashedPrivPassphrase = localkey.hashPassphraseMD5( - privKey and privKey or '' - ) - localPrivKey = localkey.localizeKeyMD5( - hashedPrivPassphrase, snmpEngineID - ) - elif authProtocol == usmHMACSHAAuthProtocol: - hashedPrivPassphrase = localkey.hashPassphraseSHA( - privKey and privKey or '' - ) - localPrivKey = localkey.localizeKeySHA( - hashedPrivPassphrase, snmpEngineID - ) - else: - raise error.PySnmpError( - 'Unknown auth protocol %s' % (authProtocol,) - ) - elif privProtocol == usmNoPrivProtocol: - hashedPrivPassphrase = localPrivKey = None - else: - raise error.PySnmpError( - 'Unknown priv protocol %s' % (privProtocol,) - ) - - # Commit localized keys - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((pysnmpUsmKeyEntry.name + (1,) + tblIdx1, localAuthKey), - (pysnmpUsmKeyEntry.name + (2,) + tblIdx1, localPrivKey), - (pysnmpUsmKeyEntry.name + (3,) + tblIdx1, hashedAuthPassphrase), - (pysnmpUsmKeyEntry.name + (4,) + tblIdx1, hashedPrivPassphrase)) - ) - - # Commit passphrases - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo'), - (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey), - (pysnmpUsmSecretEntry.name + (3,) + tblIdx2, privKey),) - ) - -def delV3User(snmpEngine, securityName, contextEngineId=None): - ( snmpEngineID, usmUserEntry, tblIdx1, - pysnmpUsmSecretEntry, tblIdx2 ) = __cookV3UserInfo( - snmpEngine, securityName, contextEngineId - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) - ) - -def __cookTargetParamsInfo(snmpEngine, name): - snmpTargetParamsEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') - tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) - return snmpTargetParamsEntry, tblIdx - -def addTargetParams( - snmpEngine, - name, - securityName, - securityLevel, - mpModel=3 # 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 - ): - if mpModel == 0: - securityModel = 1 - elif mpModel == 1 or mpModel == 2: - securityModel = 2 - elif mpModel == 3: - securityModel = 3 - else: - raise error.PySnmpError('Unknown MP model %s' % mpModel) - - snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo'), - (snmpTargetParamsEntry.name + (1,) + tblIdx, name), - (snmpTargetParamsEntry.name + (2,) + tblIdx, mpModel), - (snmpTargetParamsEntry.name + (3,) + tblIdx, securityModel), - (snmpTargetParamsEntry.name + (4,) + tblIdx, securityName), - (snmpTargetParamsEntry.name + (5,) + tblIdx, securityLevel)) - ) - -def delTargetParams(snmpEngine, name): - snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo( - snmpEngine, name - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) - ) - -def __cookTargetAddrInfo(snmpEngine, addrName): - snmpTargetAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') - tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) - return snmpTargetAddrEntry, tblIdx - -def addTargetAddr( - snmpEngine, - addrName, - transportDomain, - transportAddress, - params, - timeout=None, - retryCount=None, - tagList='' - ): - snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo( - snmpEngine, addrName - ) - - if transportDomain == snmpUDPDomain: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') - transportAddress = SnmpUDPAddress(transportAddress) - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo'), - (snmpTargetAddrEntry.name + (1,) + tblIdx, addrName), - (snmpTargetAddrEntry.name + (2,) + tblIdx, transportDomain), - (snmpTargetAddrEntry.name + (3,) + tblIdx, transportAddress), - (snmpTargetAddrEntry.name + (4,) + tblIdx, timeout), - (snmpTargetAddrEntry.name + (5,) + tblIdx, retryCount), - # XXX - (snmpTargetAddrEntry.name + (6,) + tblIdx,'%s %s'%(addrName,tagList)), - (snmpTargetAddrEntry.name + (7,) + tblIdx, params),) - ) - -def delTargetAddr(snmpEngine, addrName): - snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo( - snmpEngine, addrName - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) - ) - -def addSocketTransport(snmpEngine, transportDomain, transport): - """Add transport object to socket dispatcher of snmpEngine""" - if not snmpEngine.transportDispatcher: - snmpEngine.registerTransportDispatcher(dispatch.AsynsockDispatcher()) - snmpEngine.transportDispatcher.registerTransport( - transportDomain, transport - ) - -def delSocketTransport(snmpEngine, transportDomain): - """Unregister transport object at socket dispatcher of snmpEngine""" - if not snmpEngine.transportDispatcher: - return - snmpEngine.transportDispatcher.unregisterTransport( - transportDomain - ) - snmpEngine.unregisterTransportDispatcher() - -# VACM shortcuts - -def addContext(snmpEngine, contextName): - vacmContextEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry' - ) - tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmContextEntry.name + (1,) + tblIdx, contextName),) - ) - -def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): - vacmSecurityToGroupEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' - ) - tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( - securityModel, securityName - ) - return vacmSecurityToGroupEntry, tblIdx - -def addVacmGroup(snmpEngine, groupName, securityModel, securityName): - vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( - snmpEngine, securityModel, securityName - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo'), - (vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), - (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), - (vacmSecurityToGroupEntry.name + (3,) + tblIdx, groupName),) - ) - -def delVacmGroup(snmpEngine, securityModel, securityName): - vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( - snmpEngine, securityModel, securityName - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) - ) - -def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, - securityLevel): - vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' - ) - tblIdx = vacmAccessEntry.getInstIdFromIndices( - groupName, contextName, securityModel, securityLevel - ) - return vacmAccessEntry, tblIdx - -def addVacmAccess(snmpEngine, groupName, contextName, securityModel, - securityLevel, prefix, readView, writeView, notifyView): - vacmAccessEntry, tblIdx = __cookVacmAccessInfo( - snmpEngine, groupName, contextName, securityModel, securityLevel - ) - - addContext(snmpEngine, contextName) # this is leaky - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo'), - (vacmAccessEntry.name + (1,) + tblIdx, contextName), - (vacmAccessEntry.name + (2,) + tblIdx, securityModel), - (vacmAccessEntry.name + (3,) + tblIdx, securityLevel), - (vacmAccessEntry.name + (4,) + tblIdx, prefix), - (vacmAccessEntry.name + (5,) + tblIdx, readView), - (vacmAccessEntry.name + (6,) + tblIdx, writeView), - (vacmAccessEntry.name + (7,) + tblIdx, notifyView),) - ) - -def delVacmAccess(snmpEngine, groupName, contextName, securityModel, - securityLevel): - vacmAccessEntry, tblIdx = __cookVacmAccessInfo( - snmpEngine, groupName, contextName, securityModel, securityLevel - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) - ) - -def __cookVacmViewInfo(snmpEngine, viewName, subTree): - vacmViewTreeFamilyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' - ) - tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices( - viewName, subTree - ) - return vacmViewTreeFamilyEntry, tblIdx - -def addVacmView(snmpEngine, viewName, viewType, subTree, mask): - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( - snmpEngine, viewName, subTree - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo'), - (vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), - (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), - (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, mask), - (vacmViewTreeFamilyEntry.name + (4,) + tblIdx, viewType),) - ) - -def delVacmView(snmpEngine, viewName, subTree): - vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( - snmpEngine, viewName, subTree - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) - ) - -# VACM simplicity wrappers - -def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): - groupName = 'v-%s-%d' % (hash(securityName), securityModel) - SnmpSecurityLevel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') - securityLevel = SnmpSecurityLevel(securityLevel) - return ( groupName, securityLevel, - 'r' + groupName, 'w' + groupName, 'n' + groupName ) - -def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, - readSubTree=(), writeSubTree=(), notifySubTree=()): - ( groupName, securityLevel, - readView, writeView, notifyView ) = __cookVacmUserInfo( - snmpEngine, securityModel, securityName, securityLevel, - ) - addVacmGroup( - snmpEngine, groupName, securityModel, securityName - ) - addVacmAccess( - snmpEngine, groupName, '', securityModel, securityLevel, 1, - readView, writeView, notifyView - ) - if readSubTree: - addVacmView( - snmpEngine, readView, "included", readSubTree, '', - ) - if writeSubTree: - addVacmView( - snmpEngine, writeView, "included", writeSubTree, '', - ) - if notifySubTree: - addVacmView( - snmpEngine, notifyView, "included", notifySubTree, '', - ) - -def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, - readSubTree=(), writeSubTree=(), notifySubTree=()): - ( groupName, securityLevel, - readView, writeView, notifyView ) = __cookVacmUserInfo( - snmpEngine, securityModel, securityName, securityLevel, - ) - delVacmGroup( - snmpEngine, securityModel, securityName - ) - delVacmAccess( - snmpEngine, groupName, '', securityModel, securityLevel - ) - if readSubTree: - delVacmView( - snmpEngine, readView, readSubTree - ) - if writeSubTree: - delVacmView( - snmpEngine, writeView, writeSubTree - ) - if notifySubTree: - delVacmView( - snmpEngine, notifyView, notifySubTree - ) - -# Obsolete shortcuts for add/delVacmUser() wrappers - -def addRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - addVacmUser( - snmpEngine, securityModel, securityName, securityLevel, subTree - ) - -def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - delVacmUser( - snmpEngine, securityModel, securityName, securityLevel, subTree - ) - -def addRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - addVacmUser( - snmpEngine, securityModel, securityName, securityLevel, - subTree, subTree - ) - -def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): - delVacmUser( - snmpEngine, securityModel, securityName, securityLevel, - subTree, subTree - ) - -def addTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): - addVacmUser( - snmpEngine, securityModel, securityName, securityLevel, - (), (), subTree, - ) - -def delTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): - delVacmUser( - snmpEngine, securityModel, securityName, securityLevel, - (), (), subTree, - ) - -# Notification target setup - -def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, - filterSubtree=None): - snmpNotifyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') - tblIdx1 = snmpNotifyEntry.getInstIdFromIndices( - notificationName - ) - - snmpNotifyFilterProfileEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') - tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices( - paramsName - ) - - profileName = '%s-filter' % hash(notificationName) - - if filterSubtree: - snmpNotifyFilterEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') - tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices( - profileName, filterSubtree - ) - else: - snmpNotifyFilterEntry = tblIdx3 = None - - return ( snmpNotifyEntry, tblIdx1, - snmpNotifyFilterProfileEntry, tblIdx2, profileName, - snmpNotifyFilterEntry, tblIdx3 ) - -def addNotificationTarget(snmpEngine, notificationName, paramsName, - transportTag, notifyType=None, filterSubtree=None, - filterMask=None, filterType=None): - ( snmpNotifyEntry, tblIdx1, - snmpNotifyFilterProfileEntry, tblIdx2, profileName, - snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( - snmpEngine, notificationName, paramsName, filterSubtree - ) - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyEntry.name + (5,) + tblIdx1, 'createAndGo'), - (snmpNotifyEntry.name + (2,) + tblIdx1, transportTag), - (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType),) - ) - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'createAndGo'), - (snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName),) - ) - - if not snmpNotifyFilterEntry: - return - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) - ) - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo'), - (snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), - (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), - (snmpNotifyFilterEntry.name + (3,) + tblIdx3, filterType),) - ) - -def delNotificationTarget(snmpEngine, notificationName, paramsName, - filterSubtree=None): - ( snmpNotifyEntry, tblIdx1, - snmpNotifyFilterProfileEntry, tblIdx2, profileName, - snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( - snmpEngine, notificationName, paramsName, filterSubtree - ) - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) - ) - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) - ) - - if not snmpNotifyFilterEntry: - return - - snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( - ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) - ) - -# rfc3415: A.1 -def setInitialVacmParameters(snmpEngine): - # rfc3415: A.1.1 --> initial-semi-security-configuration - - # rfc3415: A.1.2 - addContext(snmpEngine, "") - - # rfc3415: A.1.3 - addVacmGroup(snmpEngine, "initial", 3, "initial") - - # rfc3415: A.1.4 - addVacmAccess(snmpEngine, "initial", "", 3, "noAuthNoPriv", "exact", - "restricted", None, "restricted") - addVacmAccess(snmpEngine, "initial", "", 3, "authNoPriv", "exact", - "internet", "internet", "internet") - addVacmAccess(snmpEngine, "initial", "", 3, "authPriv", "exact", - "internet", "internet", "internet") - - # rfc3415: A.1.5 (semi-secure) - addVacmView(snmpEngine, "internet", "included", (1,3,6,1),"") - addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,2,1,1),"") - addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,2,1,11),"") - addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,10,2,1),"") - addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,11,2,1),"") - addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,15,1,1),"") diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/engine.py python-pysnmp4-4.2.2/pysnmp/v4/entity/engine.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/engine.py 2006-09-20 16:26:13.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/engine.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -# SNMP engine -from pysnmp.proto.rfc3412 import MsgAndPduDispatcher -from pysnmp.proto.mpmod.rfc2576 import SnmpV1MessageProcessingModel, \ - SnmpV2cMessageProcessingModel -from pysnmp.proto.mpmod.rfc3412 import SnmpV3MessageProcessingModel -from pysnmp.proto.secmod.rfc2576 import SnmpV1SecurityModel, \ - SnmpV2cSecurityModel -from pysnmp.proto.secmod.rfc3414 import SnmpUSMSecurityModel -from pysnmp.proto.acmod import rfc3415 -from pysnmp import error - -class SnmpEngine: - def __init__(self, snmpEngineID=None, maxMessageSize=65507): - self.msgAndPduDsp = MsgAndPduDispatcher() - self.messageProcessingSubsystems = { - SnmpV1MessageProcessingModel.messageProcessingModelID: - SnmpV1MessageProcessingModel(), - SnmpV2cMessageProcessingModel.messageProcessingModelID: - SnmpV2cMessageProcessingModel(), - SnmpV3MessageProcessingModel.messageProcessingModelID: - SnmpV3MessageProcessingModel() - } - self.securityModels = { - SnmpV1SecurityModel.securityModelID: SnmpV1SecurityModel(), - SnmpV2cSecurityModel.securityModelID: SnmpV2cSecurityModel(), - SnmpUSMSecurityModel.securityModelID: SnmpUSMSecurityModel() - } - self.accessControlModel = { - rfc3415.accessModelID: rfc3415 - } - - self.transportDispatcher = None - - if self.msgAndPduDsp.mibInstrumController is None: - raise error.PySnmpError( - 'MIB instrumentation does not yet exist' - ) - snmpEngineMaxMessageSize, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') - snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize) - snmpEngineBoots, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots') - snmpEngineBoots.syntax = snmpEngineBoots.syntax + 1 - if snmpEngineID is not None: - origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) - - # Transport dispatcher bindings - - def __receiveMessageCbFun( - self, - transportDispatcher, - transportDomain, - transportAddress, - wholeMsg - ): - self.msgAndPduDsp.receiveMessage( - self, transportDomain, transportAddress, wholeMsg - ) - - def __receiveTimerTickCbFun(self, timeNow): - self.msgAndPduDsp.receiveTimerTick(self, timeNow) - for mpHandler in self.messageProcessingSubsystems.values(): - mpHandler.receiveTimerTick(self, timeNow) - for smHandler in self.securityModels.values(): - smHandler.receiveTimerTick(self, timeNow) - - def registerTransportDispatcher(self, transportDispatcher): - if self.transportDispatcher is not None: - raise error.ProtocolError( - 'Transport dispatcher already registered' - ) - transportDispatcher.registerRecvCbFun( - self.__receiveMessageCbFun - ) - transportDispatcher.registerTimerCbFun( - self.__receiveTimerTickCbFun - ) - self.transportDispatcher = transportDispatcher - - def unregisterTransportDispatcher(self): - if self.transportDispatcher is None: - raise error.ProtocolError( - 'Transport dispatcher not registered' - ) - self.transportDispatcher.unregisterRecvCbFun() - self.transportDispatcher.unregisterTimerCbFun() - self.transportDispatcher = None diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/cmdgen.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/cmdgen.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/cmdgen.py 2007-11-23 10:26:44.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/cmdgen.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,558 +0,0 @@ -import types, time -from pysnmp.proto import rfc1157, rfc1905, api -from pysnmp.entity.rfc3413 import config -from pysnmp.proto.proxy import rfc2576 -from pysnmp.proto import error - -def getVersionSpecifics(snmpVersion): - if snmpVersion == 0: - pduVersion = 0 - else: - pduVersion = 1 - return pduVersion, api.protoModules[pduVersion] - -class CommandGeneratorBase: - def __init__(self): - self.__pendingReqs = {} - self._sendRequestHandleSource = 0L - - def processResponsePdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - statusInformation, - sendPduHandle, - (cbFun, cbCtx) - ): - # 3.1.1 - ( origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPduVersion, - origPdu, - origTimeout, - origRetryCount, - origRetries, - origSendRequestHandle - ) = self.__pendingReqs[sendPduHandle] - del self.__pendingReqs[sendPduHandle] - - snmpEngine.transportDispatcher.jobFinished(id(self)) - - # 3.1.3 - if statusInformation: - if origRetries == origRetryCount: - cbFun(origSendRequestHandle, - statusInformation['errorIndication'], 0, 0, (), - cbCtx) - return - self._sendPdu( - snmpEngine, - origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPduVersion, - origPdu, - origTimeout, - origRetryCount, - origRetries, - origSendRequestHandle, - (self.processResponsePdu, (cbFun, cbCtx)) - ) - return - - if origMessageProcessingModel != messageProcessingModel or \ - origSecurityModel != securityModel or \ - origSecurityName != origSecurityName or \ - origContextEngineId and origContextEngineId != contextEngineId or \ - origContextName and origContextName != contextName or \ - origPduVersion != pduVersion: - return - - pMod = api.protoModules[pduVersion] - - # 3.1.2 - if pMod.apiPDU.getRequestID(PDU) != pMod.apiPDU.getRequestID(origPdu): - return - - # User-side API assumes SMIv2 - if messageProcessingModel == 0: - PDU = rfc2576.v1ToV2(PDU, origPdu) - pMod = api.protoModules[api.protoVersion2c] - - self._handleResponse( - snmpEngine, - origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPduVersion, - origPdu, - origTimeout, - origRetryCount, - pMod, - PDU, - origSendRequestHandle, - (cbFun, cbCtx), - ) - - def sendReq( - self, - snmpEngine, - addrName, - varBinds, - cbFun, - cbCtx=None, - contextEngineId=None, - contextName='' - ): - raise error.ProtocolError('Method not implemented') - - def _sendPdu( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - timeout, - retryCount, - retries, - sendRequestHandle, - (processResponsePdu, cbCtx) - ): - # 3.1 - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - (processResponsePdu, float(timeout)/100 + time.time(), cbCtx) - ) - - snmpEngine.transportDispatcher.jobStarted(id(self)) - - self.__pendingReqs[sendPduHandle] = ( - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - timeout, - retryCount, - retries + 1, - sendRequestHandle, - ) - -class GetCommandGenerator(CommandGeneratorBase): - def sendReq( - self, - snmpEngine, - addrName, - varBinds, - cbFun, - cbCtx=None, - contextEngineId=None, - contextName='' - ): - ( transportDomain, - transportAddress, - timeout, - retryCount, - messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetInfo(snmpEngine, addrName) - - pduVersion, pMod = getVersionSpecifics(messageProcessingModel) - - reqPDU = pMod.GetRequestPDU() - pMod.apiPDU.setDefaults(reqPDU) - - pMod.apiPDU.setVarBinds(reqPDU, varBinds) - - self._sendRequestHandleSource = self._sendRequestHandleSource + 1 - - self._sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - timeout, - retryCount, - 0, - self._sendRequestHandleSource, - (self.processResponsePdu, (cbFun, cbCtx)) - ) - - return self._sendRequestHandleSource - - def _handleResponse( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - timeout, - retryCount, - pMod, - rspPDU, - sendRequestHandle, - (cbFun, cbCtx) - ): - cbFun(sendRequestHandle, - None, - pMod.apiPDU.getErrorStatus(rspPDU), - pMod.apiPDU.getErrorIndex(rspPDU), - pMod.apiPDU.getVarBinds(rspPDU), - cbCtx) - -class SetCommandGenerator(CommandGeneratorBase): - def sendReq( - self, - snmpEngine, - addrName, - varBinds, - cbFun, - cbCtx=None, - contextEngineId=None, - contextName='' - ): - ( transportDomain, - transportAddress, - timeout, - retryCount, - messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetInfo(snmpEngine, addrName) - - pduVersion, pMod = getVersionSpecifics(messageProcessingModel) - - reqPDU = pMod.SetRequestPDU() - pMod.apiPDU.setDefaults(reqPDU) - - pMod.apiPDU.setVarBinds(reqPDU, varBinds) - - # User-side API assumes SMIv2 - if messageProcessingModel == 0: - reqPDU = rfc2576.v2ToV1(reqPDU) - pMod = api.protoModules[api.protoVersion1] - - self._sendRequestHandleSource = self._sendRequestHandleSource + 1 - - self._sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - timeout, - retryCount, - 0, - self._sendRequestHandleSource, - (self.processResponsePdu, (cbFun, cbCtx)) - ) - - return self._sendRequestHandleSource - - def _handleResponse( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - timeout, - retryCount, - pMod, - rspPDU, - sendRequestHandle, - (cbFun, cbCtx) - ): - cbFun(sendRequestHandle, - None, - pMod.apiPDU.getErrorStatus(rspPDU), - pMod.apiPDU.getErrorIndex(rspPDU), - pMod.apiPDU.getVarBinds(rspPDU), - cbCtx) - -class NextCommandGenerator(CommandGeneratorBase): - def sendReq( - self, - snmpEngine, - addrName, - varBinds, - cbFun, - cbCtx=None, - contextEngineId=None, - contextName='' - ): - ( transportDomain, - transportAddress, - timeout, - retryCount, - messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetInfo(snmpEngine, addrName) - - pduVersion, pMod = getVersionSpecifics(messageProcessingModel) - - reqPDU = pMod.GetNextRequestPDU() - pMod.apiPDU.setDefaults(reqPDU) - - pMod.apiPDU.setVarBinds(reqPDU, varBinds) - - self._sendRequestHandleSource = self._sendRequestHandleSource + 1 - - self._sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - timeout, - retryCount, - 0, - self._sendRequestHandleSource, - (self.processResponsePdu, (cbFun, cbCtx)) - ) - - return self._sendRequestHandleSource - - def _handleResponse( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - timeout, - retryCount, - pMod, - rspPDU, - sendRequestHandle, - (cbFun, cbCtx) - ): - varBindTable = pMod.apiPDU.getVarBindTable(PDU, rspPDU) - - if not cbFun(sendRequestHandle, None, - pMod.apiPDU.getErrorStatus(rspPDU), - pMod.apiPDU.getErrorIndex(rspPDU), - varBindTable, cbCtx): - return # app says enough - - pMod.apiPDU.setRequestID(PDU, pMod.getNextRequestID()) - pMod.apiPDU.setVarBinds( - PDU, map(lambda (x,y),n=pMod.Null(''): (x,n), varBindTable[-1]) - ) - - self._sendRequestHandleSource = self._sendRequestHandleSource + 1 - - self._sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - timeout, - retryCount, - 0, - self._sendRequestHandleSource, - (self.processResponsePdu, (cbFun, cbCtx)) - ) - -class BulkCommandGenerator(CommandGeneratorBase): - def sendReq( - self, - snmpEngine, - addrName, - nonRepeaters, - maxRepetitions, - varBinds, - cbFun, - cbCtx=None, - contextEngineId=None, - contextName='' - ): - ( transportDomain, - transportAddress, - timeout, - retryCount, - messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetInfo(snmpEngine, addrName) - - pduVersion, pMod = getVersionSpecifics(messageProcessingModel) - - if not hasattr(pMod, 'GetBulkRequestPDU'): - raise error.ProtocolError('BULK PDU not implemented at %s' % pMod) - reqPDU = pMod.GetBulkRequestPDU() - pMod.apiBulkPDU.setDefaults(reqPDU) - - pMod.apiBulkPDU.setNonRepeaters(reqPDU, nonRepeaters) - pMod.apiBulkPDU.setMaxRepetitions(reqPDU, maxRepetitions) - - pMod.apiBulkPDU.setVarBinds(reqPDU, varBinds) - - self._sendRequestHandleSource = self._sendRequestHandleSource + 1 - - self._sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - reqPDU, - timeout, - retryCount, - 0, - self._sendRequestHandleSource, - (self.processResponsePdu, (cbFun, cbCtx)) - ) - - return self._sendRequestHandleSource - - def _handleResponse( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - timeout, - retryCount, - pMod, - rspPDU, - sendRequestHandle, - (cbFun, cbCtx) - ): - varBindTable = pMod.apiBulkPDU.getVarBindTable(PDU, rspPDU) - - if not cbFun(sendRequestHandle, None, - pMod.apiBulkPDU.getErrorStatus(rspPDU), - pMod.apiBulkPDU.getErrorIndex(rspPDU), - varBindTable, cbCtx): - return # app says enough - - pMod.apiBulkPDU.setRequestID(PDU, pMod.getNextRequestID()) - pMod.apiBulkPDU.setVarBinds( - PDU, map(lambda (x,y),n=pMod.Null(''): (x,n), varBindTable[-1]) - ) - - self._sendRequestHandleSource = self._sendRequestHandleSource + 1 - - self._sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - timeout, - retryCount, - 0, - self._sendRequestHandleSource, - (self.processResponsePdu, (cbFun, cbCtx)) - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/cmdrsp.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/cmdrsp.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/cmdrsp.py 2007-08-29 05:57:16.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/cmdrsp.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,289 +0,0 @@ -from pysnmp.proto import rfc1157, rfc1905, rfc3411, error -from pysnmp.proto.api import v2c # backend is always SMIv2 compliant -from pysnmp.proto.proxy import rfc2576 -import pysnmp.smi.error - -vacmID = 3 - -# 3.2 -class CommandResponderBase: - pduTypes = () - - def __init__(self, snmpEngine, snmpContext): - snmpEngine.msgAndPduDsp.registerContextEngineId( - snmpContext.contextEngineId, self.pduTypes, self.processPdu - ) - self.snmpContext = snmpContext # for unregistration - self.__pendingReqs = {} - - def _handleManagementOperation( - self, snmpEngine, contextMibInstrumCtl, PDU, (acFun, acCtx) - ): pass - - def close(self, snmpEngine): - snmpEngine.msgAndPduDsp.unregisterContextEngineId( - self.snmpContext.contextEngineId, self.pduTypes - ) - - def __sendResponse(self, snmpEngine, errorStatus, errorIndex, - varBinds, stateReference): - ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - statusInformation ) = self.__pendingReqs[stateReference] - - del self.__pendingReqs[stateReference] - - v2c.apiPDU.setErrorStatus(PDU, errorStatus) - v2c.apiPDU.setErrorIndex(PDU, errorIndex) - v2c.apiPDU.setVarBinds(PDU, varBinds) - - # Agent-side API complies with SMIv2 - if messageProcessingModel == 0: - PDU = rfc2576.v2ToV1(PDU) - - # 3.2.6 - try: - snmpEngine.msgAndPduDsp.returnResponsePdu( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) - except error.StatusInformation: - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') - snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 - - _getRequestType = rfc1905.GetRequestPDU.tagSet - _getNextRequestType = rfc1905.GetNextRequestPDU.tagSet - _setRequestType = rfc1905.SetRequestPDU.tagSet - - def processPdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference - ): - - # Agent-side API complies with SMIv2 - if messageProcessingModel == 0: - PDU = rfc2576.v1ToV2(PDU) - - # 3.2.1 - if rfc3411.readClassPDUs.has_key(PDU.tagSet): - viewType = 'read' - elif rfc3411.writeClassPDUs.has_key(PDU.tagSet): - viewType = 'write' - else: - raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) - - # 3.2.2 --> no-op - - # 3.2.4 - rspPDU = v2c.apiPDU.getResponse(PDU) - - statusInformation = {} - - self.__pendingReqs[stateReference] = ( - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - rspPDU, - maxSizeResponseScopedPDU, - statusInformation - ) - - contextMibInstrumCtl = self.snmpContext.getMibInstrum(contextName) - - acCtx = ( - snmpEngine, securityModel, securityName, securityLevel, contextName - ) - - # 3.2.5 - varBinds = v2c.apiPDU.getVarBinds(PDU) - errorStatus, errorIndex = 'noError', 0 - try: - errorStatus, errorIndex, varBinds = self._handleManagementOperation( - snmpEngine, contextMibInstrumCtl, PDU, - (self.__verifyAccess, acCtx) - ) - # SNMPv2 SMI exceptions - except pysnmp.smi.error.GenError, errorIndication: - if errorIndication.has_key('oid'): - # Request REPORT generation - statusInformation['oid'] = errorIndication['oid'] - 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: - errorStatus, errorIndex = 'genErr', errorIndication['idx'] + 1 - - self.__sendResponse( - snmpEngine, errorStatus, errorIndex, varBinds, stateReference - ) - - def __verifyAccess(self, name, idx, viewType, - (snmpEngine, securityModel, securityName, - securityLevel, contextName) - ): - try: - snmpEngine.accessControlModel[vacmID].isAccessAllowed( - snmpEngine, securityModel, securityName, - securityLevel, viewType, contextName, name - ) - # Map ACM errors onto SMI ones - except error.StatusInformation, statusInformation: - errorIndication = statusInformation['errorIndication'] - # 3.2.5... - if errorIndication == 'noSuchView' or \ - errorIndication == 'noAccessEntry' or \ - errorIndication == 'noGroupName': - raise pysnmp.smi.error.AuthorizationError( - name=name, idx=idx - ) - elif errorIndication == 'otherError': - raise pysnmp.smi.error.GenError(name=name, idx=idx) - elif errorIndication == 'noSuchContext': - snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-TARGET-MIB', 'snmpUnknownContexts') - snmpUnknownContexts.syntax = snmpUnknownContexts.syntax + 1 - # Request REPORT generation - raise pysnmp.smi.error.GenError( - name=name, idx=idx, - oid=snmpUnknownContexts.name, - val=snmpUnknownContexts.syntax - ) - elif errorIndication == 'notInView': - return 1 - else: - raise error.ProtocolError( - 'Unknown ACM error %s' % errorIndication - ) - -class GetCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.GetRequestPDU.tagSet, ) - - # rfc1905: 4.2.1 - def _handleManagementOperation( - self, snmpEngine, contextMibInstrumCtl, PDU, (acFun, acCtx) - ): - # rfc1905: 4.2.1.1 - return 0, 0, contextMibInstrumCtl.readVars( - v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) - ) - -class NextCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.GetNextRequestPDU.tagSet, ) - - # rfc1905: 4.2.2 - def _handleManagementOperation(self, snmpEngine, contextMibInstrumCtl, - PDU, (acFun, acCtx)): - # rfc1905: 4.2.1.1 - return 0, 0, contextMibInstrumCtl.readNextVars( - v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) - ) - -class BulkCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.GetBulkRequestPDU.tagSet, ) - maxVarBinds = 64 - - # rfc1905: 4.2.3 - def _handleManagementOperation(self, snmpEngine, contextMibInstrumCtl, - PDU, (acFun, acCtx)): - nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU) - if nonRepeaters < 0: - nonRepeaters = 0 - maxRepetitions = v2c.apiBulkPDU.getMaxRepetitions(PDU) - if maxRepetitions < 0: - maxRepetitions = 0 - reqVarBinds = v2c.apiPDU.getVarBinds(PDU) - - N = min(nonRepeaters, len(reqVarBinds)) - M = int(maxRepetitions) - R = max(len(reqVarBinds)-N, 0) - - if nonRepeaters: - rspVarBinds = contextMibInstrumCtl.readNextVars( - reqVarBinds[:int(nonRepeaters)], (acFun, acCtx) - ) - else: - rspVarBinds = [] - - if M and R: - for i in range(N, R): - varBind = reqVarBinds[i] - for r in range(1, M): - rspVarBinds.extend(contextMibInstrumCtl.readNextVars( - (varBind,), (acFun, acCtx) - )) - varBind = rspVarBinds[-1] - - if len(rspVarBinds) > self.maxVarBinds: - rspVarBinds = rspVarBinds[:self.maxVarBinds] - - return 0, 0, rspVarBinds - -class SetCommandResponder(CommandResponderBase): - pduTypes = ( rfc1905.SetRequestPDU.tagSet, ) - - # rfc1905: 4.2.5 - def _handleManagementOperation( - self, snmpEngine, contextMibInstrumCtl, PDU, (acFun, acCtx) - ): - # rfc1905: 4.2.5.1-13 - try: - return 0, 0, contextMibInstrumCtl.writeVars( - v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) - ) - except ( pysnmp.smi.error.NoSuchObjectError, - pysnmp.smi.error.NoSuchInstanceError ), errorIndication: - e = pysnmp.smi.error.NotWritableError() - e.update(errorIndication) - raise e diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/config.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/config.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/config.py 2006-10-01 19:26:32.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/config.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -# Shortcuts to MIB instrumentation items used internally in SNMP applications -import string -from pysnmp.smi.error import NoSuchObjectError -from pysnmp.entity import config - -def getVersionSpecifics(snmpVersion): pass - -def getTargetAddr(snmpEngine, snmpTargetAddrName): - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - # Transport endpoint - snmpTargetAddrEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry' - ) - tblIdx = snmpTargetAddrEntry.getInstIdFromIndices( - snmpTargetAddrName - ) - - ((v, snmpTargetAddrTDomain), - (v, snmpTargetAddrTAddress), - (v, snmpTargetAddrTimeout), - (v, snmpTargetAddrRetryCount), - (v, snmpTargetAddrParams)) = mibInstrumController.readVars( - ((snmpTargetAddrEntry.name + (2,) + tblIdx, None), - (snmpTargetAddrEntry.name + (3,) + tblIdx, None), - (snmpTargetAddrEntry.name + (4,) + tblIdx, None), - (snmpTargetAddrEntry.name + (5,) + tblIdx, None), - (snmpTargetAddrEntry.name + (7,) + tblIdx, None)) - ) - - if snmpTargetAddrTDomain == config.snmpUDPDomain: - SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') - snmpTargetAddrTAddress = tuple( - SnmpUDPAddress(snmpTargetAddrTAddress) - ) - - return ( snmpTargetAddrTDomain, - snmpTargetAddrTAddress, - snmpTargetAddrTimeout, - snmpTargetAddrRetryCount, - snmpTargetAddrParams ) - -def getTargetInfo(snmpEngine, snmpTargetAddrName): - # Transport endpoint - ( snmpTargetAddrTDomain, - snmpTargetAddrTAddress, - snmpTargetAddrTimeout, - snmpTargetAddrRetryCount, - snmpTargetAddrParams ) = getTargetAddr(snmpEngine, snmpTargetAddrName) - - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - - # Target params - snmpTargetParamsEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetParamsEntry' - ) - tblIdx = snmpTargetParamsEntry.getInstIdFromIndices( - snmpTargetAddrParams - ) - ((v, snmpTargetParamsMPModel), - (v, snmpTargetParamsSecurityModel), - (v, snmpTargetParamsSecurityName), - (v, snmpTargetParamsSecurityLevel)) = mibInstrumController.readVars( - ((snmpTargetParamsEntry.name + (2,) + tblIdx, None), - (snmpTargetParamsEntry.name + (3,) + tblIdx, None), - (snmpTargetParamsEntry.name + (4,) + tblIdx, None), - (snmpTargetParamsEntry.name + (5,) + tblIdx, None)) - ) - - return ( snmpTargetAddrTDomain, - snmpTargetAddrTAddress, - snmpTargetAddrTimeout, - snmpTargetAddrRetryCount, - snmpTargetParamsMPModel, - snmpTargetParamsSecurityModel, - snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel ) - -def getTargetParams(snmpEngine, paramsName): - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - snmpTargetParamsEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetParamsEntry' - ) - tblIdx = snmpTargetParamsEntry.getInstIdFromIndices( - paramsName - ) - ((v, snmpTargetParamsMPModel), - (v, snmpTargetParamsSecurityModel), - (v, snmpTargetParamsSecurityName), - (v, snmpTargetParamsSecurityLevel)) = mibInstrumController.readVars( - ((snmpTargetParamsEntry.name + (2,) + tblIdx, None), - (snmpTargetParamsEntry.name + (3,) + tblIdx, None), - (snmpTargetParamsEntry.name + (4,) + tblIdx, None), - (snmpTargetParamsEntry.name + (5,) + tblIdx, None)) - ) - - return ( snmpTargetParamsMPModel, - snmpTargetParamsSecurityModel, - snmpTargetParamsSecurityName, - snmpTargetParamsSecurityLevel ) - -def getNotificationInfo(snmpEngine, notificationTarget): - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - # Transport endpoint - snmpNotifyEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry' - ) - tblIdx = snmpNotifyEntry.getInstIdFromIndices( - notificationTarget - ) - ((v, snmpNotifyTag), - (v, snmpNotifyType)) = mibInstrumController.readVars( - ((snmpNotifyEntry.name + (2,) + tblIdx, None), - (snmpNotifyEntry.name + (3,) + tblIdx, None)) - ) - - return snmpNotifyTag, snmpNotifyType - -def getTargetNames(snmpEngine, tag): - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - # Transport endpoint - ( snmpTargetAddrEntry, - snmpTargetAddrTagList ) = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry', 'snmpTargetAddrTagList' - ) - targetNames = [] - nextName = snmpTargetAddrTagList.name - while 1: - try: - mibNode = snmpTargetAddrTagList.getNextNode(nextName) - except NoSuchObjectError: - break - # XXX stop on eot - if tag in string.split(str(mibNode.syntax)): # XXX add __split__() - idx = mibNode.name[len(snmpTargetAddrTagList.name):] - targetNames.append( - snmpTargetAddrEntry.getIndicesFromInstId(idx)[0] - ) - nextName = mibNode.name - return targetNames - -# XXX -# convert cmdrsp/cmdgen into this api diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/context.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/context.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/context.py 2006-05-21 11:36:23.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/context.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -# SNMP entity context -from pysnmp import error - -class SnmpContext: - def __init__(self, snmpEngine, contextEngineId=None): - if contextEngineId is None: - # Default to local snmpEngineId - contextEngineId,= snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - contextEngineId = contextEngineId.syntax - self.contextEngineId = contextEngineId - self.contextNames = { - '': snmpEngine.msgAndPduDsp.mibInstrumController # Default name - } - - def registerContextName(self, contextName, mibInstrum=None): - if self.contextNames.has_key(contextName): - raise error.PySnmpError( - 'Duplicate contextName %s' % contextName - ) - if mibInstrum is None: - self.contextNames[contextName] = self.contextNames[''] - else: - self.contextNames[contextName] = mibInstrum - - def unregisterContextName(self, contextName): - if self.contextNames.has_key(contextName): - del self.contextNames[contextName] - - def getMibInstrum(self, contextName): - if not self.contextNames.has_key(contextName): - raise error.PySnmpError( - 'Missing contextName %s' % contextName - ) - else: - return self.contextNames[contextName] diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/mibvar.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/mibvar.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/mibvar.py 2006-09-04 18:21:47.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/mibvar.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -# 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 modName: # load module if needed - mibView.mibBuilder.loadModules(modName) - else: - mibView.mibBuilder.loadModules() # load all (slow) - if symName: - oid, label, suffix = mibView.getNodeNameByDesc(symName, modName) - else: - oid, label, suffix = mibView.getFirstNodeName(modName) - suffix = name[1:] - modName, symName, _s = mibView.getNodeLocation(oid) - mibNode, = mibView.mibBuilder.importSymbols( - modName, symName - ) - 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) - else: # scalar or incomplete spec - return oid, suffix - else: - oid, label, suffix = mibView.getNodeNameByOid(name) - return oid, suffix - -__scalarSuffix = (univ.Integer(0),) - -def oidToMibName(mibView, oid): - _oid, label, suffix = mibView.getNodeNameByOid(tuple(oid)) - modName, symName, __suffix = mibView.getNodeLocation(_oid) - mibNode, = mibView.mibBuilder.importSymbols( - modName, symName - ) - if hasattr(mibNode, 'createTest'): # table column - __modName, __symName, __s = mibView.getNodeLocation(_oid[:-1]) - rowNode, = mibView.mibBuilder.importSymbols(__modName, __symName) - return (symName, modName), rowNode.getIndicesFromInstId(suffix) - elif not suffix: # scalar - return (symName, modName), suffix - elif suffix == (0,): # scalar - return (symName, modName), __scalarSuffix - else: - raise NoSuchObjectError( - str='No MIB info for %s (closest parent %s)' % - (oid, mibNode.name) - ) - -# Value - -def cloneFromMibValue(mibView, modName, symName, value): - mibNode, = mibView.mibBuilder.importSymbols( - modName, symName - ) - if hasattr(mibNode, 'syntax'): # scalar - return mibNode.syntax.clone(value) - else: - return # identifier diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/ntforg.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/ntforg.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/ntforg.py 2007-11-23 10:30:36.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/ntforg.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,255 +0,0 @@ -import time -try: - from sys import version_info -except ImportError: - version_info = ( 0, 0 ) # a really early version -from pysnmp.entity.rfc3413 import config -from pysnmp.proto.proxy import rfc2576 -from pysnmp.proto.api import v2c -from pysnmp.smi import error - -vacmID = 3 - -class NotificationOriginator: - def __init__(self, snmpContext): - self.__pendingReqs = {} - self.__sendRequestHandleSource = 0L - self.__context = snmpContext - - def processResponsePdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - statusInformation, - sendPduHandle, - (cbFun, cbCtx) - ): - # 3.3.6d - ( origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPduVersion, - origPdu, - origTimeout, - origRetryCount, - origRetries, - origSendRequestHandle - ) = self.__pendingReqs[sendPduHandle] - del self.__pendingReqs[sendPduHandle] - - snmpEngine.transportDispatcher.jobFinished(id(self)) - - if statusInformation: - if origRetries == origRetryCount: - cbFun(origSendRequestHandle, - statusInformation['errorIndication'], - cbCtx) - return - - # 3.3.6a - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( - snmpEngine, - origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPduVersion, - origPdu, - (self.processResponsePdu, float(origTimeout)/100 + time.time(), - (cbFun, cbCtx)) - ) - - snmpEngine.transportDispatcher.jobStarted(id(self)) - - # 3.3.6b - self.__pendingReqs[sendPduHandle] = ( - origTransportDomain, - origTransportAddress, - origMessageProcessingModel, - origSecurityModel, - origSecurityName, - origSecurityLevel, - origContextEngineId, - origContextName, - origPduVersion, - origPdu, - origTimeout, - origRetryCount, - origRetries + 1, - sendPduHandle - ) - return - - # 3.3.6c - cbFun(origSendRequestHandle, None, cbCtx) - - def sendNotification( - self, - snmpEngine, - notificationTarget, - notificationName, - additionalVarBinds=None, - cbFun=None, - cbCtx=None, - contextName='' - ): - # 3.3 - ( notifyTag, - notifyType ) = config.getNotificationInfo( - snmpEngine, notificationTarget - ) - contextMibInstrumCtl = self.__context.getMibInstrum( - contextName - ) - for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): - ( transportDomain, - transportAddress, - timeout, - retryCount, - params ) = config.getTargetAddr(snmpEngine, targetAddrName) - ( messageProcessingModel, - securityModel, - securityName, - securityLevel ) = config.getTargetParams(snmpEngine, params) - - # 3.3.1 XXX -# XXX filtering's yet to be implemented -# filterProfileName = config.getNotifyFilterProfile(params) - -# ( filterSubtree, -# filterMask, -# filterType ) = config.getNotifyFilter(filterProfileName) - - varBinds = [] - - # 3.3.2 & 3.3.3 - sysUpTime, = contextMibInstrumCtl.mibBuilder.importSymbols( - '__SNMPv2-MIB', 'sysUpTime' - ) - varBinds.append((sysUpTime.name, sysUpTime.syntax)) - - snmpTrapOid, = contextMibInstrumCtl.mibBuilder.importSymbols( - '__SNMPv2-MIB', 'snmpTrapOID' - ) - if notificationName: - varBinds.append((snmpTrapOid.name, snmpTrapOid.syntax.clone(notificationName))) - else: - varBinds.append((snmpTrapOid.name, snmpTrapOid.syntax)) - -# 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 -# ) -# try: -# objectInstance = mibNode.getNode(mibNode.name + (0,)) -# except error.SmiError: -# return -# varBinds.append((objectInstance.name, objectInstance.syntax)) - - if additionalVarBinds: - if version_info < (1, 6): - additionalVarBinds = list(additionalVarBinds) - varBinds.extend(additionalVarBinds) - - for varName, varVal in varBinds: - try: - snmpEngine.accessControlModel[vacmID].isAccessAllowed( - snmpEngine, securityModel, securityName, - securityLevel, 'notify', contextName, varName - ) - except error.SmiError: - return - - # 3.3.4 - if notifyType == 1: - pdu = v2c.SNMPv2TrapPDU() - elif notifyType == 2: - pdu = v2c.InformRequestPDU() - else: - raise RuntimeError() - v2c.apiPDU.setDefaults(pdu) - v2c.apiPDU.setVarBinds(pdu, varBinds) - - # User-side API assumes SMIv2 - if messageProcessingModel == 0: - pdu = rfc2576.v2ToV1(pdu) - pduVersion = 0 - else: - pduVersion = 1 - - # 3.3.5 - if notifyType == 1: - snmpEngine.msgAndPduDsp.sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - self.__context.contextEngineId, - contextName, - pduVersion, - pdu, - None - ) - else: - # 3.3.6a - sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - self.__context.contextEngineId, - contextName, - pduVersion, - pdu, - (self.processResponsePdu, float(timeout)/100 + time.time(), - (cbFun, cbCtx)) - ) - - # 3.3.6b - self.__pendingReqs[sendPduHandle] = ( - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - self.__context.contextEngineId, - contextName, - pduVersion, - pdu, - timeout, - retryCount, - 1, - self.__sendRequestHandleSource - ) - - snmpEngine.transportDispatcher.jobStarted(id(self)) - -# XXX -# move/group/implement config setting/retrieval at a stand-alone module - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/ntfrcv.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/ntfrcv.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/ntfrcv.py 2006-05-21 11:37:54.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/ntfrcv.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -from pysnmp.proto import rfc3411, error -from pysnmp.proto.api import v1, v2c # backend is always SMIv2 compliant -from pysnmp.proto.proxy import rfc2576 - -# 3.4 -class NotificationReceiver: - pduTypes = ( - v1.TrapPDU.tagSet, - v2c.SNMPv2TrapPDU.tagSet, - v2c.InformRequestPDU.tagSet - ) - - def __init__(self, snmpEngine, cbFun, cbCtx=None): - snmpEngine.msgAndPduDsp.registerContextEngineId( - '', self.pduTypes, self.processPdu # '' is a wildcard - ) - self.__cbFun = cbFun - self.__cbCtx = cbCtx - - def close(self, snmpEngine): - snmpEngine.msgAndPduDsp.unregisterContextEngineId( - '', self.pduTypes - ) - - def processPdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference - ): - - # Agent-side API complies with SMIv2 - if messageProcessingModel == 0: - PDU = rfc2576.v1ToV2(PDU) - - errorStatus = 'noError'; errorIndex = 0 - varBinds = v2c.apiPDU.getVarBinds(PDU) - - # 3.4 - if rfc3411.confirmedClassPDUs.has_key(PDU.tagSet): - # 3.4.1 --> no-op - - rspPDU = v2c.apiPDU.getResponse(PDU) - - # 3.4.2 - v2c.apiPDU.setErrorStatus(rspPDU, errorStatus) - v2c.apiPDU.setErrorIndex(rspPDU, errorIndex) - v2c.apiPDU.setVarBinds(rspPDU, varBinds) - - # Agent-side API complies with SMIv2 - if messageProcessingModel == 0: - rspPDU = rfc2576.v2ToV1(rspPDU) - - statusInformation = {} - - # 3.4.3 - try: - snmpEngine.msgAndPduDsp.returnResponsePdu( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - rspPDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) - except error.StatusInformation: - snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') - snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 - - elif rfc3411.unconfirmedClassPDUs.has_key(PDU.tagSet): - pass - else: - raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) - - self.__cbFun( - snmpEngine, contextEngineId, contextName, varBinds, self.__cbCtx - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/oneliner/cmdgen.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/oneliner/cmdgen.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/oneliner/cmdgen.py 2007-11-26 09:33:27.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/oneliner/cmdgen.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,421 +0,0 @@ -import socket, string, types -from pysnmp.entity import engine, config -from pysnmp.entity.rfc3413 import cmdgen, mibvar -from pysnmp.carrier.asynsock.dgram import udp -from pysnmp.smi import view -from pysnmp import error -from pyasn1.type import univ - -# Auth protocol -usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol -usmHMACSHAAuthProtocol = config.usmHMACSHAAuthProtocol -usmNoAuthProtocol = config.usmNoAuthProtocol - -# Privacy protocol -usmDESPrivProtocol = config.usmDESPrivProtocol -usmAesCfb128Protocol = config.usmAesCfb128Protocol -usmNoPrivProtocol = config.usmNoPrivProtocol - -class CommunityData: - mpModel=1 # Default is SMIv2 - securityModel=mpModel+1 - securityLevel='noAuthNoPriv' - def __init__(self, securityName, communityName, mpModel=None): - self.securityName = securityName - self.communityName = communityName - if mpModel is not None: - self.mpModel = mpModel - self.securityModel = mpModel + 1 - self.__hash = hash((self.mpModel, self.securityModel, self.securityLevel, self.securityName, self.communityName)) - - def __repr__(self): return '%s("%s", , %s)' % ( - self.__class__.__name__, - self.securityName, - self.mpModel - ) - - def __hash__(self): return self.__hash - def __cmp__(self, other): return cmp(self.__hash, other) - -class UsmUserData: - authKey = privKey = None - authProtocol = usmNoAuthProtocol - privProtocol = usmNoPrivProtocol - securityLevel='noAuthNoPriv' - securityModel=3 - mpModel=2 - def __init__(self, securityName, - authKey=None, privKey=None, - authProtocol=None, privProtocol=None): - self.securityName = securityName - - if authKey is not None: - self.authKey = authKey - if authProtocol is None: - self.authProtocol = usmHMACMD5AuthProtocol - else: - self.authProtocol = authProtocol - if self.securityLevel != 'authPriv': - self.securityLevel = 'authNoPriv' - - if privKey is not None: - self.privKey = privKey - if self.authProtocol == usmNoAuthProtocol: - raise error.PySnmpError('Privacy implies authenticity') - self.securityLevel = 'authPriv' - if privProtocol is None: - self.privProtocol = usmDESPrivProtocol - else: - self.privProtocol = privProtocol - - self.__hash = hash((self.mpModel, self.securityModel, self.securityLevel, self.securityName, self.authProtocol, self.authKey, self.privProtocol, self.privKey)) - - def __repr__(self): return '%s("%s", , , %s, %s)' % ( - self.__class__.__name__, - self.securityName, - self.authProtocol, - self.privProtocol - ) - - def __hash__(self): return self.__hash - def __cmp__(self, other): return cmp(self.__hash, other) - -class UdpTransportTarget: - transportDomain = udp.domainName - def __init__(self, transportAddr, timeout=1, retries=5): - self.transportAddr = ( - socket.gethostbyname(transportAddr[0]), transportAddr[1] - ) - self.timeout = timeout - self.retries = retries - - def __repr__(self): return '%s(("%s", %s), %s, %s)' % ( - self.__class__.__name__, - self.transportAddr[0], self.transportAddr[1], - self.timeout, self.retries - ) - - def openClientMode(self): - self.transport = udp.UdpSocketTransport().openClientMode() - return self.transport - -class AsynCommandGenerator: - _null = univ.Null('') - def __init__(self, snmpEngine=None): - if snmpEngine is None: - self.snmpEngine = engine.SnmpEngine() - else: - self.snmpEngine = snmpEngine - self.mibViewController = view.MibViewController( - self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder - ) - self.__knownAuths = {} - self.__knownTransports = {} - self.__knownTransportAddrs = {} - - def __del__(self): self.uncfgCmdGen() - - def cfgCmdGen(self, authData, transportTarget, tagList=''): - paramsName = 'p-%s' % hash(authData.securityName) - if not self.__knownAuths.has_key(authData): - if isinstance(authData, CommunityData): - config.addV1System( - self.snmpEngine, - authData.securityName, - authData.communityName - ) - config.addTargetParams( - self.snmpEngine, paramsName, - authData.securityName, authData.securityLevel, - authData.mpModel - ) - elif isinstance(authData, UsmUserData): - config.addV3User( - self.snmpEngine, - authData.securityName, - authData.authProtocol, authData.authKey, - authData.privProtocol, authData.privKey - ) - config.addTargetParams( - self.snmpEngine, paramsName, - authData.securityName, authData.securityLevel - ) - else: - raise error.PySnmpError('Unsupported SNMP version') - self.__knownAuths[authData] = 1 - - if not self.__knownTransports.has_key(transportTarget.transportDomain): - transport = transportTarget.openClientMode() - config.addSocketTransport( - self.snmpEngine, - transportTarget.transportDomain, - transport - ) - self.__knownTransports[transportTarget.transportDomain] = transport - - addrName = 'a-%s' % hash((paramsName, transportTarget.transportAddr)) - if not self.__knownTransportAddrs.has_key(addrName): - config.addTargetAddr( - self.snmpEngine, addrName, - transportTarget.transportDomain, - transportTarget.transportAddr, - paramsName, - transportTarget.timeout * 100, - transportTarget.retries, - tagList - ) - self.__knownTransportAddrs[addrName] = 1 - - return addrName, paramsName - - def uncfgCmdGen(self): - for authData in self.__knownAuths.keys(): - paramsName = 'p-%s' % hash(authData.securityName) - if isinstance(authData, CommunityData): - config.delV1System( - self.snmpEngine, - authData.securityName - ) - config.delTargetParams( - self.snmpEngine, paramsName - ) - elif isinstance(authData, UsmUserData): - config.delV3User( - self.snmpEngine, authData.securityName - ) - config.delTargetParams( - self.snmpEngine, paramsName - ) - else: - raise error.PySnmpError('Unsupported SNMP version') - self.__knownAuths.clear() - - for transportDomain, transport in self.__knownTransports.items(): - config.delSocketTransport( - self.snmpEngine, transportDomain - ) - transport.closeTransport() - self.__knownTransports.clear() - - for addrName in self.__knownTransportAddrs.keys(): - config.delTargetAddr( - self.snmpEngine, addrName - ) - self.__knownTransportAddrs.clear() - - # Async SNMP apps - - def asyncGetCmd( - self, authData, transportTarget, varNames, (cbFun, cbCtx) - ): - addrName, paramsName = self.cfgCmdGen( - authData, transportTarget - ) - varBinds = [] - for varName in varNames: - name, oid = mibvar.mibNameToOid( - self.mibViewController, varName - ) - varBinds.append((name + oid, self._null)) - return cmdgen.GetCommandGenerator().sendReq( - self.snmpEngine, addrName, varBinds, cbFun, cbCtx - ) - - def asyncSetCmd( - self, authData, transportTarget, varBinds, (cbFun, cbCtx) - ): - addrName, paramsName = self.cfgCmdGen( - authData, transportTarget - ) - __varBinds = [] - for varName, varVal in varBinds: - name, oid = mibvar.mibNameToOid( - self.mibViewController, varName - ) - if not type(varVal) == types.InstanceType: - ((symName, modName), suffix) = mibvar.oidToMibName( - self.mibViewController, name + oid - ) - syntax = mibvar.cloneFromMibValue( - self.mibViewController, modName, symName, varVal - ) - if syntax is None: - raise error.PySnmpError( - 'Value type MIB lookup failed for %s' % repr(varName) - ) - varVal = syntax.clone(varVal) - __varBinds.append((name + oid, varVal)) - return cmdgen.SetCommandGenerator().sendReq( - self.snmpEngine, addrName, __varBinds, cbFun, cbCtx - ) - - def asyncNextCmd( - self, authData, transportTarget, varNames, (cbFun, cbCtx) - ): - addrName, paramsName = self.cfgCmdGen( - authData, transportTarget - ) - varBinds = [] - for varName in varNames: - name, oid = mibvar.mibNameToOid( - self.mibViewController, varName - ) - varBinds.append((name + oid, self._null)) - return cmdgen.NextCommandGenerator().sendReq( - self.snmpEngine, addrName, varBinds, cbFun, cbCtx - ) - - def asyncBulkCmd( - self, authData, transportTarget, nonRepeaters, maxRepetitions, - varNames, (cbFun, cbCtx) - ): - addrName, paramsName = self.cfgCmdGen( - authData, transportTarget - ) - varBinds = [] - for varName in varNames: - name, oid = mibvar.mibNameToOid( - self.mibViewController, varName - ) - varBinds.append((name + oid, self._null)) - return cmdgen.BulkCommandGenerator().sendReq( - self.snmpEngine, addrName, nonRepeaters, maxRepetitions, - varBinds, cbFun, cbCtx - ) - -class CommandGenerator(AsynCommandGenerator): - def getCmd(self, authData, transportTarget, *varNames): - def __cbFun( - sendRequestHandle, errorIndication, errorStatus, errorIndex, - varBinds, appReturn - ): - appReturn['errorIndication'] = errorIndication - appReturn['errorStatus'] = errorStatus - appReturn['errorIndex'] = errorIndex - appReturn['varBinds'] = varBinds - - appReturn = {} - self.asyncGetCmd( - authData, transportTarget, varNames, (__cbFun, appReturn) - ) - self.snmpEngine.transportDispatcher.runDispatcher() - return ( - appReturn['errorIndication'], - appReturn['errorStatus'], - appReturn['errorIndex'], - appReturn['varBinds'] - ) - - def setCmd(self, authData, transportTarget, *varBinds): - def __cbFun( - sendRequestHandle, errorIndication, errorStatus, errorIndex, - varBinds, appReturn - ): - appReturn['errorIndication'] = errorIndication - appReturn['errorStatus'] = errorStatus - appReturn['errorIndex'] = errorIndex - appReturn['varBinds'] = varBinds - - appReturn = {} - self.asyncSetCmd( - authData, transportTarget, varBinds, (__cbFun, appReturn) - ) - self.snmpEngine.transportDispatcher.runDispatcher() - return ( - appReturn['errorIndication'], - appReturn['errorStatus'], - appReturn['errorIndex'], - appReturn['varBinds'] - ) - - def nextCmd(self, authData, transportTarget, *varNames): - def __cbFun( - sendRequestHandle, errorIndication, errorStatus, errorIndex, - varBindTable, (varBindHead, varBindTotalTable, appReturn) - ): - if errorIndication or errorStatus: - appReturn['errorIndication'] = errorIndication - appReturn['errorStatus'] = errorStatus - appReturn['errorIndex'] = errorIndex - appReturn['varBindTable'] = varBindTable - return - else: - varBindTableRow = varBindTable[-1] - for idx in range(len(varBindTableRow)): - name, val = varBindTableRow[idx] - # XXX extra rows - if val is not None and varBindHead[idx].isPrefixOf(name): - break - else: - appReturn['errorIndication'] = errorIndication - appReturn['errorStatus'] = errorStatus - appReturn['errorIndex'] = errorIndex - appReturn['varBindTable'] = varBindTotalTable - return - varBindTotalTable.extend(varBindTable) - - return 1 # continue table retrieval - - varBindHead = map(lambda (x,y): univ.ObjectIdentifier(x+y), map(lambda x,self=self: mibvar.mibNameToOid(self.mibViewController, x), varNames)) - - appReturn = {} - self.asyncNextCmd( - authData, transportTarget, varNames, - (__cbFun, (varBindHead,[],appReturn)) - ) - - self.snmpEngine.transportDispatcher.runDispatcher() - - return ( - appReturn['errorIndication'], - appReturn['errorStatus'], - appReturn['errorIndex'], - appReturn['varBindTable'] - ) - - def bulkCmd(self, authData, transportTarget, - nonRepeaters, maxRepetitions, *varNames): - def __cbFun( - sendRequestHandle, errorIndication, errorStatus, errorIndex, - varBindTable, (varBindHead, varBindTotalTable, appReturn) - ): - if errorIndication or errorStatus: - appReturn['errorIndication'] = errorIndication - appReturn['errorStatus'] = errorStatus - appReturn['errorIndex'] = errorIndex - appReturn['varBindTable'] = varBindTable - return - else: - varBindTotalTable.extend(varBindTable) # XXX out of table - # rows possible - varBindTableRow = varBindTable[-1] - for idx in range(len(varBindTableRow)): - name, val = varBindTableRow[idx] - if val is not None and varBindHead[idx].isPrefixOf(name): - break - else: - appReturn['errorIndication'] = errorIndication - appReturn['errorStatus'] = errorStatus - appReturn['errorIndex'] = errorIndex - appReturn['varBindTable'] = varBindTotalTable - return - - return 1 # continue table retrieval - - varBindHead = map(lambda (x,y): univ.ObjectIdentifier(x+y), map(lambda x,self=self: mibvar.mibNameToOid(self.mibViewController, x), varNames)) - - appReturn = {} - - self.asyncBulkCmd( - authData, transportTarget, nonRepeaters, maxRepetitions, - varNames, (__cbFun, (varBindHead, [], appReturn)) - ) - - self.snmpEngine.transportDispatcher.runDispatcher() - - return ( - appReturn['errorIndication'], - appReturn['errorStatus'], - appReturn['errorIndex'], - appReturn['varBindTable'] - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/oneliner/ntforg.py python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/oneliner/ntforg.py --- python-pysnmp4-4.1.9a/pysnmp/v4/entity/rfc3413/oneliner/ntforg.py 2007-07-09 13:39:48.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/entity/rfc3413/oneliner/ntforg.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -import types -from pysnmp.entity import config -from pysnmp.entity.rfc3413 import ntforg, context, mibvar -from pysnmp.entity.rfc3413.oneliner import cmdgen - -# Auth protocol -usmHMACMD5AuthProtocol = cmdgen.usmHMACMD5AuthProtocol -usmHMACSHAAuthProtocol = cmdgen.usmHMACSHAAuthProtocol -usmNoAuthProtocol = cmdgen.usmNoAuthProtocol - -# Privacy protocol -usmDESPrivProtocol = cmdgen.usmDESPrivProtocol -usmAesCfb128Protocol = cmdgen.usmAesCfb128Protocol -usmNoPrivProtocol = cmdgen.usmNoPrivProtocol - -# Credentials -CommunityData = cmdgen.CommunityData -UsmUserData = cmdgen.UsmUserData - -# Transport -UdpTransportTarget = cmdgen.UdpTransportTarget - -class AsynNotificationOriginator(cmdgen.AsynCommandGenerator): - def __init__(self, snmpEngine=None, snmpContext=None): - cmdgen.AsynCommandGenerator.__init__(self, snmpEngine) - self.snmpContext = snmpContext - self.__knownAuths = {} - - def __del__(self): self.uncfgNtfOrg() - - def cfgNtfOrg(self, authData, transportTarget, notifyType, tagList=''): - addrName, paramsName = self.cfgCmdGen(authData, transportTarget, - tagList) - notifyName = 'n-%s' % hash(tagList) - if not self.__knownAuths.has_key(authData): - config.addNotificationTarget( - self.snmpEngine, - notifyName, - paramsName, - tagList, - notifyType - ) - config.addContext( - self.snmpEngine, '' # this is leaky - ) - subTree = (1,3,6) - config.addTrapUser( - self.snmpEngine, - authData.securityModel, - authData.securityName, - authData.securityLevel, - subTree - ) - if self.snmpContext is None: - self.snmpContext = context.SnmpContext(self.snmpEngine) - self.__knownAuths[authData] = notifyName, paramsName, subTree - return notifyName - - def uncfgNtfOrg(self): - self.uncfgCmdGen() - for authData, (notifyName, paramsName, subTree) in self.__knownAuths.items(): - config.delNotificationTarget( - self.snmpEngine, notifyName, paramsName - ) - config.delTrapUser( - self.snmpEngine, - authData.securityModel, - authData.securityName, - authData.securityLevel, - subTree - ) - - def asyncSendNotification( - self, authData, transportTarget, notifyType, - notificationType, varBinds=None, (cbFun, cbCtx)=(None, None) - ): - tagList = 'notify-list' - notifyName = self.cfgNtfOrg(authData, transportTarget, - notifyType, tagList) - if notificationType: - name, oid = mibvar.mibNameToOid( - self.mibViewController, notificationType - ) - notificationType = name + oid - if varBinds: - __varBinds = [] - for varName, varVal in varBinds: - name, oid = mibvar.mibNameToOid( - self.mibViewController, varName - ) - if not type(varVal) == types.InstanceType: - ((symName, modName), suffix) = mibvar.oidToMibName( - self.mibViewController, name + oid - ) - syntax = mibvar.cloneFromMibValue( - self.mibViewController, modName, symName, varVal - ) - if syntax is None: - raise error.PySnmpError( - 'Value type MIB lookup failed for %s' % repr(varName) - ) - varVal = syntax.clone(varVal) - __varBinds.append((name + oid, varVal)) - else: - __varBinds = None - - return ntforg.NotificationOriginator(self.snmpContext).sendNotification(self.snmpEngine, notifyName, notificationType, __varBinds, cbFun, cbCtx) - -class NotificationOriginator(AsynNotificationOriginator): - def sendNotification( - self, authData, transportTarget, notifyType, - notificationType, *varBinds - ): - def __cbFun(sendRequestHandle, errorIndication, appReturn): - appReturn['errorIndication'] = errorIndication - - appReturn = {} - errorIndication = self.asyncSendNotification( - authData, transportTarget, notifyType, notificationType, varBinds, - (__cbFun, appReturn) - ) - if errorIndication: - return errorIndication - self.snmpEngine.transportDispatcher.runDispatcher() - return appReturn.get('errorIndication') diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/error.py python-pysnmp4-4.2.2/pysnmp/v4/error.py --- python-pysnmp4-4.1.9a/pysnmp/v4/error.py 2005-06-14 09:12:52.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/error.py 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -class PySnmpError(StandardError): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/__init__.py python-pysnmp4-4.2.2/pysnmp/v4/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/v4/__init__.py 2004-11-12 16:15:12.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/__init__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -# PySNMP, version 4 -majorVersionId = '4' diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/acmod/rfc3415.py python-pysnmp4-4.2.2/pysnmp/v4/proto/acmod/rfc3415.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/acmod/rfc3415.py 2006-09-06 16:41:47.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/acmod/rfc3415.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -# View-based Access Control Model -from pysnmp.smi.error import NoSuchObjectError -from pysnmp.proto import error -from pysnmp import debug - -accessModelID = 3 - -__powOfTwoSeq = [128, 64, 32, 16, 8, 4, 2, 1] - -# 3.2 -def isAccessAllowed( - snmpEngine, - securityModel, - securityName, - securityLevel, - viewType, - contextName, - variableName): - mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController - - debug.logger & debug.flagACL and debug.logger('isAccessAllowed: viewType %s for variableName %s' % (viewType, variableName)) - - # 3.2.1 - vacmContextEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') - tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) - try: - vacmContextName = vacmContextEntry.getNode( - vacmContextEntry.name + (1,) + tblIdx - ).syntax - except NoSuchObjectError: - raise error.StatusInformation(errorIndication='noSuchContext') - - # 3.2.2 - vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' - ) - tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( - securityModel, securityName - ) - try: - vacmGroupName = vacmSecurityToGroupEntry.getNode( - vacmSecurityToGroupEntry.name + (3,) + tblIdx - ).syntax - except NoSuchObjectError: - raise error.StatusInformation(errorIndication='noGroupName') - - # 3.2.3 - vacmAccessEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' - ) - # XXX partial context name match - tblIdx = vacmAccessEntry.getInstIdFromIndices( - vacmGroupName, contextName, securityModel, securityLevel - ) - - # 3.2.4 - if viewType == 'read': - entryIdx = vacmAccessEntry.name + (5,) + tblIdx - elif viewType == 'write': - entryIdx = vacmAccessEntry.name + (6,) + tblIdx - elif viewType == 'notify': - entryIdx = vacmAccessEntry.name + (7,) + tblIdx - else: - raise error.ProtocolError('Unknown view type %s' % viewType) - - try: - viewName = vacmAccessEntry.getNode(entryIdx).syntax - except NoSuchObjectError: - raise error.StatusInformation(errorIndication='noAccessEntry') - if not len(viewName): - raise error.StatusInformation(errorIndication='noSuchView') - - # XXX split onto object & instance ? - - # 3.2.5a - vacmViewTreeFamilyEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry') - tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName) - - # Walk over entries - initialTreeName = treeName = vacmViewTreeFamilyEntry.name + (2,) + tblIdx - maskName = vacmViewTreeFamilyEntry.name + (3,) + tblIdx - while 1: - vacmViewTreeFamilySubtree = vacmViewTreeFamilyEntry.getNextNode( - treeName - ) - vacmViewTreeFamilyMask = vacmViewTreeFamilyEntry.getNextNode( - maskName - ) - treeName = vacmViewTreeFamilySubtree.name - maskName = vacmViewTreeFamilyMask.name - if initialTreeName != treeName[:len(initialTreeName)]: - # 3.2.5b - raise error.StatusInformation(errorIndication='notInView') - l = len(vacmViewTreeFamilySubtree.syntax) - if l > len(variableName): - continue - if vacmViewTreeFamilyMask.syntax: - mask = [] - for c in map(None, str(vacmViewTreeFamilyMask.syntax)): - mask = mask + map(lambda b,c=ord(c): b&c, __powOfTwoSeq) - m = len(mask)-1 - idx = l-1 - while idx: - if idx > m or mask[idx] and \ - vacmViewTreeFamilySubtree.syntax[idx] != variableName[idx]: - break - idx = idx - 1 - if idx: continue # no match - else: # no mask - if vacmViewTreeFamilySubtree.syntax != variableName[:l]: - continue # no match - # 3.2.5c - return error.StatusInformation(errorIndication='accessAllowed') diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/__init__.py python-pysnmp4-4.2.2/pysnmp/v4/proto/api/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/__init__.py 2005-06-14 10:40:08.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/api/__init__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -from pysnmp.proto.api import v1, v2c, verdec - -# Protocol versions -protoVersion1 = 0 -protoVersion2c = 1 -protoModules = { protoVersion1: v1, protoVersion2c: v2c } - -decodeMessageVersion = verdec.decodeMessageVersion diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/v1.py python-pysnmp4-4.2.2/pysnmp/v4/proto/api/v1.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/v1.py 2007-10-05 17:39:33.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/api/v1.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,197 +0,0 @@ -import types -from pyasn1.type import univ -from pysnmp.proto import rfc1155, rfc1157, error - -# Shortcuts to SNMP types -Integer = univ.Integer -OctetString = univ.OctetString -Null = univ.Null -ObjectIdentifier = univ.ObjectIdentifier - -IpAddress = rfc1155.IpAddress -NetworkAddress = rfc1155.NetworkAddress -Counter = rfc1155.Counter -Gauge = rfc1155.Gauge -TimeTicks = rfc1155.TimeTicks -Opaque = rfc1155.Opaque - -VarBind = rfc1157.VarBind -VarBindList = rfc1157.VarBindList -GetRequestPDU = rfc1157.GetRequestPDU -GetNextRequestPDU = rfc1157.GetNextRequestPDU -GetResponsePDU = rfc1157.GetResponsePDU -SetRequestPDU = rfc1157.SetRequestPDU -TrapPDU = rfc1157.TrapPDU -Message = rfc1157.Message - -class VarBindAPI: - _null = Null('') - def setOIDVal(self, varBind, (oid, val)): - varBind.setComponentByPosition(0, oid) - if val is None: val = self._null - varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(), val, 1) - return varBind - - def getOIDVal(self, varBind): - return varBind[0], varBind[1].getComponent(1) - -apiVarBind = VarBindAPI() - -class __RequestIDSource: - requestId = 0 - def __call__(self): - if self.requestId > 0xfffe: - self.requestId = 0 - else: - self.requestId = self.requestId + 1 - return self.requestId - -getNextRequestID = __RequestIDSource() - -class PDUAPI: - def setDefaults(self, pdu): - pdu.setComponentByPosition(0, getNextRequestID()) - pdu.setComponentByPosition(1, 0) - pdu.setComponentByPosition(2, 0) - pdu.setComponentByPosition(3) - - def getRequestID(self, pdu): return pdu.getComponentByPosition(0) - def setRequestID(self, pdu, value): pdu.setComponentByPosition(0, value) - - def getErrorStatus(self, pdu): return pdu.getComponentByPosition(1) - def setErrorStatus(self, pdu, value): pdu.setComponentByPosition(1, value) - - def getErrorIndex(self, pdu): - errorIndex = pdu.getComponentByPosition(2) - if errorIndex > len(pdu[3]): - raise error.ProtocolError( - 'Error index out of range: %s > %s' % (errorIndex, len(pdu[3])) - ) - return errorIndex - def setErrorIndex(self, pdu, value): - pdu.setComponentByPosition(2, value) - - def setEndOfMibError(self, pdu, errorIndex): - self.setErrorStatus(pdu, 2) - - def setNoSuchInstanceError(self, pdu, errorIndex): - self.setEndOfMibError(pdu, errorIndex) - - def getVarBindList(self, pdu): - return pdu.getComponentByPosition(3) - def setVarBindList(self, pdu, varBindList): - varBindList = pdu.setComponentByPosition(3, varBindList) - - def getVarBinds(self, pdu): - return map(lambda x: apiVarBind.getOIDVal(x), - pdu.getComponentByPosition(3)) - def setVarBinds(self, pdu, varBinds): - varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) - varBindList.clear() - idx = 0 - for varBind in varBinds: - if type(varBind) is types.InstanceType: - varBindList.setComponentByPosition(idx, varBind) - else: - varBindList.setComponentByPosition(idx) - apiVarBind.setOIDVal( - varBindList.getComponentByPosition(idx), varBind - ) - idx = idx + 1 - - def getResponse(self, reqPDU): - rspPDU = GetResponsePDU() - self.setDefaults(rspPDU) - self.setRequestID(rspPDU, self.getRequestID(reqPDU)) - return rspPDU - - def getVarBindTable(self, reqPDU, rspPDU): - if apiPDU.getErrorStatus(rspPDU) == 2: - return [ map(lambda (x,y): (x, None), apiPDU.getVarBinds(reqPDU)) ] - else: - return [ apiPDU.getVarBinds(rspPDU) ] - -apiPDU = PDUAPI() - -try: - import socket - _agentAddress = socket.gethostbyname(socket.gethostname()) -except: - _agentAddress = '0.0.0.0' - -class TrapPDUAPI: - def setDefaults(self, pdu): - pdu.setComponentByPosition(0, (1,3,6,1,4,1,20408)) - pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(0, _agentAddress) - pdu.setComponentByPosition(2, 0) - pdu.setComponentByPosition(3, 0) - pdu.setComponentByPosition(4, 0) - pdu.setComponentByPosition(5) - - def getEnterprise(self, pdu): return pdu.getComponentByPosition(0) - def setEnterprise(self, pdu, value): pdu.setComponentByPosition(0, value) - - def getAgentAddr(self, pdu): - return pdu.getComponentByPosition(1).getComponentByPosition(0) - def setAgentAddr(self, pdu, value): - pdu.getComponentByPosition(1).setComponentByPosition(0, value) - - def getGenericTrap(self, pdu): return pdu.getComponentByPosition(2) - def setGenericTrap(self, pdu, value): pdu.setComponentByPosition(2, value) - - def getSpecificTrap(self, pdu): return pdu.getComponentByPosition(3) - def setSpecificTrap(self, pdu, value): pdu.setComponentByPosition(3, value) - - def getTimeStamp(self, pdu): return pdu.getComponentByPosition(4) - def setTimeStamp(self, pdu, value): pdu.setComponentByPosition(4, value) - - def getVarBindList(self, pdu): - return pdu.getComponentByPosition(5) - def setVarBindList(self, pdu, varBindList): - varBindList = pdu.setComponentByPosition(5, varBindList) - - def getVarBinds(self, pdu): - return map(lambda x: apiVarBind.getOIDVal(x), - pdu.getComponentByPosition(5)) - def setVarBinds(self, pdu, varBinds): - varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5) - varBindList.clear() - idx = 0 - for varBind in varBinds: - if type(varBind) is types.InstanceType: - varBindList.setComponentByPosition(idx, varBind) - else: - varBindList.setComponentByPosition(idx) - apiVarBind.setOIDVal( - varBindList.getComponentByPosition(idx), varBind - ) - idx = idx + 1 - -apiTrapPDU = TrapPDUAPI() - -class MessageAPI: - def setDefaults(self, msg): - msg.setComponentByPosition(0, 0) - msg.setComponentByPosition(1, 'public') - return msg - - def getVersion(self, msg): return msg.getComponentByPosition(0) - def setVersion(self, msg, value): msg.setComponentByPosition(0, value) - - def getCommunity(self, msg): return msg.getComponentByPosition(1) - def setCommunity(self, msg, value): msg.setComponentByPosition(1, value) - - def getPDU(self, msg): return msg.getComponentByPosition(2).getComponent() - def setPDU(self, msg, value): - msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(value.getTagSet(), value, 1) - - def getResponse(self, reqMsg): - rspMsg = Message() - self.setDefaults(rspMsg) - self.setVersion(rspMsg, self.getVersion(reqMsg)) - self.setCommunity(rspMsg, self.getCommunity(reqMsg)) - self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) - return rspMsg - -apiMessage = MessageAPI() - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/v2c.py python-pysnmp4-4.2.2/pysnmp/v4/proto/api/v2c.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/v2c.py 2006-05-21 11:44:46.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/api/v2c.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,132 +0,0 @@ -from pysnmp.proto import rfc1902, rfc1905, error -from pysnmp.proto.api import v1 -from pysnmp.smi import exval -from pyasn1.type import univ, namedtype, namedval - -# Shortcuts to SNMP types -Null = univ.Null -ObjectIdentifier = univ.ObjectIdentifier - -Integer = rfc1902.Integer -Integer32 = rfc1902.Integer32 -OctetString = rfc1902.OctetString -IpAddress = rfc1902.IpAddress -Counter32 = rfc1902.Counter32 -Gauge32 = rfc1902.Gauge32 -Unsigned32 = rfc1902.Unsigned32 -TimeTicks = rfc1902.TimeTicks -Opaque = rfc1902.Opaque -Counter64 = rfc1902.Counter64 -Bits = rfc1902.Bits - -VarBind = rfc1905.VarBind -VarBindList = rfc1905.VarBindList -GetRequestPDU = rfc1905.GetRequestPDU -GetNextRequestPDU = rfc1905.GetNextRequestPDU -ResponsePDU = GetResponsePDU = rfc1905.ResponsePDU -SetRequestPDU = rfc1905.SetRequestPDU -GetBulkRequestPDU = rfc1905.GetBulkRequestPDU -InformRequestPDU = rfc1905.InformRequestPDU -SNMPv2TrapPDU = TrapPDU = rfc1905.SNMPv2TrapPDU -ReportPDU = rfc1905.ReportPDU - -# v2 model uses v1 messaging but it's not defined in v2 MIB -class Message(v1.Message): - componentType = namedtype.NamedTypes( - namedtype.NamedType('version', univ.Integer(namedValues = namedval.NamedValues(('version-2', 1)))), - namedtype.NamedType('community', univ.OctetString()), - namedtype.NamedType('data', rfc1905.PDUs()) - ) - -getNextRequestID = v1.getNextRequestID - -apiVarBind = v1.apiVarBind - -class PDUAPI(v1.PDUAPI): - def getResponse(self, reqPDU): - rspPDU = ResponsePDU() - self.setDefaults(rspPDU) - self.setRequestID(rspPDU, self.getRequestID(reqPDU)) - return rspPDU - - def getVarBindTable(self, reqPDU, rspPDU): - varBinds = [] - for oid, val in apiPDU.getVarBinds(rspPDU): - if exval.endOfMib.isSameTypeWith(val): - val = None - varBinds.append((oid, val)) - return [ varBinds ] - - def setEndOfMibError(self, pdu, errorIndex): - varBindList = self.getVarBindList(pdu) - varBindList[errorIndex-1].setComponentByPosition(1, exval.endOfMib) - - def setNoSuchInstanceError(self, pdu, errorIndex): - varBindList = self.getVarBindList(pdu) - varBindList[errorIndex-1].setComponentByPosition(1,exval.noSuchInstance) - -apiPDU = PDUAPI() - -class BulkPDUAPI(PDUAPI): - def setDefaults(self, pdu): - PDUAPI.setDefaults(self, pdu) - pdu.setComponentByPosition(2, 10) - - def getNonRepeaters(self, pdu): return pdu.getComponentByPosition(1) - def setNonRepeaters(self, pdu, value): pdu.setComponentByPosition(1, value) - - def getMaxRepetitions(self, pdu): return pdu.getComponentByPosition(2) - def setMaxRepetitions(self,pdu,value): pdu.setComponentByPosition(2,value) - - def getVarBindTable(self, reqPDU, rspPDU): - nonRepeaters = int(self.getNonRepeaters(reqPDU)) - N = min(nonRepeaters, len(self.getVarBindList(reqPDU))) - R = max(len(self.getVarBindList(reqPDU))-N, 0) - if R == 0: - M = 0 - else: - M = int(min(self.getMaxRepetitions(reqPDU), - (len(apiPDU.getVarBindList(rspPDU))-N))/R) - varBindList = apiPDU.getVarBindList(rspPDU) - varBindRows = []; varBindTable = [ varBindRows ] -# __null = Null() - for idx in range(N): - oid, val = apiVarBind.getOIDVal(varBindList[idx]) - if exval.endOfMib.isSameTypeWith(val): - val = None -# val = __null - varBindRows.append((oid, val)) - for rowIdx in range(M): - if len(varBindTable) < rowIdx+1: - varBindTable.append([]) - varBindRow = varBindTable[-1] - for colIdx in range(R): - while rowIdx and len(varBindRow) < N: - varBindRow.append(varBindTable[-2][colIdx]) - idx = N + rowIdx*R + colIdx - oid, val = apiVarBind.getOIDVal(varBindList[idx]) - if exval.endOfMib.isSameTypeWith(val): - val = None - if len(varBindRow) < colIdx+N+1: - varBindRow.append((oid, val)) - else: - varBindRow[colIdx] = (oid, val) - return varBindTable - -apiBulkPDU = BulkPDUAPI() - -class MessageAPI(v1.MessageAPI): - def setDefaults(self, msg): - msg.setComponentByPosition(0, 1) - msg.setComponentByPosition(1, 'public') - return msg - - def getResponse(self, reqMsg): - rspMsg = Message() - self.setDefaults(rspMsg) - self.setVersion(rspMsg, self.getVersion(reqMsg)) - self.setCommunity(rspMsg, self.getCommunity(reqMsg)) - self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) - return rspMsg - -apiMessage = MessageAPI() diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/verdec.py python-pysnmp4-4.2.2/pysnmp/v4/proto/api/verdec.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/api/verdec.py 2005-06-14 10:40:08.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/api/verdec.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -from pyasn1.codec.ber import decoder - -def decodeMessageVersion(wholeMsg): - seq, wholeMsg = decoder.decode(wholeMsg, recursiveFlag=0) - ver, wholeMsg = decoder.decode(wholeMsg, recursiveFlag=0) - return ver diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/error.py python-pysnmp4-4.2.2/pysnmp/v4/proto/error.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/error.py 2006-09-06 16:41:47.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/error.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -from pyasn1.error import PyAsn1Error -from pysnmp.error import PySnmpError -from pysnmp import debug - -class ProtocolError(PySnmpError, PyAsn1Error): pass - -# SNMP v3 exceptions - -class SnmpV3Error(ProtocolError): pass -class StatusInformation(SnmpV3Error): - def __init__(self, **kwargs): - SnmpV3Error.__init__(self) - self.__errorIndication = kwargs - debug.logger & (debug.flagDsp|debug.flagMP|debug.flagSM) and debug.logger('StatusInformation: %s' % kwargs) - def __str__(self): return str(self.__errorIndication) - def __getitem__(self, key): return self.__errorIndication[key] - def has_key(self, key): return self.__errorIndication.has_key(key) - def get(self, key, defVal=None): - return self.__errorIndication.get(key, defVal) -class CacheExpiredError(SnmpV3Error): pass -class InternalError(SnmpV3Error): pass -class MessageProcessingError(SnmpV3Error): pass -class RequestTimeout(SnmpV3Error): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/__init__.py python-pysnmp4-4.2.2/pysnmp/v4/proto/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/__init__.py 2004-11-12 14:21:29.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/__init__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -""" - SNMP framework for Python. - - The pysnmp.proto sub-package implements various SNMP protocols. - - Copyright 1999-2004 by Ilya Etingof . See LICENSE for details. -""" diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/mpmod/base.py python-pysnmp4-4.2.2/pysnmp/v4/proto/mpmod/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/mpmod/base.py 2006-09-20 16:26:13.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/mpmod/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -# MP-specific cache management -from pysnmp.proto import error - -class AbstractMessageProcessingModel: - messageProcessingModelID = None - __stateReference = __msgID = 0L - def __init__(self): - self.__msgIdIndex = {} - self.__stateReferenceIndex = {} - self.__sendPduHandleIdx = {} - # Message expiration mechanics - self.__expirationQueue = {} - self.__expirationTimer = 0L - - def prepareOutgoingMessage( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - expectResponse, - sendPduHandle - ): - raise error.ProtocolError('method not implemented') - - def prepareResponseMessage( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ): - raise error.ProtocolError('method not implemented') - - def prepareDataElements( - self, - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ): - raise error.ProtocolError('method not implemented') - - def _newStateReference(self): - AbstractMessageProcessingModel.__stateReference = ( - AbstractMessageProcessingModel.__stateReference + 1 - ) - return self.__stateReference - - # Server mode cache handling - - def _cachePushByStateRef(self, stateReference, **msgInfo): - if self.__stateReferenceIndex.has_key(stateReference): - raise error.ProtocolError( - 'Cache dup for stateReference=%s at %s' % - (stateReference, self) - ) - expireAt = self.__expirationTimer+50 - self.__stateReferenceIndex[stateReference] = ( msgInfo, expireAt ) - - # Schedule to expire - if not self.__expirationQueue.has_key(expireAt): - self.__expirationQueue[expireAt] = {} - if not self.__expirationQueue[expireAt].has_key('stateReference'): - self.__expirationQueue[expireAt]['stateReference'] = {} - self.__expirationQueue[expireAt]['stateReference'][stateReference] = 1 - self.__expireCaches() - - def _cachePopByStateRef(self, stateReference): - cacheInfo = self.__stateReferenceIndex.get(stateReference) - if cacheInfo is None: - raise error.ProtocolError( - 'Cache miss for stateReference=%s at %s' % - (stateReference, self) - ) - del self.__stateReferenceIndex[stateReference] - cacheEntry, expireAt = cacheInfo - del self.__expirationQueue[expireAt]['stateReference'][stateReference] - return cacheEntry - - # Client mode cache handling - - def _newMsgID(self): - AbstractMessageProcessingModel.__msgID = ( - AbstractMessageProcessingModel.__msgID + 1 - ) - return self.__msgID - - def _cachePushByMsgId(self, msgId, **msgInfo): - if self.__msgIdIndex.has_key(msgId): - raise error.ProtocolError( - 'Cache dup for msgId=%s at %s' % (msgId, self) - ) - expireAt = self.__expirationTimer+50 - self.__msgIdIndex[msgId] = ( msgInfo, expireAt ) - - self.__sendPduHandleIdx[msgInfo['sendPduHandle']] = msgId - - # Schedule to expire - if not self.__expirationQueue.has_key(expireAt): - self.__expirationQueue[expireAt] = {} - if not self.__expirationQueue[expireAt].has_key('msgId'): - self.__expirationQueue[expireAt]['msgId'] = {} - self.__expirationQueue[expireAt]['msgId'][msgId] = 1 - self.__expireCaches() - - def _cachePopByMsgId(self, msgId): - cacheInfo = self.__msgIdIndex.get(msgId) - if cacheInfo is None: - raise error.ProtocolError( - 'Cache miss for msgId=%s at %s' % (msgId, self) - ) - msgInfo, expireAt = cacheInfo - del self.__sendPduHandleIdx[msgInfo['sendPduHandle']] - del self.__msgIdIndex[msgId] - cacheEntry, expireAt = cacheInfo - del self.__expirationQueue[expireAt]['msgId'][msgId] - return cacheEntry - - def _cachePopBySendPduHandle(self, sendPduHandle): - if self.__sendPduHandleIdx.has_key(sendPduHandle): - self._cachePopByMsgId(self.__sendPduHandleIdx[sendPduHandle]) - - def __expireCaches(self): - # Uses internal clock to expire pending messages - if self.__expirationQueue.has_key(self.__expirationTimer): - cacheInfo = self.__expirationQueue[self.__expirationTimer] - if cacheInfo.has_key('stateReference'): - for stateReference in cacheInfo['stateReference'].keys(): - del self.__stateReferenceIndex[stateReference] - if cacheInfo.has_key('msgId'): - for msgId in cacheInfo['msgId'].keys(): - del self.__msgIdIndex[msgId] - del self.__expirationQueue[self.__expirationTimer] - self.__expirationTimer = self.__expirationTimer + 1 - - def releaseStateInformation(self, sendPduHandle): - try: - self._cachePopBySendPduHandle(sendPduHandle) - except error.ProtocolError: - pass # XXX maybe these should all follow some scheme? - - def receiveTimerTick(self, snmpEngine, timeNow): - pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/mpmod/rfc2576.py python-pysnmp4-4.2.2/pysnmp/v4/proto/mpmod/rfc2576.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/mpmod/rfc2576.py 2007-11-26 10:16:40.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/mpmod/rfc2576.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,407 +0,0 @@ -# SNMP v1 & v2c message processing models implementation -from pyasn1.codec.ber import decoder -from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel -from pysnmp.proto.secmod import rfc2576 -from pysnmp.proto import rfc3411, 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 -# inner workings, the following has been patterned from v3MP. Most -# references here goes to RFC3412. - -class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): - messageProcessingModelID = 0 # SNMPv1 - _snmpMsgSpec = v1.Message() - # rfc3412: 7.1 - def prepareOutgoingMessage( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - expectResponse, - sendPduHandle - ): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpEngineID = snmpEngineID.syntax - - # rfc3412: 7.1.1b - if rfc3411.notificationClassPDUs.has_key(pdu.tagSet): - msgID = 0 # XXX - else: - pdu.setComponentByPosition(1) - msgID = pdu.getComponentByPosition(0) - - # rfc3412: 7.1.4 - # Since there's no SNMP engine identification in v1/2c, - # set destination contextEngineId to ours - if not contextEngineId: - contextEngineId = snmpEngineID - - # rfc3412: 7.1.5 - if not contextName: - contextName = '' - - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %s contextName %s' % (contextEngineId, contextName)) - - # rfc3412: 7.1.6 - scopedPDU = ( contextEngineId, contextName, pdu ) - - msg = self._snmpMsgSpec.clone() - msg.setComponentByPosition(0, self.messageProcessingModelID) - msg.setComponentByPosition(2) - msg.getComponentByPosition(2).setComponentByType(pdu.tagSet, pdu) - - # rfc3412: 7.1.7 - globalData = ( msg, ) - - smHandler = snmpEngine.securityModels.get(int(securityModel)) - if smHandler is None: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityModel' - ) - - # rfc3412: 7.1.9.a & rfc2576: 5.2.1 --> no-op - - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') - - # rfc3412: 7.1.9.b - ( securityParameters, - wholeMsg ) = smHandler.generateRequestMsg( - snmpEngine, - self.messageProcessingModelID, - globalData, - snmpEngineMaxMessageSize.syntax, - securityModel, - snmpEngineID, - securityName, - securityLevel, - scopedPDU - ) - - # rfc3412: 7.1.9.c - if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet): - # XXX rfc bug? why stateReference should be created? - self._cachePushByMsgId( - long(msgID), - sendPduHandle=sendPduHandle, - msgID=msgID, - snmpEngineID=snmpEngineID, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - contextEngineId=contextEngineId, - contextName=contextName, - transportDomain=transportDomain, - transportAddress=transportAddress - ) - - return ( transportDomain, transportAddress, wholeMsg ) - - # rfc3412: 7.1 - def prepareResponseMessage( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpEngineID = snmpEngineID.syntax - - # rfc3412: 7.1.2.b - cachedParams = self._cachePopByStateRef(stateReference) - msgID = cachedParams['msgID'] - contextEngineId = cachedParams['contextEngineId'] - contextName = cachedParams['contextName'] - securityModel = cachedParams['securityModel'] - securityName = cachedParams['securityName'] - securityLevel = cachedParams['securityLevel'] - securityStateReference = cachedParams['securityStateReference'] - maxMessageSize = cachedParams['msgMaxSize'] - transportDomain = cachedParams['transportDomain'] - transportAddress = cachedParams['transportAddress'] - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % (msgID, transportDomain, transportAddress, stateReference)) - - # rfc3412: 7.1.3 - if statusInformation: - # rfc3412: 7.1.3a (N/A) - - # rfc3412: 7.1.3b (always discard) - raise error.StatusInformation( - errorIndication = 'nonReportable' - ) - - # rfc3412: 7.1.4 - # Since there's no SNMP engine identification in v1/2c, - # set destination contextEngineId to ours - if not contextEngineId: - contextEngineId = snmpEngineID - - # rfc3412: 7.1.5 - if not contextName: - contextName = '' - - # rfc3412: 7.1.6 - scopedPDU = ( contextEngineId, contextName, pdu ) - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %s contextName %s' % (contextEngineId, contextName)) - - msg = self._snmpMsgSpec.clone() - msg.setComponentByPosition(0, messageProcessingModel) - msg.setComponentByPosition(2) - msg.getComponentByPosition(2).setComponentByType(pdu.tagSet, pdu) - - # att: msgId not set back to PDU as it's up to responder app - - # rfc3412: 7.1.7 - globalData = ( msg, ) - - smHandler = snmpEngine.securityModels.get(int(securityModel)) - if smHandler is None: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityModel' - ) - - securityEngineId = snmpEngineID - - # rfc3412: 7.1.8.a - ( securityParameters, - wholeMsg ) = smHandler.generateResponseMsg( - snmpEngine, - self.messageProcessingModelID, - globalData, - maxMessageSize, - securityModel, - snmpEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ) - - return ( transportDomain, transportAddress, wholeMsg ) - - # rfc3412: 7.2.1 - - def prepareDataElements( - self, - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ): - # rfc3412: 7.2.2 - try: - msg, restOfwholeMsg = decoder.decode( - wholeMsg, asn1Spec=self._snmpMsgSpec - ) - except PyAsn1Error: - snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') - snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 - raise error.StatusInformation( - errorIndication = 'parseError' - ) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: msg decoded') - - # rfc3412: 7.2.3 - msgVersion = messageProcessingModel = msg.getComponentByPosition(0) - pdu = msg.getComponentByPosition(2).getComponent() - # (wild hack: use PDU reqID at MsgID) - msgID = pdu.getComponentByPosition(0) - - # rfc2576: 5.2.1 - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') - securityParameters = ( - msg.getComponentByPosition(1), - (transportDomain, transportAddress), - ('0.0.0.0', 0) # XXX - ) - messageProcessingModel = int(msg.getComponentByPosition(0)) - securityModel = messageProcessingModel + 1 - securityLevel = 1 - - # rfc3412: 7.2.4 -- 7.2.5 -> noop - - smHandler = snmpEngine.securityModels.get(int(securityModel)) - if smHandler is None: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityModel' - ) - - # rfc3412: 7.2.6 - ( securityEngineID, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) = smHandler.processIncomingMsg( - snmpEngine, - messageProcessingModel, - snmpEngineMaxMessageSize.syntax, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg - ) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM returned securityEngineID %s securityName %s' % (securityEngineID, securityName)) - - # rfc3412: 7.2.6a --> noop - - # rfc3412: 7.2.7 - contextEngineId, contextName, pdu = scopedPDU - - # rfc2576: 5.2.1 - pduVersion = msgVersion - pduType = pdu.tagSet - - # XXX use cache - # set stateref to null as in v3 model - stateReference = securityStateReference - - # rfc3412: 7.2.8, 7.2.9 -> noop - - # rfc3412: 7.2.10 - if rfc3411.responseClassPDUs.has_key(pduType): - # 7.2.10a - try: - cachedReqParams = self._cachePopByMsgId(long(msgID)) - except error.ProtocolError: - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'dataMismatch' - ) - - # 7.2.10b - sendPduHandle = cachedReqParams['sendPduHandle'] - else: - sendPduHandle = None - - statusInformation = None - - # rfc3412: 7.2.11 -> noop - - # rfc3412: 7.2.12 - if rfc3411.responseClassPDUs.has_key(pduType): - # rfc3412: 7.2.12a -> noop - # rfc3412: 7.2.12b - if securityModel != cachedReqParams['securityModel'] or \ - securityName != cachedReqParams['securityName'] or \ - securityLevel != cachedReqParams['securityLevel'] or \ - contextEngineId != cachedReqParams['contextEngineId'] or \ - contextName != cachedReqParams['contextName']: - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'dataMismatch' - ) - - # rfc3412: 7.2.12c - smHandler.releaseStateInformation(securityStateReference) - - # rfc3412: 7.2.12d - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) - - # rfc3412: 7.2.13 - if rfc3411.confirmedClassPDUs.has_key(pduType): - # rfc3412: 7.2.13a - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - if securityEngineID != snmpEngineID.syntax: - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'engineIDMispatch' - ) - - # rfc3412: 7.2.13b - stateReference = self._newStateReference() - self._cachePushByStateRef( - stateReference, - msgVersion=messageProcessingModel, - msgID=msgID, - contextEngineId=contextEngineId, - contextName=contextName, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - securityStateReference=securityStateReference, - msgMaxSize=snmpEngineMaxMessageSize.syntax, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, - transportDomain=transportDomain, - transportAddress=transportAddress - ) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: cached by new stateReference %s' % stateReference) - - # rfc3412: 7.2.13c - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) - - # rfc3412: 7.2.14 - if rfc3411.unconfirmedClassPDUs.has_key(pduType): - # This is not specified explicitly in RFC - smHandler.releaseStateInformation(securityStateReference) - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) - - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'unsupportedPDUtype' - ) - -class SnmpV2cMessageProcessingModel(SnmpV1MessageProcessingModel): - messageProcessingModelID = 1 # SNMPv2c - _snmpMsgSpec = v2c.Message() diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/mpmod/rfc3412.py python-pysnmp4-4.2.2/pysnmp/v4/proto/mpmod/rfc3412.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/mpmod/rfc3412.py 2007-11-26 10:16:41.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/mpmod/rfc3412.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,742 +0,0 @@ -# SNMP v3 message processing model implementation -from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel -from pysnmp.proto.secmod import rfc3414 -from pysnmp.proto import rfc1905, rfc3411, error, api -from pyasn1.type import univ, namedtype, constraint -from pyasn1.codec.ber import decoder -from pyasn1.error import PyAsn1Error -from pysnmp import debug - -# API to rfc1905 protocol objects -pMod = api.protoModules[api.protoVersion2c] - -# SNMPv3 message format - -class ScopedPDU(univ.Sequence): - componentType = namedtype.NamedTypes( - namedtype.NamedType('contextEngineId', univ.OctetString()), - namedtype.NamedType('contextName', univ.OctetString()), - namedtype.NamedType('data', rfc1905.PDUs()) - ) - -class ScopedPduData(univ.Choice): - componentType = namedtype.NamedTypes( - namedtype.NamedType('plaintext', ScopedPDU()), - namedtype.NamedType('encryptedPDU', univ.OctetString()), - ) - -class HeaderData(univ.Sequence): - componentType = namedtype.NamedTypes( - namedtype.NamedType('msgID', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))), - namedtype.NamedType('msgMaxSize', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647L))), - namedtype.NamedType('msgFlags', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 1))), - namedtype.NamedType('msgSecurityModel', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))) - ) - -class SNMPv3Message(univ.Sequence): - componentType = namedtype.NamedTypes( - namedtype.NamedType('msgVersion', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))), - namedtype.NamedType('msgGlobalData', HeaderData()), - namedtype.NamedType('msgSecurityParameters', univ.OctetString()), - namedtype.NamedType('msgData', ScopedPduData()) - ) - -# XXX move somewhere? -_snmpErrors = { - (1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0): 'unsupportedSecLevel', - (1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0): 'notInTimeWindow', - (1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0): 'unknownUserName', - (1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0): 'unknownEngineID', - (1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0): 'wrongDigest', - (1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0): 'decryptionError', - } - -class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): - messageProcessingModelID = 3 # SNMPv3 - _snmpMsgSpec = SNMPv3Message() - def __init__(self): - AbstractMessageProcessingModel.__init__(self) - self.__engineIDs = {} - self.__engineIDsExpQueue = {} - self.__expirationTimer = 0L - - # 7.1.1a - def prepareOutgoingMessage( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - expectResponse, - sendPduHandle - ): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpEngineID = snmpEngineID.syntax - - # 7.1.1b - msgID = self._newMsgID() - - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: new msgID %s' % msgID) - - peerSnmpEngineData = self.__engineIDs.get( - (transportDomain, transportAddress) - ) - - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: peer SNMP engine data %s for transport %s, address %s' % (peerSnmpEngineData, transportDomain, transportAddress)) - - # 7.1.4 - if contextEngineId is None: - if peerSnmpEngineData is None: - contextEngineId = snmpEngineID - else: - contextEngineId = peerSnmpEngineData['contextEngineId'] - # Defaulting contextEngineID to securityEngineID should - # probably be done on Agent side (see 7.1.3.d.2,) so this - # is a sort of workaround. - if not contextEngineId: - contextEngineId = peerSnmpEngineData['securityEngineID'] - # 7.1.5 - if not contextName: - contextName = '' - - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %s, contextName %s' % (contextEngineId, contextName)) - - # 7.1.6 - scopedPDU = ScopedPDU() - scopedPDU.setComponentByPosition(0, contextEngineId) - scopedPDU.setComponentByPosition(1, contextName) - scopedPDU.setComponentByPosition(2) - scopedPDU.getComponentByPosition(2).setComponentByType( - pdu.tagSet, pdu - ) - - # 7.1.7 - msg = SNMPv3Message() - - # 7.1.7a - msg.setComponentByPosition(0, 3) # version - - headerData = msg.setComponentByPosition(1).getComponentByPosition(1) - - # 7.1.7b - headerData.setComponentByPosition(0, msgID) - - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') - - # 7.1.7c - # XXX need to coerce MIB value as it has incompatible constraints set - headerData.setComponentByPosition(1, int(snmpEngineMaxMessageSize.syntax)) - - # 7.1.7d - msgFlags = 0 - if securityLevel == 1: - pass - elif securityLevel == 2: - msgFlags = msgFlags | 0x01 - elif securityLevel == 3: - msgFlags = msgFlags | 0x03 - else: - raise error.ProtocolError( - 'Unknown securityLevel %s' % securityLevel - ) - - if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet): - msgFlags = msgFlags | 0x04 - - headerData.setComponentByPosition(2, chr(msgFlags)) - - # 7.1.7e - # XXX need to coerce MIB value as it has incompatible constraints set - headerData.setComponentByPosition(3, int(securityModel)) - - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: %s' % (msg.prettyPrint(),)) - - smHandler = snmpEngine.securityModels.get(securityModel) - if smHandler is None: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityModel' - ) - - # 7.1.9.a - if rfc3411.unconfirmedClassPDUs.has_key(pdu.tagSet): - securityEngineID = snmpEngineID - else: - if peerSnmpEngineData is None: - # Force engineID discovery (rfc3414, 4) - securityEngineID = securityName = '' - securityLevel = 1 - # Clear possible auth&priv flags - headerData.setComponentByPosition(2, chr(msgFlags & 0xfc)) - # XXX - scopedPDU = ScopedPDU() - scopedPDU.setComponentByPosition(0, '') - scopedPDU.setComponentByPosition(1, '') - scopedPDU.setComponentByPosition(2) - - # Use dead-empty PDU for engine-discovery report - emptyPdu = pdu.clone() - pMod.apiPDU.setDefaults(emptyPdu) - - scopedPDU.getComponentByPosition(2).setComponentByType( - emptyPdu.tagSet, emptyPdu - ) - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: force engineID discovery') - else: - securityEngineID = peerSnmpEngineData['securityEngineID'] - - debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: securityEngineID %s' % securityEngineID) - - # 7.1.9.b - ( securityParameters, - wholeMsg ) = smHandler.generateRequestMsg( - snmpEngine, - self.messageProcessingModelID, - msg, - snmpEngineMaxMessageSize.syntax, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU - ) - - # Message size constraint verification - if len(wholeMsg) > snmpEngineMaxMessageSize.syntax: - raise error.StatusInformation(errorIndication='tooBig') - - # 7.1.9.c - if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet): - # XXX rfc bug? why stateReference should be created? - self._cachePushByMsgId( - msgID, - sendPduHandle=sendPduHandle, - msgID=msgID, - snmpEngineID=snmpEngineID, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - contextEngineId=contextEngineId, - contextName=contextName, - transportDomain=transportDomain, - transportAddress=transportAddress - ) - - return ( transportDomain, - transportAddress, - wholeMsg ) - - def prepareResponseMessage( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ): - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpEngineID = snmpEngineID.syntax - - # 7.1.2.b - cachedParams = self._cachePopByStateRef(stateReference) - msgID = cachedParams['msgID'] - contextEngineId = cachedParams['contextEngineId'] - contextName = cachedParams['contextName'] - securityModel = cachedParams['securityModel'] - securityName = cachedParams['securityName'] - securityLevel = cachedParams['securityLevel'] - securityStateReference = cachedParams['securityStateReference'] - reportableFlag = cachedParams['reportableFlag'] - maxMessageSize = cachedParams['msgMaxSize'] - transportDomain = cachedParams['transportDomain'] - transportAddress = cachedParams['transportAddress'] - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % (stateReference)) - - # 7.1.3 - if statusInformation is not None and statusInformation.has_key('oid'): - # 7.1.3a - if pdu is not None: - requestID = pdu.getComponentByPosition(0) - pduType = pdu.tagSet - else: - pduType = None - - # 7.1.3b - if pdu is None and not reportableFlag or \ - pduType is not None and \ - not rfc3411.confirmedClassPDUs.has_key(pduType): - raise error.StatusInformation( - errorIndication = 'loopTerminated' - ) - - # 7.1.3c - reportPDU = rfc1905.ReportPDU() - pMod.apiPDU.setVarBinds( - reportPDU, - ((statusInformation['oid'], statusInformation['val']),) - ) - pMod.apiPDU.setErrorStatus(reportPDU, 0) - pMod.apiPDU.setErrorIndex(reportPDU, 0) - if pdu is None: - pMod.apiPDU.setRequestID(reportPDU, 0) - else: - pMod.apiPDU.setRequestID(reportPDU, requestID) - - # 7.1.3d.1 - if statusInformation.has_key('securityLevel'): - securityLevel = statusInformation['securityLevel'] - else: - securityLevel = 1 - - # 7.1.3d.2 - if statusInformation.has_key('contextEngineId'): - contextEngineId = statusInformation['contextEngineId'] - else: - contextEngineId = snmpEngineID - - # 7.1.3d.3 - if statusInformation.has_key('contextName'): - contextName = statusInformation['contextName'] - else: - contextName = "" - - # 7.1.3e - pdu = reportPDU - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation) - # 7.1.4 - if not contextEngineId: - contextEngineId = snmpEngineID # XXX impl-dep manner - - # 7.1.5 - if not contextName: - contextName = '' - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %s, contextName %s' % (contextEngineId, contextName)) - - # 7.1.6 - scopedPDU = ScopedPDU() - scopedPDU.setComponentByPosition(0, contextEngineId) - scopedPDU.setComponentByPosition(1, contextName) - scopedPDU.setComponentByPosition(2) - scopedPDU.getComponentByPosition(2).setComponentByType( - pdu.tagSet, pdu - ) - - # 7.1.7 - msg = SNMPv3Message() - - # 7.1.7a - msg.setComponentByPosition(0, 3) # version - - headerData = msg.setComponentByPosition(1).getComponentByPosition(1) - - # 7.1.7b - headerData.setComponentByPosition(0, msgID) - - snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') - - # 7.1.7c - # XXX need to coerce MIB value as it has incompatible constraints set - headerData.setComponentByPosition(1, int(snmpEngineMaxMessageSize.syntax)) - - # 7.1.7d - msgFlags = 0 - if securityLevel == 1: - pass - elif securityLevel == 2: - msgFlags = msgFlags | 0x01 - elif securityLevel == 3: - msgFlags = msgFlags | 0x03 - else: - raise error.ProtocolError( - 'Unknown securityLevel %s' % securityLevel - ) - - if rfc3411.confirmedClassPDUs.has_key(pdu.tagSet): # XXX not needed? - msgFlags = msgFlags | 0x04 - - headerData.setComponentByPosition(2, chr(msgFlags)) - - # 7.1.7e - headerData.setComponentByPosition(3, securityModel) - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),)) - - smHandler = snmpEngine.securityModels.get(securityModel) - if smHandler is None: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityModel' - ) - - # 7.1.8a - try: - ( securityParameters, - wholeMsg ) = smHandler.generateResponseMsg( - snmpEngine, - self.messageProcessingModelID, - msg, - snmpEngineMaxMessageSize.syntax, - securityModel, - snmpEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ) - except error.StatusInformation, statusInformation: - # 7.1.8.b - raise - - debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: SM finished') - - # Message size constraint verification - if len(wholeMsg) > min(snmpEngineMaxMessageSize.syntax, maxMessageSize): - raise error.StatusInformation(errorIndication='tooBig') - - return ( transportDomain, transportAddress, wholeMsg ) - - # 7.2.1 - - def prepareDataElements( - self, - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ): - # 7.2.2 - try: - msg, restOfwholeMsg = decoder.decode( - wholeMsg, asn1Spec=self._snmpMsgSpec - ) - except PyAsn1Error: - snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') - snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 - raise error.StatusInformation( - errorIndication = 'parseError' - ) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) - - # 7.2.3 - headerData = msg.getComponentByPosition(1) - msgVersion = messageProcessingModel = msg.getComponentByPosition(0) - msgID = headerData.getComponentByPosition(0) - msgFlags = ord(str(headerData.getComponentByPosition(2))) - maxMessageSize = headerData.getComponentByPosition(1) - securityModel = headerData.getComponentByPosition(3) - securityParameters = msg.getComponentByPosition(2) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (msgVersion, msgID, securityModel)) - - # 7.2.4 - if not snmpEngine.securityModels.has_key(securityModel): - snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpUnknownSecurityModels') - snmpUnknownSecurityModels.syntax = snmpUnknownSecurityModels.syntax + 1 - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityModel' - ) - - # 7.2.5 - if msgFlags & 0x03 == 0x00: - securityLevel = 1 - elif (msgFlags & 0x03) == 0x01: - securityLevel = 2 - elif (msgFlags & 0x03) == 0x03: - securityLevel = 3 - else: - snmpInvalidMsgs = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInvalidMsgs') - snmpInvalidMsgs.syntax = snmpInvalidMsgs.syntax + 1 - raise error.StatusInformation( - errorIndication = 'invalidMsg' - ) - - if msgFlags & 0x04: - reportableFlag = 1 - else: - reportableFlag = 0 - - # 7.2.6 - smHandler = snmpEngine.securityModels[securityModel] - try: - ( securityEngineID, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) = smHandler.processIncomingMsg( - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg - ) - debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded') - except error.StatusInformation, statusInformation: - debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM failed, statusInformation %s' % statusInformation) - if statusInformation.has_key('errorIndication'): - # 7.2.6a - if statusInformation.has_key('oid'): - # 7.2.6a1 - securityStateReference = statusInformation[ - 'securityStateReference' - ] - contextEngineId = statusInformation['contextEngineId'] - contextName = statusInformation['contextName'] - scopedPDU = statusInformation.get('scopedPDU') - if scopedPDU is not None: - pdu = scopedPDU.getComponentByPosition(2).getComponent() - else: - pdu = None - maxSizeResponseScopedPDU = statusInformation[ - 'maxSizeResponseScopedPDU' - ] - securityName = None # XXX secmod cache used - - # 7.2.6a2 - stateReference = self._newStateReference() - self._cachePushByStateRef( - stateReference, - msgVersion=messageProcessingModel, - msgID=msgID, - contextEngineId=contextEngineId, - contextName=contextName, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - securityStateReference=securityStateReference, - reportableFlag=reportableFlag, - msgMaxSize=maxMessageSize, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, - transportDomain=transportDomain, - transportAddress=transportAddress - ) - - # 7.2.6a3 - try: - snmpEngine.msgAndPduDsp.returnResponsePdu( - snmpEngine, - 3, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - 1, - pdu, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) - except error.StatusInformation: - pass - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: error reported') - # 7.2.6b - raise statusInformation - else: - # Sniff for engineIDs - k = (transportDomain, transportAddress) - if not self.__engineIDs.has_key(k): - contextEngineId, contextName, pdu = scopedPDU - - self.__engineIDs[k] = { - 'securityEngineID': securityEngineID, - 'contextEngineId': contextEngineId, - 'contextName': contextName - } - - expireAt = self.__expirationTimer + 300 - if not self.__engineIDsExpQueue.has_key(expireAt): - self.__engineIDsExpQueue[expireAt] = [] - self.__engineIDsExpQueue[expireAt].append(k) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: cache securityEngineID %s for %s %s' % (securityEngineID, transportDomain, transportAddress)) - - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - snmpEngineID = snmpEngineID.syntax - - # 7.2.7 XXX PDU would be parsed here? - contextEngineId, contextName, pdu = scopedPDU - pdu = pdu.getComponent() # PDUs - - # 7.2.8 - pduVersion = api.protoVersion2c - - # 7.2.9 - pduType = pdu.tagSet - - # 7.2.10 - if rfc3411.responseClassPDUs.has_key(pduType) or \ - rfc3411.internalClassPDUs.has_key(pduType): - # 7.2.10a - try: - cachedReqParams = self._cachePopByMsgId(msgID) - except error.ProtocolError: - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'dataMismatch' - ) - # 7.2.10b - sendPduHandle = cachedReqParams['sendPduHandle'] - else: - sendPduHandle = None - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID)) - - # 7.2.11 - if rfc3411.internalClassPDUs.has_key(pduType): - # 7.2.11a - varBinds = pMod.apiPDU.getVarBinds(pdu) - if varBinds: - statusInformation = error.StatusInformation( - errorIndication=_snmpErrors.get( - varBinds[0][0], 'errorReportReceived' - ), - oid=varBinds[0][0], - val=varBinds[0][1], - sendPduHandle=sendPduHandle - ) - - # 7.2.11b (incomplete implementation) - - # 7.2.11c - smHandler.releaseStateInformation(securityStateReference) - - # 7.2.11d - stateReference = None - - # 7.2.11e XXX may need to pass Reports up to app in some cases... - raise statusInformation - - statusInformation = None # no errors ahead - - # 7.2.12 - if rfc3411.responseClassPDUs.has_key(pduType): - # 7.2.12a -> noop - - # 7.2.12b - if securityModel != cachedReqParams['securityModel'] or \ - securityName != cachedReqParams['securityName'] or \ - securityLevel != cachedReqParams['securityLevel'] or \ - contextEngineId != cachedReqParams['contextEngineId'] or \ - contextName != cachedReqParams['contextName']: - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'dataMispatch' - ) - - # 7.2.12c - smHandler.releaseStateInformation(securityStateReference) - stateReference = None - - # 7.2.12d - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) - - # 7.2.13 - if rfc3411.confirmedClassPDUs.has_key(pduType): - # 7.2.13a - if securityEngineID != snmpEngineID: - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'engineIDMispatch' - ) - - # 7.2.13b - stateReference = self._newStateReference() - self._cachePushByStateRef( - stateReference, - msgVersion=messageProcessingModel, - msgID=msgID, - contextEngineId=contextEngineId, - contextName=contextName, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - securityStateReference=securityStateReference, - reportableFlag=reportableFlag, - msgMaxSize=maxMessageSize, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, - transportDomain=transportDomain, - transportAddress=transportAddress - ) - - debug.logger & debug.flagMP and debug.logger('prepareDataElements: new stateReference %s' % stateReference) - - # 7.2.13c - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) - - # 7.2.14 - if rfc3411.unconfirmedClassPDUs.has_key(pduType): - # This is not specified explicitly in RFC - smHandler.releaseStateInformation(securityStateReference) - return ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - pdu, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - None ) - - smHandler.releaseStateInformation(securityStateReference) - raise error.StatusInformation( - errorIndication = 'unknownPDU' - ) - - def __expireEnginesInfo(self): - if self.__engineIDsExpQueue.has_key(self.__expirationTimer): - for engineKey in self.__engineIDsExpQueue[self.__expirationTimer]: - del self.__engineIDs[engineKey] - debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %s' % (engineKey,)) - del self.__engineIDsExpQueue[self.__expirationTimer] - self.__expirationTimer = self.__expirationTimer + 1 - - def receiveTimerTick(self, snmpEngine, timeNow): - self.__expireEnginesInfo() diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/proxy/rfc2576.py python-pysnmp4-4.2.2/pysnmp/v4/proto/proxy/rfc2576.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/proxy/rfc2576.py 2007-10-05 17:41:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/proxy/rfc2576.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,306 +0,0 @@ -# PDU v1/v2c two-way proxy -from pysnmp.proto import rfc3411, error -from pysnmp.proto.api import v1, v2c -from pysnmp.smi import exval -from pysnmp import debug - -# 2.1.1 - -__v1ToV2ValueMap = { - v1.Integer.tagSet: v2c.Integer32(), - v1.OctetString.tagSet: v2c.OctetString(), - v1.Null.tagSet: v2c.Null(), - v1.ObjectIdentifier.tagSet: v2c.ObjectIdentifier(), - v1.IpAddress.tagSet: v2c.IpAddress(), - v1.Counter.tagSet: v2c.Counter32(), - v1.Gauge.tagSet: v2c.Gauge32(), - v1.TimeTicks.tagSet: v2c.TimeTicks(), - v1.Opaque.tagSet: v2c.Opaque() - } - -__v2ToV1ValueMap = { # XXX do not re-create same-type items? - v2c.Integer32.tagSet: v1.Integer(), - v2c.OctetString.tagSet: v1.OctetString(), - v2c.Null.tagSet: v1.Null(), - v2c.ObjectIdentifier.tagSet: v1.ObjectIdentifier(), - v2c.IpAddress.tagSet: v1.IpAddress(), - v2c.Counter32.tagSet: v1.Counter(), - v2c.Gauge32.tagSet: v1.Gauge(), - v2c.TimeTicks.tagSet: v1.TimeTicks(), - v2c.Opaque.tagSet: v1.Opaque() - } - -# PDU map - -__v1ToV2PduMap = { - v1.GetRequestPDU.tagSet: v2c.GetRequestPDU(), - v1.GetNextRequestPDU.tagSet: v2c.GetNextRequestPDU(), - v1.SetRequestPDU.tagSet: v2c.SetRequestPDU(), - v1.GetResponsePDU.tagSet: v2c.ResponsePDU(), - v1.TrapPDU.tagSet: v2c.SNMPv2TrapPDU() - } - -__v2ToV1PduMap = { - v2c.GetRequestPDU.tagSet: v1.GetRequestPDU(), - v2c.GetNextRequestPDU.tagSet: v1.GetNextRequestPDU(), - v2c.SetRequestPDU.tagSet: v1.SetRequestPDU(), - v2c.ResponsePDU.tagSet: v1.GetResponsePDU(), - v2c.SNMPv2TrapPDU.tagSet: v1.TrapPDU(), - v2c.GetBulkRequestPDU.tagSet: v1.GetNextRequestPDU() # 4.1.1 - } - -__sysUpTime = (1,3,6,1,2,1,1,3) -__snmpTrapAddress = (1,3,6,1,6,3,18,1,3,0) -__snmpTrapOID = (1,3,6,1,6,3,1,1,4,1,0) -__snmpTrapEnterprise = (1,3,6,1,6,3,1,1,4,3,0) -try: - import socket - __agentAddress = v1.IpAddress(socket.gethostbyname(socket.gethostname())) -except: - __agentAddress = v1.IpAddress('0.0.0.0') - -# Trap map - -__v1ToV2TrapMap = { - 0: (1,3,6,1,6,3,1,1,5,1), - 1: (1,3,6,1,6,3,1,1,5,2), - 2: (1,3,6,1,6,3,1,1,5,3), - 3: (1,3,6,1,6,3,1,1,5,4), - 4: (1,3,6,1,6,3,1,1,5,5), - 5: (1,3,6,1,6,3,1,1,5,6) - } - -__v2ToV1TrapMap = { - (1,3,6,1,6,3,1,1,5,1): 0, - (1,3,6,1,6,3,1,1,5,2): 1, - (1,3,6,1,6,3,1,1,5,3): 2, - (1,3,6,1,6,3,1,1,5,4): 3, - (1,3,6,1,6,3,1,1,5,5): 4, - (1,3,6,1,6,3,1,1,5,6): 5 - } - -# 4.3 - -__v2ToV1ErrorMap = { - 0: 0, - 1: 1, - 5: 5, - 10: 3, - 9: 3, - 7: 3, - 8: 3, - 12: 3, - 6: 2, - 17: 2, - 11: 2, - 18: 2, - 13: 5, - 14: 5, - 15: 5, - 16: 2 - } - -def v1ToV2(v1Pdu, origV2Pdu=None): - pduType = v1Pdu.tagSet - v2Pdu = __v1ToV2PduMap[pduType].clone() - v2c.apiPDU.setDefaults(v2Pdu) - - debug.logger & debug.flagPrx and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint()) - - v2VarBinds = [] - - # 3.1 - if rfc3411.notificationClassPDUs.has_key(pduType): - # 3.1.1 - sysUpTime = v1.apiTrapPDU.getTimeStamp(v1Pdu) - - # 3.1.2 - genericTrap = v1.apiTrapPDU.getGenericTrap(v1Pdu) - if genericTrap == 6: - snmpTrapOIDParam = v1.apiTrapPDU.getEnterprise(v1Pdu) + (0,) + \ - (v1.apiTrapPDU.getSpecificTrap(v1Pdu),) - - # 3.1.3 - else: - snmpTrapOIDParam = v2c.ObjectIdentifier( - __v1ToV2TrapMap[genericTrap] - ) - - v2VarBinds.append((__sysUpTime, sysUpTime)) - v2VarBinds.append((__snmpTrapOID, snmpTrapOIDParam)) - v2VarBinds.append( - (__snmpTrapEnterprise, v1.apiTrapPDU.getEnterprise(v1Pdu)) - ) - - # 3.1.4 - v2VarBinds.append( - (__snmpTrapAddress, v1.apiTrapPDU.getAgentAddr(v1Pdu)) - ) - - varBinds = v1.apiTrapPDU.getVarBinds(v1Pdu) - else: - varBinds = v1.apiPDU.getVarBinds(v1Pdu) - - # Translate Var-Binds - for oid, v1Val in varBinds: - # 2.1.1.11 - if v1Val.tagSet == v1.NetworkAddress.tagSet: - v1Val = v1Val.getComponent() - v2VarBinds.append( - (oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val)) - ) - - if rfc3411.responseClassPDUs.has_key(pduType): - # 4.1.2.2.1&2 - errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu)) - errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu)) - if errorStatus == 2: # noSuchName - if origV2Pdu.tagSet == v2c.GetNextRequestPDU.tagSet: - v2VarBinds[errorIndex-1] = ( - v2VarBinds[errorIndex-1][0], exval.endOfMib - ) - else: - v2VarBinds[errorIndex-1] = ( - v2VarBinds[errorIndex-1][0], exval.noSuchObject - ) - else: # one-to-one mapping - v2c.apiPDU.setErrorStatus(v2Pdu, errorStatus) - v2c.apiPDU.setErrorIndex(v2Pdu, errorIndex) - - # 4.1.2.1 --> no-op - - if not rfc3411.notificationClassPDUs.has_key(pduType): - v2c.apiPDU.setRequestID(v2Pdu, long(v1.apiPDU.getRequestID(v1Pdu))) - - v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds) - - debug.logger & debug.flagPrx and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint()) - - return v2Pdu - -def v2ToV1(v2Pdu, origV1Pdu=None): - debug.logger & debug.flagPrx and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint()) - - pduType = v2Pdu.tagSet - - v1Pdu = __v2ToV1PduMap[pduType].clone() - - v2VarBinds = v2c.apiPDU.getVarBinds(v2Pdu) - v1VarBinds = [] - - if rfc3411.notificationClassPDUs.has_key(pduType): - v1.apiTrapPDU.setDefaults(v1Pdu) - else: - v1.apiPDU.setDefaults(v1Pdu) - - # 3.2 - if rfc3411.notificationClassPDUs.has_key(pduType): - # 3.2.1 - (snmpTrapOID, snmpTrapOIDParam) = v2VarBinds[1] - if snmpTrapOID != __snmpTrapOID: - raise error.ProtocolError('Second OID not snmpTrapOID') - - if __v2ToV1TrapMap.has_key(snmpTrapOIDParam): - for oid, val in v2VarBinds: - if oid == __snmpTrapEnterprise: - v1.apiTrapPDU.setEnterprise(v1Pdu, val) - break - else: - # snmpTraps - v1.apiTrapPDU.setEnterprise(v1Pdu, (1, 3, 6, 1, 6, 3, 1, 1, 5)) - else: - if snmpTrapOIDParam[-2] == 0: - v1.apiTrapPDU.setEnterprise(v1Pdu, snmpTrapOIDParam[:-2]) - else: - v1.apiTrapPDU.setEnterprise(v1Pdu, snmpTrapOIDParam[:-1]) - - # 3.2.2 - for oid, val in v2VarBinds: - # snmpTrapAddress - if oid == __snmpTrapAddress: - v1.apiTrapPDU.setAgentAddr(v1Pdu, val) - break - else: - v1.apiTrapPDU.setAgentAddr(v1Pdu, __agentAddress) - - # 3.2.3 - if __v2ToV1TrapMap.has_key(snmpTrapOIDParam): - v1.apiTrapPDU.setGenericTrap(v1Pdu, __v2ToV1TrapMap[snmpTrapOIDParam]) - else: - v1.apiTrapPDU.setGenericTrap(v1Pdu, 6) - - # 3.2.4 - if __v2ToV1TrapMap.has_key(snmpTrapOIDParam): - v1.apiTrapPDU.setSpecificTrap(v1Pdu, 0) - else: - v1.apiTrapPDU.setSpecificTrap(v1Pdu, snmpTrapOIDParam[-1]) - - # 3.2.5 - v1.apiTrapPDU.setTimeStamp(v1Pdu, v2VarBinds[0][1]) - - __v2VarBinds = [] - for oid, val in v2VarBinds[2:]: - if __v2ToV1TrapMap.has_key(oid) or \ - oid in (__sysUpTime, __snmpTrapAddress, - __snmpTrapEnterprise): - continue - __v2VarBinds.append((oid, val)) - v2VarBinds = __v2VarBinds; - - # 3.2.6 --> done below - - if rfc3411.responseClassPDUs.has_key(pduType): - idx = len(v2VarBinds)-1 - while idx >= 0: - # 4.1.2.1 - oid, val = v2VarBinds[idx] - if v2c.Counter64.tagSet == val.tagSet: - if origV1Pdu.tagSet == v1.GetRequestPDU.tagSet: - v1.apiPDU.setErrorStatus(v1Pdu, 2) - v1.apiPDU.setErrorIndex(v1Pdu, idx+1) - break - elif origV1Pdu.tagSet == v1.GetNextRequestPDU.tagSet: - raise error.StatusInformation(idx=idx, pdu=v2Pdu) - else: - raise error.ProtocolError('Counter64 on the way') - - # 4.1.2.2.1&2 - if exval.noSuchInstance.tagSet == val.tagSet or \ - exval.noSuchObject.tagSet == val.tagSet or \ - exval.endOfMib.tagSet == val.tagSet: - v1.apiPDU.setErrorStatus(v1Pdu, 2) - v1.apiPDU.setErrorIndex(v1Pdu, idx+1) - - idx = idx - 1 - - # 4.1.2.3.1 - v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu) - if v2ErrorStatus: - v1.apiPDU.setErrorStatus( - v1Pdu, __v2ToV1ErrorMap[v2ErrorStatus] - ) - v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu)) - - # Translate Var-Binds - for oid, v2Val in v2VarBinds: - # 2.1.1.11 - if v2Val.tagSet == v2c.IpAddress.tagSet: - v1Val = v1.NetworkAddress().setComponentByPosition( - 0, __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val) - ) - else: - v1Val = __v2ToV1ValueMap[v2Val.tagSet].clone(v2Val) - v1VarBinds.append((oid, v1Val)) - - if rfc3411.notificationClassPDUs.has_key(pduType): - v1.apiTrapPDU.setVarBinds(v1Pdu, v1VarBinds) - else: - v1.apiPDU.setVarBinds(v1Pdu, v1VarBinds) - - v1.apiPDU.setRequestID( - v1Pdu, v2c.apiPDU.getRequestID(v2Pdu) - ) - - debug.logger & debug.flagPrx and debug.logger('v2ToV1: v1Pdu %s' % v1Pdu.prettyPrint()) - - return v1Pdu diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/rfc1155.py python-pysnmp4-4.2.2/pysnmp/v4/proto/rfc1155.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/rfc1155.py 2005-06-28 17:39:58.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/rfc1155.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -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) - ) - subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( - 4, 4 - ) - - def prettyIn(self, value): return ipAddressPrettyIn(value) - def prettyOut(self, value): return ipAddressPrettyOut(value) - -class Counter(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class NetworkAddress(univ.Choice): - componentType = namedtype.NamedTypes( - namedtype.NamedType('internet', IpAddress()) - ) - -class Gauge(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class TimeTicks(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class Opaque(univ.OctetString): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) - ) - -class ObjectName(univ.ObjectIdentifier): pass - -class TypeCoercionHackMixIn: # XXX - # Reduce ASN1 type check to simple tag check as SMIv2 objects may - # not be constraints-compatible with those used in SNMP PDU. - def _verifyComponent(self, idx, value): - componentType = self._componentType - if componentType: - if idx >= len(componentType): - raise PyAsn1Error( - 'Component type error out of range' - ) - t = componentType[idx].getType() - if not t.getTagSet().isSuperTagSetOf(value.getTagSet()): - raise PyAsn1Error('Component type error %s vs %s' % - (repr(t), repr(value))) - -class SimpleSyntax(TypeCoercionHackMixIn, univ.Choice): - componentType = namedtype.NamedTypes( - namedtype.NamedType('number', univ.Integer()), - namedtype.NamedType('string', univ.OctetString()), - namedtype.NamedType('object', univ.ObjectIdentifier()), - namedtype.NamedType('empty', univ.Null()) - ) - -class ApplicationSyntax(TypeCoercionHackMixIn, univ.Choice): - componentType = namedtype.NamedTypes( - namedtype.NamedType('address', NetworkAddress()), - namedtype.NamedType('counter', Counter()), - namedtype.NamedType('gauge', Gauge()), - namedtype.NamedType('ticks', TimeTicks()), - namedtype.NamedType('arbitrary', Opaque()) - ) - -class ObjectSyntax(univ.Choice): - componentType = namedtype.NamedTypes( - namedtype.NamedType('simple', SimpleSyntax()), - namedtype.NamedType('application-wide', ApplicationSyntax()) - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/rfc1157.py python-pysnmp4-4.2.2/pysnmp/v4/proto/rfc1157.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/rfc1157.py 2005-06-22 18:48:43.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/rfc1157.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -from pyasn1.type import univ, tag, namedtype, namedval -from pysnmp.proto import rfc1155 - -class VarBind(univ.Sequence): - componentType = namedtype.NamedTypes( - namedtype.NamedType('name', rfc1155.ObjectName()), - namedtype.NamedType('value', rfc1155.ObjectSyntax()) - ) -class VarBindList(univ.SequenceOf): - componentType = VarBind() - -class _RequestBase(univ.Sequence): - componentType = namedtype.NamedTypes( - namedtype.NamedType('request-id', univ.Integer()), - namedtype.NamedType('error-status', univ.Integer(namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5)))), - namedtype.NamedType('error-index', univ.Integer()), - namedtype.NamedType('variable-bindings', VarBindList()) - ) - -class GetRequestPDU(_RequestBase): - tagSet = _RequestBase.tagSet.tagImplicitly( - tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0) - ) -class GetNextRequestPDU(_RequestBase): - tagSet = _RequestBase.tagSet.tagImplicitly( - tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1) - ) -class GetResponsePDU(_RequestBase): - tagSet = _RequestBase.tagSet.tagImplicitly( - tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2) - ) -class SetRequestPDU(_RequestBase): - tagSet = _RequestBase.tagSet.tagImplicitly( - tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3) - ) - -class TrapPDU(univ.Sequence): - tagSet = univ.Sequence.tagSet.tagImplicitly( - tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 4) - ) - componentType = namedtype.NamedTypes( - namedtype.NamedType('enterprise', univ.ObjectIdentifier()), - namedtype.NamedType('agent-addr', rfc1155.NetworkAddress()), - namedtype.NamedType('generic-trap', univ.Integer().clone(namedValues=namedval.NamedValues(('coldStart', 0), ('warmStart', 1), ('linkDown', 2), ('linkUp', 3), ('authenticationFailure', 4), ('egpNeighborLoss', 5), ('enterpriseSpecific', 6)))), - namedtype.NamedType('specific-trap', univ.Integer()), - namedtype.NamedType('time-stamp', rfc1155.TimeTicks()), - namedtype.NamedType('variable-bindings', VarBindList()) - ) - -class PDUs(univ.Choice): - componentType = namedtype.NamedTypes( - namedtype.NamedType('get-request', GetRequestPDU()), - namedtype.NamedType('get-next-request', GetNextRequestPDU()), - namedtype.NamedType('get-response', GetResponsePDU()), - namedtype.NamedType('set-request', SetRequestPDU()), - namedtype.NamedType('trap', TrapPDU()) - ) - -class Message(univ.Sequence): - componentType = namedtype.NamedTypes( - namedtype.NamedType('version', univ.Integer(namedValues = namedval.NamedValues(('version-1', 0)))), - namedtype.NamedType('community', univ.OctetString()), - namedtype.NamedType('data', PDUs()) - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/rfc1902.py python-pysnmp4-4.2.2/pysnmp/v4/proto/rfc1902.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/rfc1902.py 2007-02-07 13:01:31.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/rfc1902.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,199 +0,0 @@ -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 - ) - -class Integer32(univ.Integer): - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - -2147483648L, 2147483647L - ) - -class OctetString(univ.OctetString): - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueSizeConstraint( - 0, 65535 - ) - # rfc1902 uses a notion of "fixed length string" what might mean - # having zero-range size constraint applied. The following is - # supposed to be used for setting and querying this property. - - fixedLength = None - - def setFixedLength(self, value): - self.fixedLength = value - return self - - def isFixedLength(self): - return self.fixedLength is not None - - def getFixedLength(self): - return self.fixedLength - -class IpAddress(univ.OctetString): - tagSet = univ.OctetString.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) - ) - subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( - 4, 4 - ) - fixedLength = 4 - def prettyIn(self, value): return rfc1155.ipAddressPrettyIn(value) - def prettyOut(self, value): return rfc1155.ipAddressPrettyOut(value) - -class Counter32(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class Gauge32(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class Unsigned32(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class TimeTicks(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 4294967295L - ) - -class Opaque(univ.OctetString): - tagSet = univ.OctetString.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) - ) - -class Counter64(univ.Integer): - tagSet = univ.Integer.tagSet.tagImplicitly( - tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x06) - ) - subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( - 0, 18446744073709551615L - ) - -class Bits(univ.OctetString): - namedValues = namedval.NamedValues() - def __init__(self, value=None, tagSet=None, subtypeSpec=None, - namedValues=None): - if namedValues is None: - self.__namedValues = self.namedValues - else: - self.__namedValues = namedValues - univ.OctetString.__init__( - self, value, tagSet, subtypeSpec - ) - - def prettyIn(self, bits): - if type(bits) not in (types.TupleType, types.ListType): - return str(bits) # raw bitstring - octets = [] - for bit in bits: # tuple of named bits - v = self.__namedValues.getValue(bit) - if v is None: - raise error.ProtocolError( - 'Unknown named bit %s' % bit - ) - d, m = divmod(v, 8) - 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)) - - def prettyOut(self, value): - names = [] - octets = tuple(map(None, str(value))) - i = 0 - while i < len(octets): - v = ord(octets[i]) - j = 7 - while j >= 0: - if v & (0x01< noop - - # 4.3.3 - for pduType in pduTypes: - k = (str(contextEngineId), pduType) - if self.__appsRegistration.has_key(k): - raise error.ProtocolError( - 'Duplicate registration %s/%s' % (contextEngineId, pduType) - ) - - # 4.3.4 - self.__appsRegistration[k] = processPdu - - debug.logger & debug.flagDsp and debug.logger('registerContextEngineId: contextEngineId %s pduTypes %s' % (contextEngineId, pduTypes)) - # 4.4.1 - def unregisterContextEngineId(self, contextEngineId, pduTypes): - """Unregister application with dispatcher""" - # 4.3.4 - if contextEngineId is None: - # Default to local snmpEngineId - contextEngineId, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - - for pduType in pduTypes: - k = (str(contextEngineId), pduType) - if self.__appsRegistration.has_key(k): - del self.__appsRegistration[k] - - debug.logger & debug.flagDsp and debug.logger('unregisterContextEngineId: contextEngineId %s pduTypes %s' % (contextEngineId, pduTypes)) - - def getRegisteredApp(self, contextEngineId, pduType): - k = ( str(contextEngineId), pduType ) - if self.__appsRegistration.has_key(k): - return self.__appsRegistration[k] - k = ( '', pduType ) - if self.__appsRegistration.has_key(k): - return self.__appsRegistration[k] # wildcard - - # Dispatcher <-> application API - - # 4.1.1 - - def sendPdu( - self, - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - expectResponse - ): - """PDU dispatcher -- prepare and serialize a request or notification""" - # 4.1.1.2 - mpHandler = snmpEngine.messageProcessingSubsystems.get( - int(messageProcessingModel) - ) - if mpHandler is None: - raise error.StatusInformation( - errorIndication='unsupportedMsgProcessingModel' - ) - - debug.logger & debug.flagDsp and debug.logger('sendPdu: PDU %s' % PDU.prettyPrint()) - - # 4.1.1.3 - sendPduHandle = self.__newSendPduHandle() - if expectResponse: - self.__cacheAdd( - sendPduHandle, - messageProcessingModel=messageProcessingModel, - sendPduHandle=sendPduHandle, - expectResponse=expectResponse - ) - - debug.logger & debug.flagDsp and debug.logger('sendPdu: new sendPduHandle %s' % sendPduHandle) - - # 4.1.1.4 & 4.1.1.5 - try: - ( destTransportDomain, - destTransportAddress, - outgoingMessage ) = mpHandler.prepareOutgoingMessage( - snmpEngine, - transportDomain, - transportAddress, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - expectResponse, - sendPduHandle - ) - debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded') - except error.StatusInformation, statusInformation: -# XXX is it still needed here? -# self.releaseStateInformation(snmpEngine, sendPduHandle, messageProcessingModel) - raise - - # 4.1.1.6 - if snmpEngine.transportDispatcher is None: - raise error.PySnmpError('Transport dispatcher not set') - snmpEngine.transportDispatcher.sendMessage( - outgoingMessage, destTransportDomain, destTransportAddress - ) - - # Update cache with orignal req params (used for retrying) - if expectResponse: - self.__cacheUpdate( - sendPduHandle, - transportDomain=transportDomain, - transportAddress=transportAddress, - securityModel=securityModel, - securityName=securityName, - securityLevel=securityLevel, - contextEngineId=contextEngineId, - contextName=contextName, - pduVersion=pduVersion, - PDU=PDU - ) - - return sendPduHandle - - # 4.1.2.1 - def returnResponsePdu( - self, - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ): - """PDU dispatcher -- prepare and serialize a response""" - # Extract input values and initialize defaults - mpHandler = snmpEngine.messageProcessingSubsystems.get( - int(messageProcessingModel) - ) - if mpHandler is None: - raise error.StatusInformation( - errorIndication='unsupportedMsgProcessingModel' - ) - - debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: PDU %s' % (PDU and PDU.prettyPrint() or "",)) - - # 4.1.2.2 - try: - ( destTransportDomain, - destTransportAddress, - outgoingMessage ) = mpHandler.prepareResponseMessage( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) - debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded') - except error.StatusInformation, statusInformation: - # 4.1.2.3 - raise - - # Handle oversized messages XXX transport constrains? - snmpEngineMaxMessageSize, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') - if snmpEngineMaxMessageSize.syntax and \ - len(outgoingMessage) > snmpEngineMaxMessageSize.syntax: - snmpSilentDrops, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') - snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 - raise error.MessageTooBigError() - - # 4.1.2.4 - snmpEngine.transportDispatcher.sendMessage( - outgoingMessage, - destTransportDomain, - destTransportAddress - ) - - # 4.2.1 - def receiveMessage( - self, - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ): - """Message dispatcher -- de-serialize message into PDU""" - # 4.2.1.1 - snmpInPkts, = self.mibInstrumController.mibBuilder.importSymbols( - '__SNMPv2-MIB', 'snmpInPkts' - ) - snmpInPkts.syntax = snmpInPkts.syntax + 1 - - # 4.2.1.2 - try: - restOfWholeMsg = '' # 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 - - debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion) - - messageProcessingModel = msgVersion - - mpHandler = snmpEngine.messageProcessingSubsystems.get( - int(messageProcessingModel) - ) - if mpHandler is None: - snmpInBadVersions, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadVersions') - snmpInBadVersions.syntax = snmpInBadVersions.syntax + 1 - return restOfWholeMsg - - # 4.2.1.3 -- no-op - - # 4.2.1.4 - try: - ( messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - pduType, - sendPduHandle, - maxSizeResponseScopedPDU, - statusInformation, - stateReference ) = mpHandler.prepareDataElements( - snmpEngine, - transportDomain, - transportAddress, - wholeMsg - ) - debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded') - except error.StatusInformation, statusInformation: - if statusInformation.has_key('sendPduHandle'): - # Dropped REPORT -- re-run pending reqs queue as some - # of them may be waiting for this REPORT - debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP failed, statusInformation %s' % statusInformation) - self.__expireRequest( - snmpEngine, - self.__cachePop(statusInformation['sendPduHandle']), - statusInformation - ) - return restOfWholeMsg - - debug.logger & debug.flagDsp and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint()) - - # 4.2.2 - if sendPduHandle is None: - # 4.2.2.1 (request or notification) - - debug.logger & debug.flagDsp and debug.logger('receiveMessage: pduType %s' % pduType) - # 4.2.2.1.1 - processPdu = self.getRegisteredApp(contextEngineId, pduType) - - # 4.2.2.1.2 - if processPdu is None: - # 4.2.2.1.2.a - snmpUnknownPDUHandlers, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownPDUHandlers') - snmpUnknownPDUHandlers.syntax = snmpUnknownPDUHandlers.syntax+1 - - # 4.2.2.1.2.b - statusInformation = { - 'errorIndication': 'unknownPDUHandler', - 'oid': snmpUnknownPDUHandlers.name, - 'val': snmpUnknownPDUHandlers.syntax - } - - debug.logger & debug.flagDsp and debug.logger('receiveMessage: unhandled PDU type') - - # XXX fails on unknown PDU - - try: - ( destTransportDomain, - destTransportAddress, - outgoingMessage ) = mpHandler.prepareResponseMessage( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference, - statusInformation - ) - except error.StatusInformation, statusInformation: - debug.logger & debug.flagDsp and debug.logger('receiveMessage: report failed, statusInformation %s' % statusInformation) - return restOfWholeMsg - - # 4.2.2.1.2.c - try: - snmpEngine.transportDispatcher.sendMessage( - outgoingMessage, - destTransportDomain, - destTransportAddress - ) - except PySnmpError: # XXX - pass - - debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded') - - # 4.2.2.1.2.d - return restOfWholeMsg - else: - # 4.2.2.1.3 - processPdu( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - maxSizeResponseScopedPDU, - stateReference - ) - debug.logger & debug.flagDsp and debug.logger('receiveMessage: processPdu succeeded') - return restOfWholeMsg - else: - # 4.2.2.2 (response) - - # 4.2.2.2.1 - cachedParams = self.__cachePop(sendPduHandle) - - # 4.2.2.2.2 - if cachedParams is None: - snmpUnknownPDUHandlers, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownPDUHandlers') - snmpUnknownPDUHandlers.syntax = snmpUnknownPDUHandlers.syntax+1 - return restOfWholeMsg - - debug.logger & debug.flagDsp and debug.logger('receiveMessage: cache read by sendPduHandle %s' % sendPduHandle) - - # 4.2.2.2.3 - # no-op ? XXX - - # 4.2.2.2.4 - processResponsePdu, timeoutAt, cbCtx = cachedParams[ - 'expectResponse' - ] - processResponsePdu( - snmpEngine, - messageProcessingModel, - securityModel, - securityName, - securityLevel, - contextEngineId, - contextName, - pduVersion, - PDU, - statusInformation, - cachedParams['sendPduHandle'], - cbCtx - ) - debug.logger & debug.flagDsp and debug.logger('receiveMessage: processResponsePdu succeeded') - return restOfWholeMsg - - def releaseStateInformation( - self, snmpEngine, sendPduHandle, messageProcessingModel - ): - mpHandler = snmpEngine.messageProcessingSubsystems.get( - int(messageProcessingModel) - ) - mpHandler.releaseStateInformation(sendPduHandle) - - # Cache expiration stuff - - def __expireRequest(self, snmpEngine,cachedParams,statusInformation=None): - processResponsePdu, timeoutAt, cbCtx = cachedParams['expectResponse'] - if statusInformation is None and time.time() < timeoutAt: - return - - debug.logger & debug.flagDsp and debug.logger('__expireRequest: req cachedParams %s' % cachedParams) - - # Fail timed-out requests - if not statusInformation: - statusInformation = error.StatusInformation( - errorIndication='requestTimedOut' - ) - self.releaseStateInformation( - snmpEngine, - cachedParams['sendPduHandle'], - cachedParams['messageProcessingModel'] - ) - processResponsePdu( - snmpEngine, - None, - None, - None, - None, - None, - None, - None, - None, - statusInformation, - cachedParams['sendPduHandle'], - cbCtx - ) - return 1 - - def receiveTimerTick(self, snmpEngine, timeNow): - self.__cacheExpire(snmpEngine, self.__expireRequest) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/base.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/base.py 2006-09-20 16:26:13.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -from pysnmp.proto import error - -class AbstractSecurityModel: - securityModelID = None - __stateReference = 0L - def __init__(self): - self.__cacheEntries = {} - - def processIncomingMsg( - self, - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg, - ): - raise error.ProtocolError( - 'Security model %s not implemented' % self - ) - - def generateRequestMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - ): - raise error.ProtocolError( - 'Security model %s not implemented' % self - ) - - def generateResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): - raise error.ProtocolError( - 'Security model %s not implemented' % self - ) - - # Caching stuff - - def _cachePush(self, **securityData): - stateReference = AbstractSecurityModel.__stateReference - AbstractSecurityModel.__stateReference = stateReference + 1 - self.__cacheEntries[stateReference] = securityData - return stateReference - - def _cachePop(self, stateReference): - securityData = self.__cacheEntries.get(stateReference) - if securityData is None: - raise error.ProtocolError( - 'Cache miss for stateReference=%s at %s' % - (stateReference, self) - ) - del self.__cacheEntries[stateReference] - return securityData - - def releaseStateInformation(self, stateReference): - self._cachePop(stateReference) - - def receiveTimerTick(self, snmpEngine, timeNow): - pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc2576.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc2576.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc2576.py 2007-07-24 15:45:38.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc2576.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,194 +0,0 @@ -# SNMP v1 & v2c security models implementation -from pyasn1.codec.ber import encoder -from pysnmp.proto.secmod import base -from pysnmp.smi.error import NoSuchInstanceError -from pysnmp.proto import error -from pysnmp import debug - -class SnmpV1SecurityModel(base.AbstractSecurityModel): - securityModelID = 1 - # According to rfc2576, community name <-> contextEngineId/contextName - # mapping is up to MP module for notifications but belongs to secmod - # responsibility for other PDU types. Since I do not yet understand - # the reason for this de-coupling, I've moved this code from MP-scope - # in here. - - def generateRequestMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineId, - securityName, - securityLevel, - scopedPDU - ): - msg, = globalData - contextEngineId, contextName, pdu = scopedPDU - - # rfc2576: 5.2.3 - ( snmpCommunityName, - snmpCommunitySecurityName, - snmpCommunityContextEngineId, - snmpCommunityContextName ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-COMMUNITY-MIB', - 'snmpCommunityName', - 'snmpCommunitySecurityName', - 'snmpCommunityContextEngineID', - 'snmpCommunityContextName' - ) - mibNodeIdx = snmpCommunitySecurityName - while 1: - try: - mibNodeIdx = snmpCommunitySecurityName.getNextNode( - mibNodeIdx.name - ) - except NoSuchInstanceError: - break - if mibNodeIdx.syntax != securityName: - continue - instId = mibNodeIdx.name[len(snmpCommunitySecurityName.name):] - mibNode = snmpCommunityContextEngineId.getNode( - snmpCommunityContextEngineId.name + instId - ) - if mibNode.syntax != contextEngineId: - continue - mibNode = snmpCommunityContextName.getNode( - snmpCommunityContextName.name + instId - ) - if mibNode.syntax != contextName: - continue - # XXX TODO: snmpCommunityTransportTag - mibNode = snmpCommunityName.getNode( - snmpCommunityName.name + instId - ) - securityParameters = mibNode.syntax - - debug.logger & debug.flagSM and debug.logger('generateRequestMsg: found community %s for securityName %s contextEngineId %s contextName %s' % (securityParameters, securityName, contextEngineId, contextName)) - - msg.setComponentByPosition(1, securityParameters) - msg.setComponentByPosition(2) - msg.getComponentByPosition(2).setComponentByType(pdu.tagSet, pdu) - wholeMsg = encoder.encode(msg) - return ( securityParameters, wholeMsg ) - - raise error.StatusInformation( - errorIndication = 'unknownCommunityName' - ) - - def generateResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): - # rfc2576: 5.2.2 - msg, = globalData - contextEngineId, contextName, pdu = scopedPDU - cachedSecurityData = self._cachePop(securityStateReference) - communityName = cachedSecurityData['communityName'] - - debug.logger & debug.flagSM and debug.logger('generateResponseMsg: recovered community %s by securityStateReference %s' % (communityName, securityStateReference)) - - msg.setComponentByPosition(1, communityName) - msg.setComponentByPosition(2) - msg.getComponentByPosition(2).setComponentByType(pdu.tagSet, pdu) - - wholeMsg = encoder.encode(msg) - return ( communityName, wholeMsg ) - - def processIncomingMsg( - self, - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg - ): - # rfc2576: 5.2.1 - ( communityName, srcTransport, destTransport ) = securityParameters - ( snmpCommunityName, - snmpCommunitySecurityName, - snmpCommunityContextEngineId, - snmpCommunityContextName - ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( - 'SNMP-COMMUNITY-MIB', - 'snmpCommunityName', - 'snmpCommunitySecurityName', - 'snmpCommunityContextEngineID', - 'snmpCommunityContextName' - ) - mibNodeIdx = snmpCommunityName - while 1: - try: - mibNodeIdx = snmpCommunityName.getNextNode( - mibNodeIdx.name - ) - except NoSuchInstanceError: - break - if mibNodeIdx.syntax != communityName: - continue - break - else: - snmpInBadCommunityNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-COMMUNITY-MIB', 'snmpInBadCommunityNames') - snmpInBadCommunityNames.syntax = snmpInBadCommunityNames.syntax+1 - raise error.StatusInformation( - errorIndication = 'unknownCommunityName' - ) - - # XXX TODO: snmpCommunityTransportTag - instId = mibNodeIdx.name[len(snmpCommunityName.name):] - communityName = snmpCommunityName.getNode( - snmpCommunityName.name + instId - ) - securityName = snmpCommunitySecurityName.getNode( - snmpCommunitySecurityName.name + instId - ) - contextEngineId = snmpCommunityContextEngineId.getNode( - snmpCommunityContextEngineId.name + instId - ) - contextName = snmpCommunityContextName.getNode( - snmpCommunityContextName.name + instId - ) - snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: looked up securityName %s contextEngineId %s contextName %s by communityName %s' % (securityName, contextEngineId, contextName, communityName)) - - stateReference = self._cachePush( - communityName=communityName.syntax - ) - - securityEngineID = snmpEngineID.syntax - securityName = securityName.syntax - scopedPDU = ( - contextEngineId.syntax, contextName.syntax, - msg.getComponentByPosition(2).getComponent() - ) - maxSizeResponseScopedPDU = maxMessageSize - 128 - securityStateReference = stateReference - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: generated maxSizeResponseScopedPDU %s securityStateReference %s' % (maxSizeResponseScopedPDU, securityStateReference)) - - return ( securityEngineID, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) - -class SnmpV2cSecurityModel(SnmpV1SecurityModel): - securityModelID = 2 - -# XXX -# contextEngineId/contextName goes to globalData diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/base.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/base.py 2006-10-01 19:29:28.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -from pysnmp.proto import error - -class AbstractAuthenticationService: - serviceID = None - # 7.2.4.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): - raise error.ProtocolError('no authentication') - - # 7.2.4.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): - raise error.ProtocolError('no authentication') diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/hmacmd5.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/hmacmd5.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/hmacmd5.py 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/hmacmd5.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,107 +0,0 @@ -from hashlib import md5 -import string -from pysnmp.proto.secmod.rfc3414.auth import base -from pysnmp.proto import error - -_twelveZeros = '\x00'*12 -_fortyEightZeros = '\x00'*48 - -# rfc3414: 6.2.4 - -class HmacMd5(base.AbstractAuthenticationService): - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol - __ipad = [0x36]*64 - __opad = [0x5C]*64 - - # 6.3.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): - # Here we expect calling secmod to indicate where the digest - # 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) - if l == -1: - raise error.ProtocolError('Cant locate digest placeholder') - wholeHead = wholeMsg[:l] - wholeTail = wholeMsg[l+12:] - - # 6.3.1.1 - - # 6.3.1.2a - extendedAuthKey = map(ord, str(authKey) + _fortyEightZeros) - - # 6.3.1.2b --> noop - - # 6.3.1.2c - k1 = string.join( - map(lambda x,y: chr(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), '' - ) - - # 6.3.1.3 - d1 = md5(k1+wholeMsg).digest() - - # 6.3.1.4 - d2 = md5(k2+d1).digest() - mac = d2[:12] - - # 6.3.1.5 & 6 - return '%s%s%s' % (wholeHead, mac, wholeTail) - - # 6.3.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): - # 6.3.2.1 & 2 - if len(authParameters) != 12: - raise error.StatusInformation( - errorIndication='authenticationError' - ) - - # 6.3.2.3 - l = string.find(wholeMsg, str(authParameters)) - 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 - ) - - # 6.3.2.4a - extendedAuthKey = map(ord, str(authKey) + _fortyEightZeros) - - # 6.3.2.4b --> noop - - # 6.3.2.4c - k1 = string.join( - map(lambda x,y: chr(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), '' - ) - - # 6.3.2.5a - d1 = md5(k1+authenticatedWholeMsg).digest() - - # 6.3.2.5b - d2 = md5(k2+d1).digest() - - # 6.3.2.5c - mac = d2[:12] - - # 6.3.2.6 - if mac != authParameters: - raise error.StatusInformation( - errorIndication='authenticationFailure' - ) - - return authenticatedWholeMsg diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/hmacsha.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/hmacsha.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/hmacsha.py 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/hmacsha.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -import string -from hashlib import sha1 -from pysnmp.proto.secmod.rfc3414.auth import base -from pysnmp.proto import error - -_twelveZeros = '\x00'*12 -_fortyFourZeros = '\x00'*44 - -# 7.2.4 - -class HmacSha(base.AbstractAuthenticationService): - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol - __ipad = [0x36]*64 - __opad = [0x5C]*64 - - # 7.3.1 - def authenticateOutgoingMsg(self, authKey, wholeMsg): - # 7.3.1.1 - # Here we expect calling secmod to indicate where the digest - # 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) - 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) - - # 7.3.1.2b -- noop - - # 7.3.1.2c - k1 = string.join( - map(lambda x,y: chr(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), '' - ) - - # 7.3.1.3 - d1 = sha1(k1+wholeMsg).digest() - - # 7.3.1.4 - d2 = sha1(k2+d1).digest() - mac = d2[:12] - - # 7.3.1.5 & 6 - return '%s%s%s' % (wholeHead, mac, wholeTail) - - # 7.3.2 - def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): - # 7.3.2.1 & 2 - if len(authParameters) != 12: - raise error.StatusInformation( - errorIndication='authenticationError' - ) - - # 7.3.2.3 - l = string.find(wholeMsg, str(authParameters)) - 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 - ) - - # 7.3.2.4a - extendedAuthKey = map(ord, str(authKey) + _fortyFourZeros) - - # 7.3.2.4b --> noop - - # 7.3.2.4c - k1 = string.join( - map(lambda x,y: chr(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), '' - ) - - # 7.3.2.5a - d1 = sha1(k1+authenticatedWholeMsg).digest() - - # 7.3.2.5b - d2 = sha1(k2+d1).digest() - - # 7.3.2.5c - mac = d2[:12] - - # 7.3.2.6 - if mac != authParameters: - raise error.StatusInformation( - errorIndication='authenticationFailure' - ) - - return authenticatedWholeMsg diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/noauth.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/noauth.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/auth/noauth.py 2005-08-05 14:27:10.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/auth/noauth.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -from pysnmp.proto.secmod.rfc3414.auth import base - -class NoAuth(base.AbstractAuthenticationService): - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1) # usmNoAuthProtocol diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/__init__.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/__init__.py 2005-06-14 10:49:57.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/__init__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -from pysnmp.proto.secmod.rfc3414 import service - -SnmpUSMSecurityModel = service.SnmpUSMSecurityModel diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/localkey.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/localkey.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/localkey.py 2012-05-24 04:49:25.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/localkey.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -# Convert plaintext passphrase into a localized key -from hashlib import md5, sha1 - -# RFC3414: A.2.1 -def hashPassphraseMD5(passphrase): - md = md5() - ringBuffer = passphrase * (64/len(passphrase)+1) - ringBufferLen = len(ringBuffer) - count = 0 - mark = 0 - while count < 16384: - e = mark + 64 - if e < ringBufferLen: - md.update(ringBuffer[mark:e]) - mark = e - else: - md.update( - ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] - ) - mark = e-ringBufferLen - count = count + 1 - return md.digest() - -def localizeKeyMD5(passKey, snmpEngineId): - return md5('%s%s%s' % (passKey, str(snmpEngineId), passKey)).digest() - -def passwordToKeyMD5(passphrase, snmpEngineId): - return localizeKeyMD5(hashPassphraseMD5(passphrase), snmpEngineId) - -# RFC3414: A.2.2 -def hashPassphraseSHA(passphrase): - md = sha1() - ringBuffer = passphrase * (64/len(passphrase)+1) - ringBufferLen = len(ringBuffer) - count = 0 - mark = 0 - while count < 16384: - e = mark + 64 - if e < ringBufferLen: - md.update(ringBuffer[mark:e]) - mark = e - else: - md.update( - ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] - ) - mark = e-ringBufferLen - count = count + 1 - return md.digest() - -def localizeKeySHA(passKey, snmpEngineId): - return sha1('%s%s%s' % (passKey, str(snmpEngineId), passKey)).digest() - -def passwordToKeySHA(passphrase, snmpEngineId): - return localizeKeySHA(hashPassphraseSHA(passphrase), snmpEngineId) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/priv/base.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/priv/base.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/priv/base.py 2006-10-01 19:29:28.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/priv/base.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -from pysnmp.proto import error - -class AbstractEncryptionService: - serviceID = None - def encryptData(self, mibInstrumController, encryptKey, - dataToEncrypt): - raise error.ProtocolError('no encryption') - - def decryptData(self, mibInstrumController, decryptKey, - privParameters, encryptedData): - raise error.ProtocolError('no encryption') diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/priv/des.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/priv/des.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/priv/des.py 2007-07-09 13:39:48.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/priv/des.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -import random, string -from pysnmp.proto.secmod.rfc3414.priv import base -from pyasn1.type import univ -from pysnmp.proto import error - -try: - from Crypto.Cipher import DES -except ImportError: - DES = None - -random.seed() - -# 8.2.4 - -class Des(base.AbstractEncryptionService): - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol - _localInt = long(random.random()*0xffffffffL) - # 8.1.1.1 - def __getEncryptionKey(self, privKey, snmpEngineBoots): - desKey = privKey[:8] - preIV = privKey[8:16] - - securityEngineBoots = long(snmpEngineBoots) - - salt = [ - securityEngineBoots>>24&0xff, - securityEngineBoots>>16&0xff, - securityEngineBoots>>8&0xff, - securityEngineBoots&0xff, - self._localInt>>24&0xff, - self._localInt>>16&0xff, - self._localInt>>8&0xff, - self._localInt&0xff - ] - if self._localInt == 0xffffffffL: - self._localInt = 0 - else: - self._localInt = self._localInt + 1 - - return desKey, \ - string.join(map(lambda x: chr(x), salt), ''), \ - string.join(map(lambda x,y: chr(x^ord(y)), salt, preIV), '') - - def __getDecryptionKey(self, privKey, salt): - return privKey[:8], string.join( - map(lambda x,y: chr(ord(x)^ord(y)), salt, privKey[8:16]), '' - ) - - # 8.2.4.1 - def encryptData(self, encryptKey, privParameters, dataToEncrypt): - if DES is None: - raise error.StatusInformation( - errorIndication='encryptionError' - ) - - snmpEngineBoots, snmpEngineTime, salt = privParameters - - # 8.3.1.1 - desKey, salt, iv = self.__getEncryptionKey( - str(encryptKey), snmpEngineBoots - ) - - # 8.3.1.2 - privParameters = univ.OctetString(salt) - - # 8.1.1.2 - desObj = DES.new(desKey, DES.MODE_CBC, iv) - plaintext = dataToEncrypt + '\x00' * (8 - len(dataToEncrypt) % 8) - ciphertext = desObj.encrypt(plaintext) - - # 8.3.1.3 & 4 - return univ.OctetString(ciphertext), privParameters - - # 8.2.4.2 - def decryptData(self, decryptKey, privParameters, encryptedData): - if DES is None: - raise error.StatusInformation( - errorIndication='decryptionError' - ) - - snmpEngineBoots, snmpEngineTime, salt = privParameters - - # 8.3.2.1 - if len(salt) != 8: - raise error.StatusInformation( - errorIndication='decryptionError' - ) - - # 8.3.2.2 - salt = str(salt) - - # 8.3.2.3 - desKey, iv = self.__getDecryptionKey(str(decryptKey), salt) - - # 8.3.2.4 -> 8.1.1.3 - if len(encryptedData) % 8 != 0: - raise error.StatusInformation( - errorIndication='decryptionError' - ) - - desObj = DES.new(desKey, DES.MODE_CBC, iv) - - # 8.3.2.6 - return desObj.decrypt(str(encryptedData)) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/priv/nopriv.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/priv/nopriv.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/priv/nopriv.py 2005-08-05 14:27:10.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/priv/nopriv.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -from pysnmp.proto.secmod.rfc3414.priv import base - -class NoPriv(base.AbstractEncryptionService): - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1) # usmNoPrivProtocol diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/service.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/service.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3414/service.py 2007-07-09 13:39:48.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3414/service.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,807 +0,0 @@ -# SNMP v3 USM model services -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 -from pysnmp.proto.secmod.rfc3826.priv import aes -from pysnmp.proto.secmod.rfc3414 import localkey -from pysnmp.smi.error import NoSuchInstanceError -from pysnmp.proto import rfc1155, error -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 - -# 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('msgUserName', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32))), - namedtype.NamedType('msgAuthenticationParameters', univ.OctetString()), - namedtype.NamedType('msgPrivacyParameters', univ.OctetString()) - ) - -class SnmpUSMSecurityModel(AbstractSecurityModel): - securityModelID = 3 - authServices = { - hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), - hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), - noauth.NoAuth.serviceID: noauth.NoAuth() - - } - privServices = { - des.Des.serviceID: des.Des(), - aes.Aes.serviceID: aes.Aes(), - nopriv.NoPriv.serviceID: nopriv.NoPriv() - } - _securityParametersSpec = UsmSecurityParameters() - def __init__(self): - AbstractSecurityModel.__init__(self) - self.__timeline = {} - self.__timelineExpQueue = {} - self.__expirationTimer = 0L - - def __getUserInfo( - self, mibInstrumController, securityEngineID, securityName - ): - usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' - ) - tblIdx = usmUserEntry.getInstIdFromIndices( - securityEngineID, securityName - ) - # Get protocols - usmUserSecurityName = usmUserEntry.getNode( - usmUserEntry.name + (3,) + tblIdx - ).syntax - usmUserAuthProtocol = usmUserEntry.getNode( - usmUserEntry.name + (5,) + tblIdx - ).syntax - usmUserPrivProtocol = usmUserEntry.getNode( - usmUserEntry.name + (8,) + tblIdx - ).syntax - # Get keys - pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( - 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' - ) - pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (1,) + tblIdx - ).syntax - pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (2,) + tblIdx - ).syntax - return ( - usmUserSecurityName, # XXX function needed? - usmUserAuthProtocol, - pysnmpUsmKeyAuthLocalized, - usmUserPrivProtocol, - pysnmpUsmKeyPrivLocalized - ) - - def __cloneUserInfo( - self, mibInstrumController, securityEngineID, securityName - ): - snmpEngineID, = mibInstrumController.mibBuilder.importSymbols( - '__SNMP-FRAMEWORK-MIB', 'snmpEngineID' - ) - # Proto entry - usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( - 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' - ) - tblIdx = usmUserEntry.getInstIdFromIndices( - snmpEngineID.syntax, securityName - ) - # Get proto protocols - usmUserSecurityName = usmUserEntry.getNode( - usmUserEntry.name + (3,) + tblIdx - ) - usmUserAuthProtocol = usmUserEntry.getNode( - usmUserEntry.name + (5,) + tblIdx - ) - usmUserPrivProtocol = usmUserEntry.getNode( - usmUserEntry.name + (8,) + tblIdx - ) - # Get proto keys - pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( - 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' - ) - pysnmpUsmKeyAuth = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (3,) + tblIdx - ) - pysnmpUsmKeyPriv = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (4,) + tblIdx - ) - - # Create new row from proto values - - tblIdx = usmUserEntry.getInstIdFromIndices( - securityEngineID, securityName - ) - # New row - mibInstrumController.writeVars( - ((usmUserEntry.name + (13,) + tblIdx, 4),) - ) - # Set protocols - usmUserEntry.getNode( - usmUserEntry.name + (3,) + tblIdx - ).syntax = usmUserSecurityName.syntax - usmUserEntry.getNode( - usmUserEntry.name + (5,) + tblIdx - ).syntax = usmUserAuthProtocol.syntax - usmUserEntry.getNode( - usmUserEntry.name + (8,) + tblIdx - ).syntax = usmUserPrivProtocol.syntax - - # Localize and set keys - pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( - 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' - ) - pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (1,) + tblIdx - ) - if usmUserAuthProtocol.syntax == hmacsha.HmacSha.serviceID: - localAuthKey = localkey.localizeKeySHA( - pysnmpUsmKeyAuth.syntax, securityEngineID - ) - elif usmUserAuthProtocol.syntax == hmacmd5.HmacMd5.serviceID: - localAuthKey = localkey.localizeKeyMD5( - pysnmpUsmKeyAuth.syntax, securityEngineID - ) - elif usmUserAuthProtocol.syntax == noauth.NoAuth.serviceID: - localAuthKey = None - else: - raise error.StatusInformation( - errorIndication = 'unsupportedAuthProtocol' - ) - if localAuthKey is not None: - pysnmpUsmKeyAuthLocalized.syntax = pysnmpUsmKeyAuthLocalized.syntax.clone(localAuthKey) - pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( - pysnmpUsmKeyEntry.name + (2,) + tblIdx - ) - if usmUserPrivProtocol.syntax == des.Des.serviceID or \ - usmUserPrivProtocol.syntax == aes.Aes.serviceID: - if usmUserAuthProtocol.syntax == hmacsha.HmacSha.serviceID: - localPrivKey = localkey.localizeKeySHA( - pysnmpUsmKeyPriv.syntax, securityEngineID - ) - else: - localPrivKey = localkey.localizeKeyMD5( - pysnmpUsmKeyPriv.syntax, securityEngineID - ) - elif usmUserPrivProtocol.syntax == nopriv.NoPriv.serviceID: - localPrivKey = None - else: - raise error.StatusInformation( - errorIndication = 'unsupportedPrivProtocol' - ) - if localPrivKey is not None: - pysnmpUsmKeyPrivLocalized.syntax = pysnmpUsmKeyPrivLocalized.syntax.clone(localPrivKey) - return ( - usmUserSecurityName.syntax, # XXX function needed? - usmUserAuthProtocol.syntax, - pysnmpUsmKeyAuthLocalized.syntax, - usmUserPrivProtocol.syntax, - pysnmpUsmKeyPrivLocalized.syntax - ) - - def __generateRequestOrResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): - snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax - # 3.1.1 - if securityStateReference is not None: - # 3.1.1a - cachedSecurityData = self._cachePop(securityStateReference) - usmUserName = cachedSecurityData['msgUserName'] - usmUserAuthProtocol = cachedSecurityData.get('usmUserAuthProtocol') - usmUserAuthKeyLocalized = cachedSecurityData.get( - 'usmUserAuthKeyLocalized' - ) - usmUserPrivProtocol = cachedSecurityData.get('usmUserPrivProtocol') - usmUserPrivKeyLocalized = cachedSecurityData.get( - 'usmUserPrivKeyLocalized' - ) - securityEngineID = snmpEngineID - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: user info read from cache') - elif securityName: - # 3.1.1b - try: - ( usmUserName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - securityEngineID, securityName - ) - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read user info') - except NoSuchInstanceError: - pysnmpUsmDiscovery, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery') - __reportUnknownName = not pysnmpUsmDiscovery.syntax - if not __reportUnknownName: - try: - ( usmUserName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__cloneUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - securityEngineID, - securityName - ) - except NoSuchInstanceError: - __reportUnknownName = 1 - - if __reportUnknownName: - raise error.StatusInformation( - errorIndication = 'unknownSecurityName' - ) - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info') - else: - # empty username used for engineID discovery - usmUserName = usmUserSecurityName = '' - usmUserAuthProtocol = usmUserAuthKeyLocalized = None - usmUserPrivProtocol = usmUserPrivKeyLocalized = None - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use empty USM data') - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: local user usmUserName %s usmUserAuthProtocol %s usmUserPrivProtocol %s by securityEngineID %s securityName %s' % (usmUserName, usmUserAuthProtocol, usmUserPrivProtocol, securityEngineID, securityName)) - - msg = globalData - - # 3.1.2 - if securityLevel == 3: - if not usmUserAuthProtocol or not usmUserPrivProtocol: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityLevel' - ) - - # 3.1.3 - if securityLevel == 3 or securityLevel == 2: - if not usmUserAuthProtocol: - raise error.StatusInformation( - errorIndication = 'unsupportedSecurityLevel' - ) - - securityParameters = UsmSecurityParameters() - - scopedPDUData = msg.setComponentByPosition(3).getComponentByPosition(3) - scopedPDUData.setComponentByPosition(0, scopedPDU) - - # 3.1.6a - if securityStateReference is None and ( # request type check added - securityLevel == 3 or securityLevel == 2 - ): - if self.__timeline.has_key(securityEngineID): - ( snmpEngineBoots, - snmpEngineTime, - latestReceivedEngineTime, - latestUpdateTimestamp) = self.__timeline[ - securityEngineID - ] - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline') - else: - # 2.3 XXX is this correct? - snmpEngineBoots = snmpEngineTime = 0 - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: no timeline for securityEngineID %s' % securityEngineID) - # 3.1.6.b - elif securityStateReference is not None: # XXX Report? - ( snmpEngineBoots, - snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') - snmpEngineBoots = snmpEngineBoots.syntax - snmpEngineTime = snmpEngineTime.syntax.clone() - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD') - # 3.1.6.c - else: - snmpEngineBoots = snmpEngineTime = 0 - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime') - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use snmpEngineBoots %s snmpEngineTime %s for securityEngineID %s' % (snmpEngineBoots, snmpEngineTime, securityEngineID)) - - # 3.1.4a - if securityLevel == 3: - privHandler = self.privServices.get(usmUserPrivProtocol) - if privHandler is None: - raise error.StatusInformation( - errorIndication = 'encryptionError' - ) - dataToEncrypt = encoder.encode(scopedPDU) - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU encoded') - - try: - ( encryptedData, - privParameters ) = privHandler.encryptData( - usmUserPrivKeyLocalized, - ( snmpEngineBoots, snmpEngineTime, None ), - dataToEncrypt - ) - except error.StatusInformation, statusInformation: - raise - - securityParameters.setComponentByPosition(5, privParameters) - scopedPDUData.setComponentByPosition(1, encryptedData) - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU ciphered') - - # 3.1.4b - elif securityLevel == 1 or securityLevel == 2: - securityParameters.setComponentByPosition(5, '') - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint()) - - # 3.1.5 - securityParameters.setComponentByPosition(0, securityEngineID) - securityParameters.setComponentByPosition(1, snmpEngineBoots) - securityParameters.setComponentByPosition(2, snmpEngineTime) - - # 3.1.7 - securityParameters.setComponentByPosition(3, usmUserName) - - # 3.1.8a - if securityLevel == 3 or securityLevel == 2: - authHandler = self.authServices.get(usmUserAuthProtocol) - if authHandler is None: - raise error.StatusInformation( - errorIndication = 'authenticationFailure' - ) - - # extra-wild hack to facilitate BER substrate in-place re-write - securityParameters.setComponentByPosition( - 4, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - ) - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) - - msg.setComponentByPosition(2, encoder.encode(securityParameters)) - - wholeMsg = encoder.encode(msg) - - try: - authenticatedWholeMsg = authHandler.authenticateOutgoingMsg( - usmUserAuthKeyLocalized, wholeMsg - ) - except error.StatusInformation, statusInformation: - raise - - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: auth outgoing msg') - # 3.1.8b - else: - securityParameters.setComponentByPosition(4, '') - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) - msg.setComponentByPosition(2, encoder.encode(securityParameters)) - authenticatedWholeMsg = encoder.encode(msg) - debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: plain outgoing msg') - - # 3.1.9 - return ( - msg.getComponentByPosition(2), - authenticatedWholeMsg - ) - - def generateRequestMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - ): - return self.__generateRequestOrResponseMsg( - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - None - ) - - def generateResponseMsg( - self, - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ): - return self.__generateRequestOrResponseMsg( - snmpEngine, - messageProcessingModel, - globalData, - maxMessageSize, - securityModel, - securityEngineID, - securityName, - securityLevel, - scopedPDU, - securityStateReference - ) - - # 3.2 - def processIncomingMsg( - self, - snmpEngine, - messageProcessingModel, - maxMessageSize, - securityParameters, - securityModel, - securityLevel, - wholeMsg, - msg # XXX - ): - # 3.2.1 - try: - securityParameters, rest = decoder.decode( - securityParameters, - asn1Spec=self._securityParametersSpec - ) - except PyAsn1Error: - snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') - snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 - raise error.StatusInformation( - errorIndication='parseError' - ) - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),)) - - # 3.2.9 -- moved up here to be able to report - # maxSizeResponseScopedPDU on error - maxSizeResponseScopedPDU = maxMessageSize - 512 # XXX - if maxSizeResponseScopedPDU < 0: - maxSizeResponseScopedPDU = 0 - - # 3.2.2 - securityEngineID = securityParameters.getComponentByPosition(0) - securityStateReference = self._cachePush( - msgUserName=securityParameters.getComponentByPosition(3) - ) - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cache read securityStateReference %s by msgUserName %s' % (securityStateReference, securityParameters.getComponentByPosition(3))) - - # Used for error reporting - contextEngineId = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax - contextName = '' - - # 3.2.3 - if not self.__timeline.has_key(securityEngineID): - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %s' % securityEngineID) - if securityEngineID: - # 3.2.3a XXX any other way to get auth engine in cache? - self.__timeline[securityEngineID] = ( - securityParameters.getComponentByPosition(1), - securityParameters.getComponentByPosition(2), - securityParameters.getComponentByPosition(2), - int(time.time()) - ) - - expireAt = self.__expirationTimer + 300 - if not self.__timelineExpQueue.has_key(expireAt): - self.__timelineExpQueue[expireAt] = [] - self.__timelineExpQueue[expireAt].append(securityEngineID) - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: store timeline for securityEngineID %s' % (securityEngineID,)) - else: - # 3.2.3b - usmStatsUnknownEngineIDs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs') - usmStatsUnknownEngineIDs.syntax = usmStatsUnknownEngineIDs.syntax+1 - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: null securityEngineID') - pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') - if pysnmpUsmDiscoverable.syntax: - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: request EngineID discovery') - raise error.StatusInformation( - errorIndication = 'unknownEngineID', - oid=usmStatsUnknownEngineIDs.name, - val=usmStatsUnknownEngineIDs.syntax, - securityStateReference=securityStateReference, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) - else: - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: will not discover EngineID') - # free securityStateReference XXX - raise error.StatusInformation( - errorIndication = 'unknownEngineID' - ) - - snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax - - msgAuthoritativeEngineID = securityParameters.getComponentByPosition(0) - msgUserName = securityParameters.getComponentByPosition(3) - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read from securityParams msgAuthoritativeEngineID %s msgUserName %s' % (msgAuthoritativeEngineID, msgUserName)) - - if msgUserName: - # 3.2.4 - try: - ( usmUserSecurityName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__getUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, msgAuthoritativeEngineID, msgUserName - ) - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read user info from LCD') - except NoSuchInstanceError: - pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') - __reportUnknownName = not pysnmpUsmDiscoverable.syntax - if not __reportUnknownName: - try: - ( usmUserSecurityName, - usmUserAuthProtocol, - usmUserAuthKeyLocalized, - usmUserPrivProtocol, - usmUserPrivKeyLocalized ) = self.__cloneUserInfo( - snmpEngine.msgAndPduDsp.mibInstrumController, - securityEngineID, - msgUserName - ) - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cloned user info') - except NoSuchInstanceError: - __reportUnknownName = 1 - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %s msgUserName %s' % (securityEngineID, msgUserName)) - if __reportUnknownName: - usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') - usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 - raise error.StatusInformation( - errorIndication = 'unknownSecurityName', - oid = usmStatsUnknownUserNames.name, - val = usmStatsUnknownUserNames.syntax, - securityStateReference=securityStateReference, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) - else: - # empty username used for engineID discovery - usmUserName = usmUserSecurityName = '' - usmUserAuthProtocol = usmUserAuthKeyLocalized = None - usmUserPrivProtocol = usmUserPrivKeyLocalized = None - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: now have usmUserSecurityName %s usmUserAuthProtocol %s usmUserPrivProtocol %s for msgUserName %s' % (usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, msgUserName)) - - # 3.2.5 - __reportError = 0 - if securityLevel == 3: - if not usmUserAuthProtocol or not usmUserPrivProtocol: - __reportError = 1 - elif securityLevel == 2: - if not usmUserAuthProtocol: - __reportError = 1 - if __reportError: - usmStatsUnsupportedSecLevels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnsupportedSecLevels') - usmStatsUnsupportedSecLevels.syntax = usmStatsUnsupportedSecLevels.syntax + 1 - raise error.StatusInformation( - errorIndication='unsupportedSecurityLevel', - oid=usmStatsUnknownEngineIDs.name, - val=usmStatsUnknownEngineIDs.syntax, - securityStateReference=securityStateReference, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) - - # 3.2.6 - if securityLevel == 3 or securityLevel == 2: - authHandler = self.authServices.get(usmUserAuthProtocol) - if authHandler is None: - raise error.StatusInformation( - errorIndication = 'authenticationFailure' - ) - try: - authenticatedWholeMsg = authHandler.authenticateIncomingMsg( - usmUserAuthKeyLocalized, - securityParameters.getComponentByPosition(4), - wholeMsg - ) - except error.StatusInformation: - usmStatsWrongDigests, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsWrongDigests') - usmStatsWrongDigests.syntax = usmStatsWrongDigests.syntax+1 - raise error.StatusInformation( - errorIndication = 'authenticationFailure', - oid=usmStatsWrongDigests.name, - val=usmStatsWrongDigests.syntax, - securityStateReference=securityStateReference, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authed') - # 3.2.7 - if securityLevel == 3 or securityLevel == 2: - if msgAuthoritativeEngineID == snmpEngineID: - # Authoritative SNMP engine: use local notion (SF bug #1649032) - ( snmpEngineBoots, - snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') - snmpEngineBoots = snmpEngineBoots.syntax - snmpEngineTime = snmpEngineTime.syntax.clone() - idleTime = 0 - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read snmpEngineBoots (%s), snmpEngineTime (%s) from LCD' % (snmpEngineBoots, snmpEngineTime)) - else: - # Non-authoritative SNMP engine: use cached estimates - if self.__timeline.has_key(securityEngineID): - ( snmpEngineBoots, - snmpEngineTime, - latestReceivedEngineTime, - latestUpdateTimestamp ) = self.__timeline[ - msgAuthoritativeEngineID - ] - # time passed since last talk with this SNMP engine - idleTime = int(time.time())-latestUpdateTimestamp - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read timeline snmpEngineBoots %s snmpEngineTime %s for msgAuthoritativeEngineID %s, idle time %s secs' % (snmpEngineBoots, snmpEngineTime, msgAuthoritativeEngineID, idleTime)) - else: - raise error.ProtocolError('Peer SNMP engine info missing') - - msgAuthoritativeEngineBoots = securityParameters.getComponentByPosition(1) - msgAuthoritativeEngineTime = securityParameters.getComponentByPosition(2) - - # 3.2.7a - if msgAuthoritativeEngineID == snmpEngineID: - if snmpEngineBoots == 2147483647L or \ - snmpEngineBoots != msgAuthoritativeEngineBoots or \ - abs(idleTime + int(snmpEngineTime) - \ - int(msgAuthoritativeEngineTime)) > 150: - usmStatsNotInTimeWindows, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsNotInTimeWindows') - usmStatsNotInTimeWindows.syntax = usmStatsNotInTimeWindows.syntax+1 - raise error.StatusInformation( - errorIndication = 'notInTimeWindow', - oid=usmStatsNotInTimeWindows.name, - val=usmStatsNotInTimeWindows.syntax, - securityStateReference=securityStateReference, - securityLevel=2, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) - # 3.2.7b - else: - # 3.2.7b.1 - if msgAuthoritativeEngineBoots > snmpEngineBoots or \ - msgAuthoritativeEngineBoots == snmpEngineBoots and \ - msgAuthoritativeEngineTime > latestReceivedEngineTime: - self.__timeline[msgAuthoritativeEngineID] = ( - msgAuthoritativeEngineBoots, - msgAuthoritativeEngineTime, - msgAuthoritativeEngineTime, - int(time.time()) - ) - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineID %s' % (msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineID)) - - # 3.2.7b.2 - if snmpEngineBoots == 2147483647L or \ - msgAuthoritativeEngineBoots < snmpEngineBoots or \ - msgAuthoritativeEngineBoots == snmpEngineBoots and \ - abs(idleTime + int(snmpEngineTime) - \ - int(msgAuthoritativeEngineTime)) > 150: - raise error.StatusInformation( - errorIndication = 'notInTimeWindow' - ) - - scopedPduData = msg.getComponentByPosition(3) - - # 3.2.8a - if securityLevel == 3: - privHandler = self.privServices.get(usmUserPrivProtocol) - if privHandler is None: - raise error.StatusInformation( - errorIndication = 'decryptionError' - ) - encryptedPDU = scopedPduData.getComponentByPosition(1) - if encryptedPDU is None: # no ciphertext - raise error.StatusInformation( - errorIndication = 'decryptionError' - ) - - try: - decryptedData = privHandler.decryptData( - usmUserPrivKeyLocalized, - ( securityParameters.getComponentByPosition(1), - securityParameters.getComponentByPosition(2), - securityParameters.getComponentByPosition(5) ), - encryptedPDU - ) - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: PDU deciphered') - except error.StatusInformation: - usmStatsDecryptionErrors, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsDecryptionErrors') - usmStatsDecryptionErrors.syntax = usmStatsDecryptionErrors.syntax+1 - raise error.StatusInformation( - errorIndication = 'decryptionError', - oid=usmStatsDecryptionErrors.name, - val=usmStatsDecryptionErrors.syntax, - securityStateReference=securityStateReference, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU - ) - scopedPduSpec = scopedPduData.setComponentByPosition(0).getComponentByPosition(0) - try: - scopedPDU, rest = decoder.decode( - decryptedData, asn1Spec=scopedPduSpec - ) - except PyAsn1Error, why: - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: PDU decoder failed %s' % why) - raise error.StatusInformation( - errorIndication = 'decryptionError' - ) - else: - # 3.2.8b - scopedPDU = scopedPduData.getComponentByPosition(0) - if scopedPDU is None: # no plaintext - raise error.StatusInformation( - errorIndication = 'decryptionError' - ) - - # 3.2.10 - securityName = usmUserSecurityName - - # 3.2.11 - self._cachePop(securityStateReference) - securityStateReference = self._cachePush( - msgUserName=securityParameters.getComponentByPosition(3), - usmUserAuthProtocol=usmUserAuthProtocol, - usmUserAuthKeyLocalized=usmUserAuthKeyLocalized, - usmUserPrivProtocol=usmUserPrivProtocol, - usmUserPrivKeyLocalized=usmUserPrivKeyLocalized - ) - - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cached msgUserName %s info by securityStateReference %s' % (msgUserName, securityStateReference)) - - # Delayed to include details - if not msgUserName and not securityEngineID: - usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') - usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 - raise error.StatusInformation( - errorIndication='unknownSecurityName', - oid=usmStatsUnknownUserNames.name, - val=usmStatsUnknownUserNames.syntax, - securityStateReference=securityStateReference, - securityEngineID=securityEngineID, - contextEngineId=contextEngineId, - contextName=contextName, - maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, - PDU=scopedPDU - ) - - # 3.2.12 - return ( securityEngineID, - securityName, - scopedPDU, - maxSizeResponseScopedPDU, - securityStateReference ) - - def __expireTimelineInfo(self): - if self.__timelineExpQueue.has_key(self.__expirationTimer): - for engineIdKey in self.__timelineExpQueue[self.__expirationTimer]: - del self.__timeline[engineIdKey] - debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %s' % (engineIdKey,)) - del self.__timelineExpQueue[self.__expirationTimer] - self.__expirationTimer = self.__expirationTimer + 1 - - def receiveTimerTick(self, snmpEngine, timeNow): - self.__expireTimelineInfo() diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3826/priv/aes.py python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3826/priv/aes.py --- python-pysnmp4-4.1.9a/pysnmp/v4/proto/secmod/rfc3826/priv/aes.py 2007-07-09 13:39:48.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/proto/secmod/rfc3826/priv/aes.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,115 +0,0 @@ -import random, string -from pysnmp.proto.secmod.rfc3414.priv import base -from pyasn1.type import univ -from pysnmp.proto import error - -try: - from Crypto.Cipher import AES -except ImportError: - AES = None - -random.seed() - -# RFC3826 - -# - -class Aes(base.AbstractEncryptionService): - serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol - _localInt = long(random.random()*0xffffffffffffffffL) - # 3.1.2.1 - def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime): - salt = [ - self._localInt>>56&0xff, - self._localInt>>48&0xff, - self._localInt>>40&0xff, - self._localInt>>32&0xff, - self._localInt>>24&0xff, - self._localInt>>16&0xff, - self._localInt>>8&0xff, - self._localInt&0xff - ] - - if self._localInt == 0xffffffffffffffffL: - self._localInt = 0 - else: - self._localInt = self._localInt + 1 - - salt = string.join(map(lambda x: chr(x), salt), '') - - return self.__getDecryptionKey(privKey, snmpEngineBoots, - snmpEngineTime, salt) + ( salt, ) - - def __getDecryptionKey(self, privKey, snmpEngineBoots, - snmpEngineTime, salt): - snmpEngineBoots, snmpEngineTime, salt = ( - long(snmpEngineBoots), long(snmpEngineTime), str(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[7]), - ord(salt[6]), - ord(salt[5]), - ord(salt[4]), - ord(salt[3]), - ord(salt[2]), - ord(salt[1]), - ord(salt[0]) - ] - - return privKey[:16], string.join(map(lambda x: chr(x), iv), '') - - - # 3.2.4.1 - def encryptData(self, encryptKey, privParameters, dataToEncrypt): - if AES is None: - raise error.StatusInformation( - errorIndication='encryptionError' - ) - - snmpEngineBoots, snmpEngineTime, salt = privParameters - - # 3.3.1.1 - aesKey, iv, salt = self.__getEncryptionKey( - str(encryptKey), snmpEngineBoots, snmpEngineTime - ) - - # 3.3.1.3 - aesObj = AES.new(aesKey, AES.MODE_CFB, iv) - ciphertext = aesObj.encrypt(dataToEncrypt) - - # 3.3.1.4 - return univ.OctetString(ciphertext), salt - - # 3.2.4.2 - def decryptData(self, decryptKey, privParameters, encryptedData): - if AES is None: - raise error.StatusInformation( - errorIndication='decryptionError' - ) - - snmpEngineBoots, snmpEngineTime, salt = privParameters - - # 3.3.2.1 - if len(salt) != 8: - raise error.StatusInformation( - errorIndication='decryptionError' - ) - - # 3.3.2.3 - aesKey, iv = self.__getDecryptionKey( - str(decryptKey), snmpEngineBoots, snmpEngineTime, salt - ) - - aesObj = AES.new(aesKey, AES.MODE_CFB, iv) - - # 3.3.2.4-6 - return aesObj.decrypt(str(encryptedData)) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/builder.py python-pysnmp4-4.2.2/pysnmp/v4/smi/builder.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/builder.py 2007-03-21 14:17:16.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/builder.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,171 +0,0 @@ -# MIB modules loader -import os -from pysnmp.smi import error -try: - import pysnmp_mibs -except ImportError: - pysnmp_mibs = None -from pysnmp import debug - -class MibBuilder: - def __init__(self): - self.lastBuildId = self._autoName = 0L - paths = ( - os.path.join(os.path.split(error.__file__)[0], 'mibs','instances'), - os.path.join(os.path.split(error.__file__)[0], 'mibs') - ) - if os.environ.has_key('PYSNMP_MIB_DIR'): - paths = paths + ( - os.path.join(os.path.split(os.environ['PYSNMP_MIB_DIR'])[0]), - ) - if pysnmp_mibs: - paths = paths + ( - os.path.join(os.path.split(pysnmp_mibs.__file__)[0]), - ) - self.mibSymbols = {} - self.__modSeen = {} - self.__modPathsSeen = {} - apply(self.setMibPath, paths) - - # MIB modules management - - def setMibPath(self, *mibPaths): - self.__mibPaths = map(os.path.normpath, mibPaths) - debug.logger & debug.flagBld and debug.logger('setMibPath: new MIB path %s' % (self.__mibPaths,)) - - def getMibPath(self): return tuple(self.__mibPaths) - - def loadModules(self, *modNames): - # Build a list of available modules - if not modNames: - modNames = {} - for mibPath in self.__mibPaths: - try: - for modName in os.listdir(mibPath): - if modName == '__init__.py' or modName[-3:] != '.py': - continue - modNames[modName[:-3]] = None - except OSError: - continue - modNames = modNames.keys() - if not modNames: - raise error.SmiError( - 'No MIB module to load at %s' % (self,) - ) - for modName in modNames: - for mibPath in self.__mibPaths: - modPath = os.path.join( - mibPath, modName + '.py' - ) - - debug.logger & debug.flagBld and debug.logger('loadModules: trying %s' % modPath) - - try: - open(modPath).close() - except IOError, why: - debug.logger & debug.flagBld and debug.logger('loadModules: open() %s' % why) - continue - - if self.__modPathsSeen.has_key(modPath): - debug.logger & debug.flagBld and debug.logger('loadModules: seen %s' % modPath) - continue - else: - self.__modPathsSeen[modPath] = 1 - - g = { 'mibBuilder': self } - - try: - execfile(modPath, g) - except StandardError, why: - del self.__modPathsSeen[modPath] - raise error.SmiError( - 'MIB module \"%s\" load error: %s' % (modPath, why) - ) - - self.__modSeen[modName] = modPath - - debug.logger & debug.flagBld and debug.logger('loadModules: loaded %s' % modPath) - - break - - if not self.__modSeen.has_key(modName): - raise error.SmiError( - 'MIB file \"%s.py\" not found in search path' % modName - ) - - return self - - def unloadModules(self, *modNames): - if not modNames: - modNames = self.mibSymbols.keys() - for modName in modNames: - if not self.mibSymbols.has_key(modName): - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - self.unexportSymbols(modName) - del self.__modPathsSeen[self.__modSeen[modName]] - del self.__modSeen[modName] - - debug.logger & debug.flagBld and debug.logger('unloadModules: ' % (modName)) - - return self - - def importSymbols(self, modName, *symNames): - r = () - for symName in symNames: - if not self.mibSymbols.has_key(modName): - self.loadModules(modName) - if not self.mibSymbols.has_key(modName): - raise error.SmiError( - 'No module %s loaded at %s' % (modName, self) - ) - if not self.mibSymbols[modName].has_key(symName): - raise error.SmiError( - 'No symbol %s::%s at %s' % (modName, symName, self) - ) - r = r + (self.mibSymbols[modName][symName],) - return r - - def exportSymbols(self, modName, *anonymousSyms, **namedSyms): - if not self.mibSymbols.has_key(modName): - self.mibSymbols[modName] = {} - mibSymbols = self.mibSymbols[modName] - - for symObj in anonymousSyms: - debug.logger & debug.flagBld and debug.logger('exportSymbols: anonymous symbol %s::__pysnmp_%ld' % (modName, self._autoName)) - mibSymbols['__pysnmp_%ld' % self._autoName] = symObj - self._autoName = self._autoName + 1 - - for symName, symObj in namedSyms.items(): - if mibSymbols.has_key(symName): - raise error.SmiError( - 'Symbol %s already exported at %s' % (symName, modName) - ) - if hasattr(symObj, 'label') and symObj.label: - symName = symObj.label - mibSymbols[symName] = symObj - - debug.logger & debug.flagBld and debug.logger('exportSymbols: symbol %s::%s' % (modName, symName)) - - self.lastBuildId = self.lastBuildId + 1 - - def unexportSymbols(self, modName, *symNames): - if not self.mibSymbols.has_key(modName): - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - mibSymbols = self.mibSymbols[modName] - if not symNames: - symNames = mibSymbols.keys() - for symName in symNames: - if not mibSymbols.has_key(symName): - raise error.SmiError( - 'No symbol %s::%s at %s' % (modName, symName, self) - ) - del mibSymbols[symName] - - debug.logger & debug.flagBld and debug.logger('unexportSymbols: symbol %s::%s' % (modName, symName)) - - self.lastBuildId = self.lastBuildId + 1 - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/error.py python-pysnmp4-4.2.2/pysnmp/v4/smi/error.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/error.py 2007-08-11 08:02:40.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/error.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -from pyasn1.error import PyAsn1Error -from pysnmp.error import PySnmpError - -class SmiError(PySnmpError, PyAsn1Error): pass -class MibOperationError(SmiError): - def __init__(self, **kwargs): self.__outArgs = kwargs - def __str__(self): return '%s(%s)' % ( - self.__class__.__name__, self.__outArgs - ) - def __getitem__(self, key): return self.__outArgs[key] - def has_key(self, key): return self.__outArgs.has_key(key) - def get(self, key, defVal=None): return self.__outArgs.get(key, defVal) - def keys(self): return self.__outArgs.keys() - def update(self, d): self.__outArgs.update(d) - -# Aligned with SNMPv2 PDU error-status -class GenError(MibOperationError): pass -class NoAccessError(MibOperationError): pass -class WrongTypeError(MibOperationError): pass -class WrongValueError(MibOperationError): pass -class NoCreationError(MibOperationError): pass -class InconsistentValueError(MibOperationError): pass -class ResourceUnavailableError(MibOperationError): pass -class CommitFailedError(MibOperationError): pass -class UndoFailedError(MibOperationError): pass -class AuthorizationError(MibOperationError): pass -class NotWritableError(MibOperationError): pass -class InconsistentNameError(MibOperationError): pass - -# Aligned with SNMPv2 Var-Bind exceptions -class NoSuchObjectError(MibOperationError): pass -class NoSuchInstanceError(NoSuchObjectError): pass -class EndOfMibViewError(MibOperationError): pass - -# Row management -class RowCreationWanted(MibOperationError): pass -class RowDestructionWanted(MibOperationError): pass diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/exval.py python-pysnmp4-4.2.2/pysnmp/v4/smi/exval.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/exval.py 2007-07-12 16:21:50.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/exval.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -from pyasn1.type import univ, tag - -noSuchObject = univ.Null('').subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0x00)) -noSuchInstance = univ.Null('').subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0x01)) -endOfMib = univ.Null('').subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0x02)) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/indices.py python-pysnmp4-4.2.2/pysnmp/v4/smi/indices.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/indices.py 2007-02-17 19:12:23.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/indices.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,170 +0,0 @@ -"""Ordered dictionaries classes used for indices""" -from types import DictType, TupleType -from string import join, split, atol -from bisect import bisect - -try: - from sys import version_info -except ImportError: - version_info = ( 0, 0 ) # a really early version - -if version_info < (2, 2): - class OrderedDict: - def __init__(self, **kwargs): - self.__dict = {} - self.__keys = [] - self.__dirty = 1 - if kwargs: - self.update(kwargs) - self.__dirty = 1 - def __len__(self): return len(self.__dict) - def __getitem__(self, key): return self.__dict[key] - def __setitem__(self, key, value): - if not self.__dict.has_key(key): - self.__keys.append(key) - self.__dict[key] = value - self.__dirty = 1 - def __repr__(self): - if self.__dirty: self.__order() - return repr(self.__dict) - def __str__(self): - if self.__dirty: self.__order() - return str(self.__dict) - def __delitem__(self, key): - if self.__dict.has_key(key): - self.__keys.remove(key) - del self.__dict[key] - self.__dirty = 1 - __delattr__ = __delitem__ - def clear(self): - self.__dict.clear() - self.__keys = [] - self.__dirty = 1 - def get(self, key, default=None): return self.__dict.get(key, default) - def has_key(self, key): return self.__dict.has_key(key) - def keys(self): - if self.__dirty: self.__order() - return list(self.__keys) - def values(self): - if self.__dirty: self.__order() - return map(lambda k, d=self.__dict: d[k], self.__keys) - def items(self): - if self.__dirty: self.__order() - return map(lambda k, d=self.__dict: (k, d[k]), self.__keys) - def update(self, d): - map(lambda (k, v), self=self: self.__setitem__(k, v), 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() - self.__keysLens = tuple(l) - self.__dirty = 0 - def nextKey(self, key): - keys = self.keys() - if self.has_key(key): - nextIdx = keys.index(key) + 1 - else: - nextIdx = bisect(keys, key) - if nextIdx < len(keys): - return keys[nextIdx] - else: - raise KeyError(key) - def getKeysLens(self): - if self.__dirty: - self.__order() - return self.__keysLens -else: - class OrderedDict(DictType): - def __init__(self, **kwargs): - self.__keys = [] - self.__dirty = 1 - super(OrderedDict, self).__init__() - if kwargs: - self.update(kwargs) - def __setitem__(self, key, value): - if not self.has_key(key): - self.__keys.append(key) - super(OrderedDict, self).__setitem__(key, value) - self.__dirty = 1 - def __repr__(self): - if self.__dirty: self.__order() - return super(OrderedDict, self).__repr__() - def __str__(self): - if self.__dirty: self.__order() - return super(OrderedDict, self).__str__() - def __delitem__(self, key): - if super(OrderedDict, self).has_key(key): - self.__keys.remove(key) - super(OrderedDict, self).__delitem__(key) - self.__dirty = 1 - __delattr__ = __delitem__ - def clear(self): - super(OrderedDict, self).clear() - self.__keys = [] - self.__dirty = 1 - def keys(self): - if self.__dirty: self.__order() - return list(self.__keys) - def values(self): - if self.__dirty: self.__order() - return map(lambda k, d=self: d[k], 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()) - 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() - self.__keysLens = tuple(l) - self.__dirty = 0 - def nextKey(self, key): - keys = self.keys() - if self.has_key(key): - nextIdx = keys.index(key) + 1 - else: - nextIdx = bisect(keys, key) - if nextIdx < len(keys): - return keys[nextIdx] - else: - raise KeyError(key) - - def getKeysLens(self): - if self.__dirty: - self.__order() - return self.__keysLens - -class OidOrderedDict(OrderedDict): - def __init__(self, **kwargs): - self.__keysCache = {} - apply(OrderedDict.__init__, [self], kwargs) - - def __setitem__(self, key, value): - if not self.__keysCache.has_key(key): - if type(key) == TupleType: - self.__keysCache[key] = key - else: - self.__keysCache[key] = map( - lambda x: atol(x), filter(None, split(key, '.')) - ) - OrderedDict.__setitem__(self, key, value) - - def __delitem__(self, key): - if self.__keysCache.has_key(key): - del self.__keysCache[key] - OrderedDict.__delitem__(self, key) - __delattr__ = __delitem__ - - def sortingFun(self, keys): - def f(o1, o2, self=self): - return cmp(self.__keysCache[o1], self.__keysCache[o2]) - keys.sort(f) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/__init__.py python-pysnmp4-4.2.2/pysnmp/v4/smi/__init__.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/__init__.py 2004-11-12 14:21:30.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/__init__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -"""SNMP SMI""" diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/instrum.py python-pysnmp4-4.2.2/pysnmp/v4/smi/instrum.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/instrum.py 2006-09-18 21:44:28.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/instrum.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -# MIB modules management -from types import InstanceType -from pysnmp.smi import error -from pysnmp import debug - -__all__ = [ 'MibInstrumController' ] - -class MibInstrumController: - fsmReadVar = { - # ( state, status ) -> newState - ('start', 'ok'): 'readTest', - ('readTest', 'ok'): 'readGet', - ('readGet', 'ok'): 'stop', - ('*', 'err'): 'stop' - } - fsmReadNextVar = { - # ( state, status ) -> newState - ('start', 'ok'): 'readTestNext', - ('readTestNext', 'ok'): 'readGetNext', - ('readGetNext', 'ok'): 'stop', - ('*', 'err'): 'stop' - } - fsmWriteVar = { - # ( state, status ) -> newState - ('start', 'ok'): 'writeTest', - ('writeTest', 'ok'): 'writeCommit', - ('writeCommit', 'ok'): 'writeCleanup', - ('writeCleanup', 'ok'): 'readTest', - # Do read after successful write - ('readTest', 'ok'): 'readGet', - ('readGet', 'ok'): 'stop', - # Error handling - ('writeTest', 'err'): 'writeCleanup', - ('writeCommit', 'err'): 'writeUndo', - ('writeUndo', 'ok'): 'readTest', - # Ignore read errors (removed columns) - ('readTest', 'err'): 'stop', - ('readGet', 'err'): 'stop', - ('*', 'err'): 'stop' - } - - def __init__(self, mibBuilder): - self.mibBuilder = mibBuilder - self.lastBuildId = -1 - - # MIB indexing - - def __indexMib(self): - # Build a tree from MIB objects found at currently loaded modules - if self.lastBuildId == self.mibBuilder.lastBuildId: - return - - ( MibScalarInstance, - MibScalar, - MibTableColumn, - MibTableRow, - MibTable, - MibTree ) = self.mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance', - 'MibScalar', - 'MibTableColumn', - 'MibTableRow', - 'MibTable', - 'MibTree' - ) - - mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') - - # - # Management Instrumentation gets organized as follows: - # - # MibTree - # | - # +----MibScalar - # | | - # | +-----MibScalarInstance - # | - # +----MibTable - # | - # +----MibTableRow - # | - # +-------MibTableColumn - # | - # +------MibScalarInstance(s) - # - # Mind you, only Managed Objects get indexed here, various MIB defs and - # constants can't be SNMP managed so we drop them. - # - scalars = {}; instances = {}; tables = {}; rows = {}; cols = {} - - # Sort by module name to give user a chance to slip-in - # custom MIB modules (that would sorted out first) - mibSymbols = self.mibBuilder.mibSymbols.items() - mibSymbols.sort(lambda x,y: cmp(y[0], x[0])) - - 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): - rows[symObj.name] = symObj - elif isinstance(symObj, MibTableColumn): - cols[symObj.name] = symObj - elif isinstance(symObj, MibScalarInstance): - instances[symObj.name] = symObj - elif isinstance(symObj, MibScalar): - scalars[symObj.name] = symObj - - # Attach Managed Objects Instances to Managed Objects - for inst in instances.values(): - if scalars.has_key(inst.typeName): - scalars[inst.typeName].registerSubtrees(inst) - elif cols.has_key(inst.typeName): - cols[inst.typeName].registerSubtrees(inst) - else: - raise error.SmiError( - 'Orphan MIB scalar instance %s at %s' % (inst, self) - ) - - # Attach Table Columns to Table Rows - for col in cols.values(): - rowName = col.name[:-1] # XXX - if rows.has_key(rowName): - rows[rowName].registerSubtrees(col) - else: - raise error.SmiError( - 'Orphan MIB table column %s at %s' % (col, self) - ) - - # Attach Table Rows to MIB tree - for row in rows.values(): - mibTree.registerSubtrees(row) - - # Attach Tables to MIB tree - for table in tables.values(): - mibTree.registerSubtrees(table) - - # Attach Scalars to MIB tree - for scalar in scalars.values(): - mibTree.registerSubtrees(scalar) - - debug.logger & debug.flagIns and debug.logger('__indexMib: rebuilt') - - self.lastBuildId = self.mibBuilder.lastBuildId - - # MIB instrumentation - - def flipFlopFsm(self, fsmTable, inputNameVals, (acFun, acCtx)): - self.__indexMib() - debug.logger & debug.flagIns and debug.logger('flipFlopFsm: inputNameVals %s' % (inputNameVals,)) - mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') - outputNameVals = [] - state, status = 'start', 'ok' - myErr = None - while 1: - fsmState = fsmTable.get((state, status)) - if fsmState is None: - fsmState = fsmTable.get(('*', status)) - if fsmState is None: - raise error.SmiError( - 'Unresolved FSM state %s, %s' % (state, status) - ) - debug.logger & debug.flagIns and debug.logger('flipFlopFsm: state %s status %s -> fsmState %s' % (state, status, fsmState)) - state = fsmState - status = 'ok' - if state == 'stop': - break - idx = 0 - for name, val in inputNameVals: - f = getattr(mibTree, state, None) - if f is None: - raise error.SmiError( - 'Unsupported state handler %s at %s' % (state, self) - ) - 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, val)) - if myErr is None: # Take the first exception - myErr = why - status = 'err' - break - else: - debug.logger & debug.flagIns and debug.logger('flipFlopFsm: fun %s suceeded for %s=%s' % (f, name, val)) - if rval is not None: - outputNameVals.append((rval[0], rval[1])) - idx = idx + 1 - if myErr: - 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)) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/ASN1.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/ASN1.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/ASN1.py 2005-06-14 10:19:29.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/ASN1.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -# ASN.1 objects used in SNMP -from pyasn1.type import univ -from pysnmp.proto import rfc1902 - -Integer = rfc1902.Integer32 -OctetString = rfc1902.OctetString - -# Instead of using base ASN,1 types we use SNMPv2 SMI ones to make -# SMI objects type-compatible with SNMP protocol values - -# Integer = univ.Integer -# OctetString = univ.OctetString -BitString = univ.BitString -Null = univ.Null -ObjectIdentifier = univ.ObjectIdentifier - -mibBuilder.exportSymbols( - 'ASN1', Integer=Integer, OctetString=OctetString, - BitString=BitString, Null=Null, ObjectIdentifier=ObjectIdentifier - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__PYSNMP-USM-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__PYSNMP-USM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__PYSNMP-USM-MIB.py 2006-06-23 21:18:37.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__PYSNMP-USM-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -( MibScalarInstance, ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance' - ) - -( pysnmpUsmDiscoverable, - pysnmpUsmDiscovery ) = mibBuilder.importSymbols( - 'PYSNMP-USM-MIB', - 'pysnmpUsmDiscoverable', - 'pysnmpUsmDiscovery' - ) - -__pysnmpUsmDiscoverable = MibScalarInstance(pysnmpUsmDiscoverable.name, (0,), pysnmpUsmDiscoverable.syntax) -__pysnmpUsmDiscovery = MibScalarInstance(pysnmpUsmDiscovery.name, (0,), pysnmpUsmDiscovery.syntax) - -mibBuilder.exportSymbols( - "__PYSNMP-USM-MIB", - pysnmpUsmDiscoverable = __pysnmpUsmDiscoverable, - pysnmpUsmDiscovery = __pysnmpUsmDiscovery - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py 2007-02-14 07:59:20.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -import time - -( MibScalarInstance, ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance' - ) - -( snmpEngineID, - snmpEngineBoots, - snmpEngineTime, - snmpEngineMaxMessageSize ) = mibBuilder.importSymbols( - 'SNMP-FRAMEWORK-MIB', - 'snmpEngineID', - 'snmpEngineBoots', - 'snmpEngineTime', - 'snmpEngineMaxMessageSize' - ) - -__snmpEngineID = MibScalarInstance(snmpEngineID.name, (0,), snmpEngineID.syntax) -__snmpEngineBoots = MibScalarInstance(snmpEngineBoots.name, (0,), snmpEngineBoots.syntax.clone(1)) -__snmpEngineTime = MibScalarInstance(snmpEngineTime.name, (0,), snmpEngineTime.syntax.clone(int(time.time()))) -__snmpEngineMaxMessageSize = MibScalarInstance(snmpEngineMaxMessageSize.name, (0,), snmpEngineMaxMessageSize.syntax.clone(4096)) - -mibBuilder.exportSymbols( - '__SNMP-FRAMEWORK-MIB', - snmpEngineID = __snmpEngineID, - snmpEngineBoots = __snmpEngineBoots, - snmpEngineTime = __snmpEngineTime, - snmpEngineMaxMessageSize = __snmpEngineMaxMessageSize - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-MPD-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-MPD-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-MPD-MIB.py 2006-06-23 21:18:37.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-MPD-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -( MibScalarInstance, ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance' - ) -( snmpUnknownSecurityModels, - snmpInvalidMsgs, - snmpUnknownPDUHandlers ) = mibBuilder.importSymbols( - 'SNMP-MPD-MIB', - 'snmpUnknownSecurityModels', - 'snmpInvalidMsgs', - 'snmpUnknownPDUHandlers', - ) - -__snmpUnknownSecurityModels = MibScalarInstance(snmpUnknownSecurityModels.name, (0,), snmpUnknownSecurityModels.syntax.clone(0)) -__snmpInvalidMsgs = MibScalarInstance(snmpInvalidMsgs.name, (0,), snmpInvalidMsgs.syntax.clone(0)) -__snmpUnknownPDUHandlers = MibScalarInstance(snmpUnknownPDUHandlers.name, (0,), snmpUnknownPDUHandlers.syntax.clone(0)) - -mibBuilder.exportSymbols( - '__SNMP-MPD-MIB', - snmpUnknownSecurityModels = __snmpUnknownSecurityModels, - snmpInvalidMsgs = __snmpInvalidMsgs, - snmpUnknownPDUHandlers = __snmpUnknownPDUHandlers - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-TARGET-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-TARGET-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-TARGET-MIB.py 2006-06-23 21:18:37.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-TARGET-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -( MibScalarInstance, ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance' - ) - -( snmpTargetSpinLock, - snmpUnavailableContexts, - snmpUnknownContexts ) = mibBuilder.importSymbols( - 'SNMP-TARGET-MIB', - 'snmpTargetSpinLock', - 'snmpUnavailableContexts', - 'snmpUnknownContexts' - ) - -__snmpTargetSpinLock = MibScalarInstance(snmpTargetSpinLock.name, (0,), snmpTargetSpinLock.syntax.clone(0)) -__snmpUnavailableContexts = MibScalarInstance(snmpUnavailableContexts.name, (0,), snmpUnavailableContexts.syntax.clone(0)) -__snmpUnknownContexts = MibScalarInstance(snmpUnknownContexts.name, (0,), snmpUnknownContexts.syntax.clone(0)) - -mibBuilder.exportSymbols( - '__SNMP-TARGET-MIB', - snmpTargetSpinLock = __snmpTargetSpinLock, - snmpUnavailableContexts = __snmpUnavailableContexts, - snmpUnknownContexts = __snmpUnknownContexts - ) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py 2006-06-23 21:18:37.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -( MibScalarInstance, ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance' - ) - -( usmStatsUnsupportedSecLevels, - usmStatsNotInTimeWindows, - usmStatsUnknownUserNames, - usmStatsUnknownEngineIDs, - usmStatsWrongDigests, - usmStatsDecryptionErrors, - usmUserSpinLock ) = mibBuilder.importSymbols( - 'SNMP-USER-BASED-SM-MIB', - 'usmStatsUnsupportedSecLevels', - 'usmStatsNotInTimeWindows', - 'usmStatsUnknownUserNames', - 'usmStatsUnknownEngineIDs', - 'usmStatsWrongDigests', - 'usmStatsDecryptionErrors', - 'usmUserSpinLock' - ) - -__usmStatsUnsupportedSecLevels = MibScalarInstance(usmStatsUnsupportedSecLevels.name, (0,), usmStatsUnsupportedSecLevels.syntax.clone(0)) -__usmStatsNotInTimeWindows = MibScalarInstance(usmStatsNotInTimeWindows.name, (0,), usmStatsNotInTimeWindows.syntax.clone(0)) -__usmStatsUnknownUserNames = MibScalarInstance(usmStatsUnknownUserNames.name, (0,), usmStatsUnknownUserNames.syntax.clone(0)) -__usmStatsUnknownEngineIDs = MibScalarInstance(usmStatsUnknownEngineIDs.name, (0,), usmStatsUnknownEngineIDs.syntax.clone(0)) -__usmStatsWrongDigests = MibScalarInstance(usmStatsWrongDigests.name, (0,), usmStatsWrongDigests.syntax.clone(0)) -__usmStatsDecryptionErrors = MibScalarInstance(usmStatsDecryptionErrors.name, (0,), usmStatsDecryptionErrors.syntax.clone(0)) -__usmUserSpinLock = MibScalarInstance(usmUserSpinLock.name, (0,), usmUserSpinLock.syntax.clone(0)) - -mibBuilder.exportSymbols( - '__SNMP-USER-BASED-SM-MIB', - usmStatsUnsupportedSecLevels = __usmStatsUnsupportedSecLevels, - usmStatsNotInTimeWindows = __usmStatsNotInTimeWindows, - usmStatsUnknownUserNames = __usmStatsUnknownUserNames, - usmStatsUnknownEngineIDs = __usmStatsUnknownEngineIDs, - usmStatsWrongDigests = __usmStatsWrongDigests, - usmStatsDecryptionErrors = __usmStatsDecryptionErrors, - usmUserSpinLock = __usmUserSpinLock - ) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMPv2-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMPv2-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMPv2-MIB.py 2007-01-30 15:37:15.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMPv2-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,177 +0,0 @@ -from sys import version -from time import time -from pysnmp import majorVersionId - -( MibScalarInstance, - TimeTicks) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance', - 'TimeTicks' - ) - -( sysDescr, - sysObjectID, - sysUpTime, - sysContact, - sysName, - sysLocation, - sysServices, - sysORLastChange, - snmpInPkts, - snmpOutPkts, - snmpInBadVersions, - snmpInBadCommunityNames, - snmpInBadCommunityUses, - snmpInASNParseErrs, - snmpInTooBigs, - snmpInNoSuchNames, - snmpInBadValues, - snmpInReadOnlys, - snmpInGenErrs, - snmpInTotalReqVars, - snmpInTotalSetVars, - snmpInGetRequests, - snmpInGetNexts, - snmpInSetRequests, - snmpInGetResponses, - snmpInTraps, - snmpOutTooBigs, - snmpOutNoSuchNames, - snmpOutBadValues, - snmpOutGenErrs, - snmpOutSetRequests, - snmpOutGetResponses, - snmpOutTraps, - snmpEnableAuthenTraps, - snmpSilentDrops, - snmpProxyDrops, - snmpTrapOID, - coldStart, - snmpSetSerialNo ) = mibBuilder.importSymbols( - 'SNMPv2-MIB', - 'sysDescr', - 'sysObjectID', - 'sysUpTime', - 'sysContact', - 'sysName', - 'sysLocation', - 'sysServices', - 'sysORLastChange', - 'snmpInPkts', - 'snmpOutPkts', - 'snmpInBadVersions', - 'snmpInBadCommunityNames', - 'snmpInBadCommunityUses', - 'snmpInASNParseErrs', - 'snmpInTooBigs', - 'snmpInNoSuchNames', - 'snmpInBadValues', - 'snmpInReadOnlys', - 'snmpInGenErrs', - 'snmpInTotalReqVars', - 'snmpInTotalSetVars', - 'snmpInGetRequests', - 'snmpInGetNexts', - 'snmpInSetRequests', - 'snmpInGetResponses', - 'snmpInTraps', - 'snmpOutTooBigs', - 'snmpOutNoSuchNames', - 'snmpOutBadValues', - 'snmpOutGenErrs', - 'snmpOutSetRequests', - 'snmpOutGetResponses', - 'snmpOutTraps', - 'snmpEnableAuthenTraps', - 'snmpSilentDrops', - 'snmpProxyDrops', - 'snmpTrapOID', - 'coldStart', - 'snmpSetSerialNo' - ) - -__sysDescr = MibScalarInstance(sysDescr.name, (0,), sysDescr.syntax.clone("PySNMP engine version %s, Python %s" % (majorVersionId, version))) -__sysObjectID = MibScalarInstance(sysObjectID.name, (0,), sysObjectID.syntax.clone((1,3,6,1,4,1,20408))) - -class SysUpTime(TimeTicks): - def smiRead(self, name, value, idx): - return self.clone(int(time()-self._value)*100) - -__sysUpTime = MibScalarInstance(sysUpTime.name, (0,), SysUpTime(time())) -__sysContact = MibScalarInstance(sysContact.name, (0,), sysContact.syntax.clone('')) -__sysName = MibScalarInstance(sysName.name, (0,), sysName.syntax.clone('')) -__sysLocation = MibScalarInstance(sysLocation.name, (0,), sysLocation.syntax.clone('')) -__sysServices = MibScalarInstance(sysServices.name, (0,), sysServices.syntax.clone(0)) -__sysORLastChange = MibScalarInstance(sysORLastChange.name, (0,), sysORLastChange.syntax.clone(0)) -__snmpInPkts = MibScalarInstance(snmpInPkts.name, (0,), snmpInPkts.syntax.clone(0)) -__snmpOutPkts = MibScalarInstance(snmpOutPkts.name, (0,), snmpOutPkts.syntax.clone(0)) -__snmpInBadVersions = MibScalarInstance(snmpInBadVersions.name, (0,), snmpInBadVersions.syntax.clone(0)) -__snmpInBadCommunityNames = MibScalarInstance(snmpInBadCommunityNames.name, (0,), snmpInBadCommunityNames.syntax.clone(0)) -__snmpInBadCommunityUses = MibScalarInstance(snmpInBadCommunityUses.name, (0,), snmpInBadCommunityUses.syntax.clone(0)) -__snmpInASNParseErrs = MibScalarInstance(snmpInASNParseErrs.name, (0,), snmpInASNParseErrs.syntax.clone(0)) -__snmpInTooBigs = MibScalarInstance(snmpInTooBigs.name, (0,), snmpInTooBigs.syntax.clone(0)) -__snmpInNoSuchNames = MibScalarInstance(snmpInNoSuchNames.name, (0,), snmpInNoSuchNames.syntax.clone(0)) -__snmpInBadValues = MibScalarInstance(snmpInBadValues.name, (0,), snmpInBadValues.syntax.clone(0)) -__snmpInReadOnlys = MibScalarInstance(snmpInReadOnlys.name, (0,), snmpInReadOnlys.syntax.clone(0)) -__snmpInGenErrs = MibScalarInstance(snmpInGenErrs.name, (0,), snmpInGenErrs.syntax.clone(0)) -__snmpInTotalReqVars = MibScalarInstance(snmpInTotalReqVars.name, (0,), snmpInTotalReqVars.syntax.clone(0)) -__snmpInTotalSetVars = MibScalarInstance(snmpInTotalSetVars.name, (0,), snmpInTotalSetVars.syntax.clone(0)) -__snmpInGetRequests = MibScalarInstance(snmpInGetRequests.name, (0,), snmpInGetRequests.syntax.clone(0)) -__snmpInGetNexts = MibScalarInstance(snmpInGetNexts.name, (0,), snmpInGetNexts.syntax.clone(0)) -__snmpInSetRequests = MibScalarInstance(snmpInSetRequests.name, (0,), snmpInSetRequests.syntax.clone(0)) -__snmpInGetResponses = MibScalarInstance(snmpInGetResponses.name, (0,), snmpInGetResponses.syntax.clone(0)) -__snmpInTraps = MibScalarInstance(snmpInTraps.name, (0,), snmpInTraps.syntax.clone(0)) -__snmpOutTooBigs = MibScalarInstance(snmpOutTooBigs.name, (0,), snmpOutTooBigs.syntax.clone(0)) -__snmpOutNoSuchNames = MibScalarInstance(snmpOutNoSuchNames.name, (0,), snmpOutNoSuchNames.syntax.clone(0)) -__snmpOutBadValues = MibScalarInstance(snmpOutBadValues.name, (0,), snmpOutBadValues.syntax.clone(0)) -__snmpOutGenErrs = MibScalarInstance(snmpOutGenErrs.name, (0,), snmpOutGenErrs.syntax.clone(0)) -__snmpOutSetRequests = MibScalarInstance(snmpOutSetRequests.name, (0,), snmpOutSetRequests.syntax.clone(0)) -__snmpOutGetResponses = MibScalarInstance(snmpOutGetResponses.name, (0,), snmpOutGetResponses.syntax.clone(0)) -__snmpOutTraps = MibScalarInstance(snmpOutTraps.name, (0,), snmpOutTraps.syntax.clone(0)) -__snmpEnableAuthenTraps = MibScalarInstance(snmpEnableAuthenTraps.name, (0,), snmpEnableAuthenTraps.syntax.clone(1)) -__snmpSilentDrops = MibScalarInstance(snmpSilentDrops.name, (0,), snmpSilentDrops.syntax.clone(0)) -__snmpProxyDrops = MibScalarInstance(snmpProxyDrops.name, (0,), snmpProxyDrops.syntax.clone(0)) -__snmpTrapOID = MibScalarInstance(snmpTrapOID.name, (0,), snmpTrapOID.syntax.clone(coldStart.name)) -__snmpSetSerialNo = MibScalarInstance(snmpSetSerialNo.name, (0,), snmpSetSerialNo.syntax.clone(0)) - -mibBuilder.exportSymbols( - "__SNMPv2-MIB", - sysDescr = __sysDescr, - sysObjectID = __sysObjectID, - sysUpTime = __sysUpTime, - sysContact = __sysContact, - sysName = __sysName, - sysLocation = __sysLocation, - sysServices = __sysServices, - sysORLastChange = __sysORLastChange, - 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, - snmpOutSetRequests = __snmpOutSetRequests, - snmpOutGetResponses = __snmpOutGetResponses, - snmpOutTraps = __snmpOutTraps, - snmpEnableAuthenTraps = __snmpEnableAuthenTraps, - snmpSilentDrops = __snmpSilentDrops, - snmpProxyDrops = __snmpProxyDrops, - snmpTrapOID = __snmpTrapOID, - snmpSetSerialNo = __snmpSetSerialNo - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py 2006-06-23 21:18:37.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -( MibScalarInstance, ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', - 'MibScalarInstance' - ) - -( vacmViewSpinLock, ) = mibBuilder.importSymbols( - 'SNMP-VIEW-BASED-ACM-MIB', - 'vacmViewSpinLock' - ) - -__vacmViewSpinLock = MibScalarInstance(vacmViewSpinLock.name, (0,), vacmViewSpinLock.syntax) - -mibBuilder.exportSymbols( - "__SNMP-VIEW-BASED-ACM-MIB", - vacmViewSpinLock = __vacmViewSpinLock - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/PYSNMP-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/PYSNMP-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/PYSNMP-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/PYSNMP-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 16:12:34 2006, -# Python version (2, 4, 3, 'final', 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") -( Bits, Integer32, ModuleIdentity, MibIdentifier, TimeTicks, enterprises, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "TimeTicks", "enterprises") - -# Objects - -pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408)).setRevisions(("2005-05-14 00:00",)) -pysnmpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 1)) -pysnmpExamples = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 2)) -pysnmpEnumerations = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3)) -pysnmpModuleIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1)) -pysnmpAgentOIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 2)) -pysnmpDomains = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 3)) -pysnmpNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4)) -pysnmpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 0)) -pysnmpNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 1)) -pysnmpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5)) -pysnmpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 1)) -pysnmpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 2)) -pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999)) - -# Augmentions - -# Exports - -# Module identity -mibBuilder.exportSymbols("PYSNMP-MIB", PYSNMP_MODULE_ID=pysnmp) - -# Objects -mibBuilder.exportSymbols("PYSNMP-MIB", pysnmp=pysnmp, pysnmpObjects=pysnmpObjects, pysnmpExamples=pysnmpExamples, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpDomains=pysnmpDomains, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpNotifications=pysnmpNotifications, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpConformance=pysnmpConformance, pysnmpCompliances=pysnmpCompliances, pysnmpGroups=pysnmpGroups, pysnmpExperimental=pysnmpExperimental) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/PYSNMP-USM-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/PYSNMP-USM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/PYSNMP-USM-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/PYSNMP-USM-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-USM-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 16:12:46 2006, -# Python version (2, 4, 3, 'final', 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") -( pysnmpModuleIDs, ) = mibBuilder.importSymbols("PYSNMP-MIB", "pysnmpModuleIDs") -( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") -( usmUserEntry, ) = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") -( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks") -( RowStatus, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus") - -# Objects - -pysnmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1)).setRevisions(("2005-05-14 00:00",)) -pysnmpUsmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1)) -pysnmpUsmCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1)) -pysnmpUsmDiscoverable = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 1), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,0,)).subtype(namedValues=namedval.NamedValues(("notDiscoverable", 0), ("discoverable", 1), )).clone(1)).setMaxAccess("readwrite") -pysnmpUsmDiscovery = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 2), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,0,)).subtype(namedValues=namedval.NamedValues(("doNotDiscover", 0), ("doDiscover", 1), )).clone(1)).setMaxAccess("readwrite") -pysnmpUsmSecretTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2)) -pysnmpUsmSecretEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1)).setIndexNames((1, "PYSNMP-USM-MIB", "pysnmpUsmSecretUserName")) -pysnmpUsmSecretUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -pysnmpUsmSecretAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 2), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(8, 65535))).setMaxAccess("noaccess") -pysnmpUsmSecretPrivKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 3), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(8, 65535))).setMaxAccess("noaccess") -pysnmpUsmSecretStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate") -pysnmpUsmUser = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3)) -pysnmpUsmKeyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1)) -pysnmpUsmKeyAuthLocalized = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") -pysnmpUsmKeyPrivLocalized = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") -pysnmpUsmKeyAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") -pysnmpUsmKeyPriv = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 4), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") -pysnmpUsmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2)) -pysnmpUsmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2, 1)) -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()) - -# Exports - -# Module identity -mibBuilder.exportSymbols("PYSNMP-USM-MIB", PYSNMP_MODULE_ID=pysnmpUsmMIB) - -# Objects -mibBuilder.exportSymbols("PYSNMP-USM-MIB", pysnmpUsmMIB=pysnmpUsmMIB, pysnmpUsmMIBObjects=pysnmpUsmMIBObjects, pysnmpUsmCfg=pysnmpUsmCfg, pysnmpUsmDiscoverable=pysnmpUsmDiscoverable, pysnmpUsmDiscovery=pysnmpUsmDiscovery, pysnmpUsmSecretTable=pysnmpUsmSecretTable, pysnmpUsmSecretEntry=pysnmpUsmSecretEntry, pysnmpUsmSecretUserName=pysnmpUsmSecretUserName, pysnmpUsmSecretAuthKey=pysnmpUsmSecretAuthKey, pysnmpUsmSecretPrivKey=pysnmpUsmSecretPrivKey, pysnmpUsmSecretStatus=pysnmpUsmSecretStatus, pysnmpUsmUser=pysnmpUsmUser, pysnmpUsmKeyEntry=pysnmpUsmKeyEntry, pysnmpUsmKeyAuthLocalized=pysnmpUsmKeyAuthLocalized, pysnmpUsmKeyPrivLocalized=pysnmpUsmKeyPrivLocalized, pysnmpUsmKeyAuth=pysnmpUsmKeyAuth, pysnmpUsmKeyPriv=pysnmpUsmKeyPriv, pysnmpUsmMIBConformance=pysnmpUsmMIBConformance, pysnmpUsmMIBCompliances=pysnmpUsmMIBCompliances, pysnmpUsmMIBGroups=pysnmpUsmMIBGroups) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/RFC1155-SMI.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/RFC1155-SMI.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/RFC1155-SMI.py 2007-02-07 13:01:32.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/RFC1155-SMI.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python RFC1155-SMI -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 19:01:40 2006, -# Python version (2, 4, 3, 'final', 0) - -# Imported just in case new ASN.1 types would be created -from pyasn1.type import constraint, namedval - -# Manually added -from pysnmp.proto.rfc1155 import NetworkAddress - -# Imports - -( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") -( Bits, Integer32, MibIdentifier, TimeTicks, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "MibIdentifier", "TimeTicks") - -# Types - -class Counter(Integer32): - subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,4294967295L) - pass - -class Gauge(Integer32): - subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,4294967295L) - pass - -class IpAddress(OctetString): - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(4,4) - fixedLength = 4 - pass - -class NetworkAddress(IpAddress): - pass - -class ObjectName(ObjectIdentifier): - pass - -class Opaque(OctetString): - pass - -class TimeTicks(Integer32): - subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,4294967295L) - pass - - -# Objects - -internet = MibIdentifier((1, 3, 6, 1)) -directory = MibIdentifier((1, 3, 6, 1, 1)) -mgmt = MibIdentifier((1, 3, 6, 1, 2)) -experimental = MibIdentifier((1, 3, 6, 1, 3)) -private = MibIdentifier((1, 3, 6, 1, 4)) -enterprises = MibIdentifier((1, 3, 6, 1, 4, 1)) - -# Augmentions - -# Exports - -# Types -mibBuilder.exportSymbols("RFC1155-SMI", Counter=Counter, Gauge=Gauge, IpAddress=IpAddress, NetworkAddress=NetworkAddress, ObjectName=ObjectName, Opaque=Opaque, TimeTicks=TimeTicks) - -# Objects -mibBuilder.exportSymbols("RFC1155-SMI", internet=internet, directory=directory, mgmt=mgmt, experimental=experimental, private=private, enterprises=enterprises) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/RFC1213-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/RFC1213-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/RFC1213-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/RFC1213-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,240 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python RFC1213-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:40:44 2006, -# Python version (2, 4, 3, 'final', 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") -( NetworkAddress, ) = mibBuilder.importSymbols("RFC1155-SMI", "NetworkAddress") -( Bits, Counter32, Gauge32, Integer32, Integer32, IpAddress, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, TimeTicks, mgmt, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Gauge32", "Integer32", "Integer32", "IpAddress", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "TimeTicks", "mgmt") - -# Types - -class DisplayString(OctetString): - pass - -class PhysAddress(OctetString): - pass - - -# Objects - -mib_2 = MibIdentifier((1, 3, 6, 1, 2, 1)).setLabel("mib-2") -system = MibIdentifier((1, 3, 6, 1, 2, 1, 1)) -sysDescr = MibScalar((1, 3, 6, 1, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readonly") -sysObjectID = MibScalar((1, 3, 6, 1, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") -sysUpTime = MibScalar((1, 3, 6, 1, 2, 1, 1, 3), TimeTicks()).setMaxAccess("readonly") -sysContact = MibScalar((1, 3, 6, 1, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") -sysName = MibScalar((1, 3, 6, 1, 2, 1, 1, 5), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") -sysLocation = MibScalar((1, 3, 6, 1, 2, 1, 1, 6), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") -sysServices = MibScalar((1, 3, 6, 1, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 127))).setMaxAccess("readonly") -interfaces = MibIdentifier((1, 3, 6, 1, 2, 1, 2)) -ifNumber = MibScalar((1, 3, 6, 1, 2, 1, 2, 1), Integer32()).setMaxAccess("readonly") -ifTable = MibTable((1, 3, 6, 1, 2, 1, 2, 2)) -ifEntry = MibTableRow((1, 3, 6, 1, 2, 1, 2, 2, 1)).setIndexNames((0, "RFC1213-MIB", "ifIndex")) -ifIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 1), Integer32()).setMaxAccess("readonly") -ifDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 2), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readonly") -ifType = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 3), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(22,32,24,5,30,23,4,28,12,26,31,7,1,17,16,8,14,20,21,19,15,6,13,11,25,9,18,3,27,2,10,29,)).subtype(namedValues=namedval.NamedValues(("other", 1), ("iso88026-man", 10), ("starLan", 11), ("proteon-10Mbit", 12), ("proteon-80Mbit", 13), ("hyperchannel", 14), ("fddi", 15), ("lapb", 16), ("sdlc", 17), ("ds1", 18), ("e1", 19), ("regular1822", 2), ("basicISDN", 20), ("primaryISDN", 21), ("propPointToPointSerial", 22), ("ppp", 23), ("softwareLoopback", 24), ("eon", 25), ("ethernet-3Mbit", 26), ("nsip", 27), ("slip", 28), ("ultra", 29), ("hdh1822", 3), ("ds3", 30), ("sip", 31), ("frame-relay", 32), ("ddn-x25", 4), ("rfc877-x25", 5), ("ethernet-csmacd", 6), ("iso88023-csmacd", 7), ("iso88024-tokenBus", 8), ("iso88025-tokenRing", 9), ))).setMaxAccess("readonly") -ifMtu = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 4), Integer32()).setMaxAccess("readonly") -ifSpeed = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 5), Gauge32()).setMaxAccess("readonly") -ifPhysAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 6), PhysAddress()).setMaxAccess("readonly") -ifAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 7), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,3,1,)).subtype(namedValues=namedval.NamedValues(("up", 1), ("down", 2), ("testing", 3), ))).setMaxAccess("readwrite") -ifOperStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 8), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,3,1,)).subtype(namedValues=namedval.NamedValues(("up", 1), ("down", 2), ("testing", 3), ))).setMaxAccess("readonly") -ifLastChange = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 9), TimeTicks()).setMaxAccess("readonly") -ifInOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 10), Counter32()).setMaxAccess("readonly") -ifInUcastPkts = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 11), Counter32()).setMaxAccess("readonly") -ifInNUcastPkts = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 12), Counter32()).setMaxAccess("readonly") -ifInDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 13), Counter32()).setMaxAccess("readonly") -ifInErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 14), Counter32()).setMaxAccess("readonly") -ifInUnknownProtos = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 15), Counter32()).setMaxAccess("readonly") -ifOutOctets = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 16), Counter32()).setMaxAccess("readonly") -ifOutUcastPkts = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 17), Counter32()).setMaxAccess("readonly") -ifOutNUcastPkts = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 18), Counter32()).setMaxAccess("readonly") -ifOutDiscards = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 19), Counter32()).setMaxAccess("readonly") -ifOutErrors = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 20), Counter32()).setMaxAccess("readonly") -ifOutQLen = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 21), Gauge32()).setMaxAccess("readonly") -ifSpecific = MibTableColumn((1, 3, 6, 1, 2, 1, 2, 2, 1, 22), ObjectIdentifier()).setMaxAccess("readonly") -at = MibIdentifier((1, 3, 6, 1, 2, 1, 3)) -atTable = MibTable((1, 3, 6, 1, 2, 1, 3, 1)) -atEntry = MibTableRow((1, 3, 6, 1, 2, 1, 3, 1, 1)).setIndexNames((0, "RFC1213-MIB", "atIfIndex"), (0, "RFC1213-MIB", "atNetAddressPlaceholder"), (0, "RFC1213-MIB", "atNetAddress")) -atIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 1), Integer32()).setMaxAccess("readwrite") -atPhysAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 2), PhysAddress()).setMaxAccess("readwrite") -atNetAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 3), IpAddress()).setMaxAccess("readwrite") -# Pre-index placeholder.Should be done by smidump but it is not for some reason. -# See RFC2576 2.1.1.10 for details -atNetAddressPlaceholder = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 9993), Integer(1)).setMaxAccess("not-accessible") -ip = MibIdentifier((1, 3, 6, 1, 2, 1, 4)) -ipForwarding = MibScalar((1, 3, 6, 1, 2, 1, 4, 1), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,2,)).subtype(namedValues=namedval.NamedValues(("forwarding", 1), ("not-forwarding", 2), ))).setMaxAccess("readwrite") -ipDefaultTTL = MibScalar((1, 3, 6, 1, 2, 1, 4, 2), Integer32()).setMaxAccess("readwrite") -ipInReceives = MibScalar((1, 3, 6, 1, 2, 1, 4, 3), Counter32()).setMaxAccess("readonly") -ipInHdrErrors = MibScalar((1, 3, 6, 1, 2, 1, 4, 4), Counter32()).setMaxAccess("readonly") -ipInAddrErrors = MibScalar((1, 3, 6, 1, 2, 1, 4, 5), Counter32()).setMaxAccess("readonly") -ipForwDatagrams = MibScalar((1, 3, 6, 1, 2, 1, 4, 6), Counter32()).setMaxAccess("readonly") -ipInUnknownProtos = MibScalar((1, 3, 6, 1, 2, 1, 4, 7), Counter32()).setMaxAccess("readonly") -ipInDiscards = MibScalar((1, 3, 6, 1, 2, 1, 4, 8), Counter32()).setMaxAccess("readonly") -ipInDelivers = MibScalar((1, 3, 6, 1, 2, 1, 4, 9), Counter32()).setMaxAccess("readonly") -ipOutRequests = MibScalar((1, 3, 6, 1, 2, 1, 4, 10), Counter32()).setMaxAccess("readonly") -ipOutDiscards = MibScalar((1, 3, 6, 1, 2, 1, 4, 11), Counter32()).setMaxAccess("readonly") -ipOutNoRoutes = MibScalar((1, 3, 6, 1, 2, 1, 4, 12), Counter32()).setMaxAccess("readonly") -ipReasmTimeout = MibScalar((1, 3, 6, 1, 2, 1, 4, 13), Integer32()).setMaxAccess("readonly") -ipReasmReqds = MibScalar((1, 3, 6, 1, 2, 1, 4, 14), Counter32()).setMaxAccess("readonly") -ipReasmOKs = MibScalar((1, 3, 6, 1, 2, 1, 4, 15), Counter32()).setMaxAccess("readonly") -ipReasmFails = MibScalar((1, 3, 6, 1, 2, 1, 4, 16), Counter32()).setMaxAccess("readonly") -ipFragOKs = MibScalar((1, 3, 6, 1, 2, 1, 4, 17), Counter32()).setMaxAccess("readonly") -ipFragFails = MibScalar((1, 3, 6, 1, 2, 1, 4, 18), Counter32()).setMaxAccess("readonly") -ipFragCreates = MibScalar((1, 3, 6, 1, 2, 1, 4, 19), Counter32()).setMaxAccess("readonly") -ipAddrTable = MibTable((1, 3, 6, 1, 2, 1, 4, 20)) -ipAddrEntry = MibTableRow((1, 3, 6, 1, 2, 1, 4, 20, 1)).setIndexNames((0, "RFC1213-MIB", "ipAdEntAddr")) -ipAdEntAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 1), IpAddress()).setMaxAccess("readonly") -ipAdEntIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 2), Integer32()).setMaxAccess("readonly") -ipAdEntNetMask = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 3), IpAddress()).setMaxAccess("readonly") -ipAdEntBcastAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 4), Integer32()).setMaxAccess("readonly") -ipAdEntReasmMaxSize = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 5), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") -ipRouteTable = MibTable((1, 3, 6, 1, 2, 1, 4, 21)) -ipRouteEntry = MibTableRow((1, 3, 6, 1, 2, 1, 4, 21, 1)).setIndexNames((0, "RFC1213-MIB", "ipRouteDest")) -ipRouteDest = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 1), IpAddress()).setMaxAccess("readwrite") -ipRouteIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 2), Integer32()).setMaxAccess("readwrite") -ipRouteMetric1 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 3), Integer32()).setMaxAccess("readwrite") -ipRouteMetric2 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 4), Integer32()).setMaxAccess("readwrite") -ipRouteMetric3 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 5), Integer32()).setMaxAccess("readwrite") -ipRouteMetric4 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 6), Integer32()).setMaxAccess("readwrite") -ipRouteNextHop = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 7), IpAddress()).setMaxAccess("readwrite") -ipRouteType = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 8), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(3,2,1,4,)).subtype(namedValues=namedval.NamedValues(("other", 1), ("invalid", 2), ("direct", 3), ("indirect", 4), ))).setMaxAccess("readwrite") -ipRouteProto = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 9), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(10,12,3,13,5,8,11,1,9,14,4,2,7,6,)).subtype(namedValues=namedval.NamedValues(("other", 1), ("es-is", 10), ("ciscoIgrp", 11), ("bbnSpfIgp", 12), ("ospf", 13), ("bgp", 14), ("local", 2), ("netmgmt", 3), ("icmp", 4), ("egp", 5), ("ggp", 6), ("hello", 7), ("rip", 8), ("is-is", 9), ))).setMaxAccess("readonly") -ipRouteAge = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 10), Integer32()).setMaxAccess("readwrite") -ipRouteMask = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 11), IpAddress()).setMaxAccess("readwrite") -ipRouteMetric5 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 12), Integer32()).setMaxAccess("readwrite") -ipRouteInfo = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 13), ObjectIdentifier()).setMaxAccess("readonly") -ipNetToMediaTable = MibTable((1, 3, 6, 1, 2, 1, 4, 22)) -ipNetToMediaEntry = MibTableRow((1, 3, 6, 1, 2, 1, 4, 22, 1)).setIndexNames((0, "RFC1213-MIB", "ipNetToMediaIfIndex"), (0, "RFC1213-MIB", "ipNetToMediaNetAddress")) -ipNetToMediaIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 1), Integer32()).setMaxAccess("readwrite") -ipNetToMediaPhysAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 2), PhysAddress()).setMaxAccess("readwrite") -ipNetToMediaNetAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 3), IpAddress()).setMaxAccess("readwrite") -ipNetToMediaType = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 4), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(3,2,1,4,)).subtype(namedValues=namedval.NamedValues(("other", 1), ("invalid", 2), ("dynamic", 3), ("static", 4), ))).setMaxAccess("readwrite") -ipRoutingDiscards = MibScalar((1, 3, 6, 1, 2, 1, 4, 23), Counter32()).setMaxAccess("readonly") -icmp = MibIdentifier((1, 3, 6, 1, 2, 1, 5)) -icmpInMsgs = MibScalar((1, 3, 6, 1, 2, 1, 5, 1), Counter32()).setMaxAccess("readonly") -icmpInErrors = MibScalar((1, 3, 6, 1, 2, 1, 5, 2), Counter32()).setMaxAccess("readonly") -icmpInDestUnreachs = MibScalar((1, 3, 6, 1, 2, 1, 5, 3), Counter32()).setMaxAccess("readonly") -icmpInTimeExcds = MibScalar((1, 3, 6, 1, 2, 1, 5, 4), Counter32()).setMaxAccess("readonly") -icmpInParmProbs = MibScalar((1, 3, 6, 1, 2, 1, 5, 5), Counter32()).setMaxAccess("readonly") -icmpInSrcQuenchs = MibScalar((1, 3, 6, 1, 2, 1, 5, 6), Counter32()).setMaxAccess("readonly") -icmpInRedirects = MibScalar((1, 3, 6, 1, 2, 1, 5, 7), Counter32()).setMaxAccess("readonly") -icmpInEchos = MibScalar((1, 3, 6, 1, 2, 1, 5, 8), Counter32()).setMaxAccess("readonly") -icmpInEchoReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 9), Counter32()).setMaxAccess("readonly") -icmpInTimestamps = MibScalar((1, 3, 6, 1, 2, 1, 5, 10), Counter32()).setMaxAccess("readonly") -icmpInTimestampReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 11), Counter32()).setMaxAccess("readonly") -icmpInAddrMasks = MibScalar((1, 3, 6, 1, 2, 1, 5, 12), Counter32()).setMaxAccess("readonly") -icmpInAddrMaskReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 13), Counter32()).setMaxAccess("readonly") -icmpOutMsgs = MibScalar((1, 3, 6, 1, 2, 1, 5, 14), Counter32()).setMaxAccess("readonly") -icmpOutErrors = MibScalar((1, 3, 6, 1, 2, 1, 5, 15), Counter32()).setMaxAccess("readonly") -icmpOutDestUnreachs = MibScalar((1, 3, 6, 1, 2, 1, 5, 16), Counter32()).setMaxAccess("readonly") -icmpOutTimeExcds = MibScalar((1, 3, 6, 1, 2, 1, 5, 17), Counter32()).setMaxAccess("readonly") -icmpOutParmProbs = MibScalar((1, 3, 6, 1, 2, 1, 5, 18), Counter32()).setMaxAccess("readonly") -icmpOutSrcQuenchs = MibScalar((1, 3, 6, 1, 2, 1, 5, 19), Counter32()).setMaxAccess("readonly") -icmpOutRedirects = MibScalar((1, 3, 6, 1, 2, 1, 5, 20), Counter32()).setMaxAccess("readonly") -icmpOutEchos = MibScalar((1, 3, 6, 1, 2, 1, 5, 21), Counter32()).setMaxAccess("readonly") -icmpOutEchoReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 22), Counter32()).setMaxAccess("readonly") -icmpOutTimestamps = MibScalar((1, 3, 6, 1, 2, 1, 5, 23), Counter32()).setMaxAccess("readonly") -icmpOutTimestampReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 24), Counter32()).setMaxAccess("readonly") -icmpOutAddrMasks = MibScalar((1, 3, 6, 1, 2, 1, 5, 25), Counter32()).setMaxAccess("readonly") -icmpOutAddrMaskReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 26), Counter32()).setMaxAccess("readonly") -tcp = MibIdentifier((1, 3, 6, 1, 2, 1, 6)) -tcpRtoAlgorithm = MibScalar((1, 3, 6, 1, 2, 1, 6, 1), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,1,3,4,)).subtype(namedValues=namedval.NamedValues(("other", 1), ("constant", 2), ("rsre", 3), ("vanj", 4), ))).setMaxAccess("readonly") -tcpRtoMin = MibScalar((1, 3, 6, 1, 2, 1, 6, 2), Integer32()).setMaxAccess("readonly") -tcpRtoMax = MibScalar((1, 3, 6, 1, 2, 1, 6, 3), Integer32()).setMaxAccess("readonly") -tcpMaxConn = MibScalar((1, 3, 6, 1, 2, 1, 6, 4), Integer32()).setMaxAccess("readonly") -tcpActiveOpens = MibScalar((1, 3, 6, 1, 2, 1, 6, 5), Counter32()).setMaxAccess("readonly") -tcpPassiveOpens = MibScalar((1, 3, 6, 1, 2, 1, 6, 6), Counter32()).setMaxAccess("readonly") -tcpAttemptFails = MibScalar((1, 3, 6, 1, 2, 1, 6, 7), Counter32()).setMaxAccess("readonly") -tcpEstabResets = MibScalar((1, 3, 6, 1, 2, 1, 6, 8), Counter32()).setMaxAccess("readonly") -tcpCurrEstab = MibScalar((1, 3, 6, 1, 2, 1, 6, 9), Gauge32()).setMaxAccess("readonly") -tcpInSegs = MibScalar((1, 3, 6, 1, 2, 1, 6, 10), Counter32()).setMaxAccess("readonly") -tcpOutSegs = MibScalar((1, 3, 6, 1, 2, 1, 6, 11), Counter32()).setMaxAccess("readonly") -tcpRetransSegs = MibScalar((1, 3, 6, 1, 2, 1, 6, 12), Counter32()).setMaxAccess("readonly") -tcpConnTable = MibTable((1, 3, 6, 1, 2, 1, 6, 13)) -tcpConnEntry = MibTableRow((1, 3, 6, 1, 2, 1, 6, 13, 1)).setIndexNames((0, "RFC1213-MIB", "tcpConnLocalAddress"), (0, "RFC1213-MIB", "tcpConnLocalPort"), (0, "RFC1213-MIB", "tcpConnRemAddress"), (0, "RFC1213-MIB", "tcpConnRemPort")) -tcpConnState = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 1), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(4,5,7,11,9,8,12,6,1,10,2,3,)).subtype(namedValues=namedval.NamedValues(("closed", 1), ("closing", 10), ("timeWait", 11), ("deleteTCB", 12), ("listen", 2), ("synSent", 3), ("synReceived", 4), ("established", 5), ("finWait1", 6), ("finWait2", 7), ("closeWait", 8), ("lastAck", 9), ))).setMaxAccess("readwrite") -tcpConnLocalAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 2), IpAddress()).setMaxAccess("readonly") -tcpConnLocalPort = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 3), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") -tcpConnRemAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 4), IpAddress()).setMaxAccess("readonly") -tcpConnRemPort = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 5), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") -tcpInErrs = MibScalar((1, 3, 6, 1, 2, 1, 6, 14), Counter32()).setMaxAccess("readonly") -tcpOutRsts = MibScalar((1, 3, 6, 1, 2, 1, 6, 15), Counter32()).setMaxAccess("readonly") -udp = MibIdentifier((1, 3, 6, 1, 2, 1, 7)) -udpInDatagrams = MibScalar((1, 3, 6, 1, 2, 1, 7, 1), Counter32()).setMaxAccess("readonly") -udpNoPorts = MibScalar((1, 3, 6, 1, 2, 1, 7, 2), Counter32()).setMaxAccess("readonly") -udpInErrors = MibScalar((1, 3, 6, 1, 2, 1, 7, 3), Counter32()).setMaxAccess("readonly") -udpOutDatagrams = MibScalar((1, 3, 6, 1, 2, 1, 7, 4), Counter32()).setMaxAccess("readonly") -udpTable = MibTable((1, 3, 6, 1, 2, 1, 7, 5)) -udpEntry = MibTableRow((1, 3, 6, 1, 2, 1, 7, 5, 1)).setIndexNames((0, "RFC1213-MIB", "udpLocalAddress"), (0, "RFC1213-MIB", "udpLocalPort")) -udpLocalAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 7, 5, 1, 1), IpAddress()).setMaxAccess("readonly") -udpLocalPort = MibTableColumn((1, 3, 6, 1, 2, 1, 7, 5, 1, 2), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") -egp = MibIdentifier((1, 3, 6, 1, 2, 1, 8)) -egpInMsgs = MibScalar((1, 3, 6, 1, 2, 1, 8, 1), Counter32()).setMaxAccess("readonly") -egpInErrors = MibScalar((1, 3, 6, 1, 2, 1, 8, 2), Counter32()).setMaxAccess("readonly") -egpOutMsgs = MibScalar((1, 3, 6, 1, 2, 1, 8, 3), Counter32()).setMaxAccess("readonly") -egpOutErrors = MibScalar((1, 3, 6, 1, 2, 1, 8, 4), Counter32()).setMaxAccess("readonly") -egpNeighTable = MibTable((1, 3, 6, 1, 2, 1, 8, 5)) -egpNeighEntry = MibTableRow((1, 3, 6, 1, 2, 1, 8, 5, 1)).setIndexNames((0, "RFC1213-MIB", "egpNeighAddr")) -egpNeighState = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 1), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(3,4,1,5,2,)).subtype(namedValues=namedval.NamedValues(("idle", 1), ("acquisition", 2), ("down", 3), ("up", 4), ("cease", 5), ))).setMaxAccess("readonly") -egpNeighAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 2), IpAddress()).setMaxAccess("readonly") -egpNeighAs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 3), Integer32()).setMaxAccess("readonly") -egpNeighInMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 4), Counter32()).setMaxAccess("readonly") -egpNeighInErrs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 5), Counter32()).setMaxAccess("readonly") -egpNeighOutMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 6), Counter32()).setMaxAccess("readonly") -egpNeighOutErrs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 7), Counter32()).setMaxAccess("readonly") -egpNeighInErrMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 8), Counter32()).setMaxAccess("readonly") -egpNeighOutErrMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 9), Counter32()).setMaxAccess("readonly") -egpNeighStateUps = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 10), Counter32()).setMaxAccess("readonly") -egpNeighStateDowns = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 11), Counter32()).setMaxAccess("readonly") -egpNeighIntervalHello = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 12), Integer32()).setMaxAccess("readonly") -egpNeighIntervalPoll = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 13), Integer32()).setMaxAccess("readonly") -egpNeighMode = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 14), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,2,)).subtype(namedValues=namedval.NamedValues(("active", 1), ("passive", 2), ))).setMaxAccess("readonly") -egpNeighEventTrigger = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 15), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,2,)).subtype(namedValues=namedval.NamedValues(("start", 1), ("stop", 2), ))).setMaxAccess("readwrite") -egpAs = MibScalar((1, 3, 6, 1, 2, 1, 8, 6), Integer32()).setMaxAccess("readonly") -transmission = MibIdentifier((1, 3, 6, 1, 2, 1, 10)) -snmp = MibIdentifier((1, 3, 6, 1, 2, 1, 11)) -snmpInPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 1), Counter32()).setMaxAccess("readonly") -snmpOutPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 2), Counter32()).setMaxAccess("readonly") -snmpInBadVersions = MibScalar((1, 3, 6, 1, 2, 1, 11, 3), Counter32()).setMaxAccess("readonly") -snmpInBadCommunityNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 4), Counter32()).setMaxAccess("readonly") -snmpInBadCommunityUses = MibScalar((1, 3, 6, 1, 2, 1, 11, 5), Counter32()).setMaxAccess("readonly") -snmpInASNParseErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 6), Counter32()).setMaxAccess("readonly") -snmpInTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 8), Counter32()).setMaxAccess("readonly") -snmpInNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 9), Counter32()).setMaxAccess("readonly") -snmpInBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 10), Counter32()).setMaxAccess("readonly") -snmpInReadOnlys = MibScalar((1, 3, 6, 1, 2, 1, 11, 11), Counter32()).setMaxAccess("readonly") -snmpInGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 12), Counter32()).setMaxAccess("readonly") -snmpInTotalReqVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 13), Counter32()).setMaxAccess("readonly") -snmpInTotalSetVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 14), Counter32()).setMaxAccess("readonly") -snmpInGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 15), Counter32()).setMaxAccess("readonly") -snmpInGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 16), Counter32()).setMaxAccess("readonly") -snmpInSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 17), Counter32()).setMaxAccess("readonly") -snmpInGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 18), Counter32()).setMaxAccess("readonly") -snmpInTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 19), Counter32()).setMaxAccess("readonly") -snmpOutTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 20), Counter32()).setMaxAccess("readonly") -snmpOutNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 21), Counter32()).setMaxAccess("readonly") -snmpOutBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 22), Counter32()).setMaxAccess("readonly") -snmpOutGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 24), Counter32()).setMaxAccess("readonly") -snmpOutGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 25), Counter32()).setMaxAccess("readonly") -snmpOutGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 26), Counter32()).setMaxAccess("readonly") -snmpOutSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 27), Counter32()).setMaxAccess("readonly") -snmpOutGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 28), Counter32()).setMaxAccess("readonly") -snmpOutTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 29), Counter32()).setMaxAccess("readonly") -snmpEnableAuthenTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 30), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,1,)).subtype(namedValues=namedval.NamedValues(("enabled", 1), ("disabled", 2), ))).setMaxAccess("readwrite") - -# Augmentions - -# Exports - -# Types -mibBuilder.exportSymbols("RFC1213-MIB", DisplayString=DisplayString, PhysAddress=PhysAddress) - -# Objects -mibBuilder.exportSymbols("RFC1213-MIB", mib_2=mib_2, system=system, sysDescr=sysDescr, sysObjectID=sysObjectID, sysUpTime=sysUpTime, sysContact=sysContact, sysName=sysName, sysLocation=sysLocation, sysServices=sysServices, interfaces=interfaces, ifNumber=ifNumber, ifTable=ifTable, ifEntry=ifEntry, ifIndex=ifIndex, ifDescr=ifDescr, ifType=ifType, ifMtu=ifMtu, ifSpeed=ifSpeed, ifPhysAddress=ifPhysAddress, ifAdminStatus=ifAdminStatus, ifOperStatus=ifOperStatus, ifLastChange=ifLastChange, ifInOctets=ifInOctets, ifInUcastPkts=ifInUcastPkts, ifInNUcastPkts=ifInNUcastPkts, ifInDiscards=ifInDiscards, ifInErrors=ifInErrors, ifInUnknownProtos=ifInUnknownProtos, ifOutOctets=ifOutOctets, ifOutUcastPkts=ifOutUcastPkts, ifOutNUcastPkts=ifOutNUcastPkts, ifOutDiscards=ifOutDiscards, ifOutErrors=ifOutErrors, ifOutQLen=ifOutQLen, ifSpecific=ifSpecific, at=at, atTable=atTable, atEntry=atEntry, atIfIndex=atIfIndex, atPhysAddress=atPhysAddress, atNetAddress=atNetAddress, atNetAddressPlaceholder=atNetAddressPlaceholder, ip=ip, ipForwarding=ipForwarding, ipDefaultTTL=ipDefaultTTL, ipInReceives=ipInReceives, ipInHdrErrors=ipInHdrErrors, ipInAddrErrors=ipInAddrErrors, ipForwDatagrams=ipForwDatagrams, ipInUnknownProtos=ipInUnknownProtos, ipInDiscards=ipInDiscards, ipInDelivers=ipInDelivers, ipOutRequests=ipOutRequests, ipOutDiscards=ipOutDiscards, ipOutNoRoutes=ipOutNoRoutes, ipReasmTimeout=ipReasmTimeout, ipReasmReqds=ipReasmReqds, ipReasmOKs=ipReasmOKs, ipReasmFails=ipReasmFails, ipFragOKs=ipFragOKs, ipFragFails=ipFragFails, ipFragCreates=ipFragCreates, ipAddrTable=ipAddrTable, ipAddrEntry=ipAddrEntry, ipAdEntAddr=ipAdEntAddr, ipAdEntIfIndex=ipAdEntIfIndex, ipAdEntNetMask=ipAdEntNetMask, ipAdEntBcastAddr=ipAdEntBcastAddr, ipAdEntReasmMaxSize=ipAdEntReasmMaxSize, ipRouteTable=ipRouteTable, ipRouteEntry=ipRouteEntry, ipRouteDest=ipRouteDest, ipRouteIfIndex=ipRouteIfIndex, ipRouteMetric1=ipRouteMetric1, ipRouteMetric2=ipRouteMetric2, ipRouteMetric3=ipRouteMetric3, ipRouteMetric4=ipRouteMetric4, ipRouteNextHop=ipRouteNextHop, ipRouteType=ipRouteType, ipRouteProto=ipRouteProto, ipRouteAge=ipRouteAge, ipRouteMask=ipRouteMask, ipRouteMetric5=ipRouteMetric5, ipRouteInfo=ipRouteInfo, ipNetToMediaTable=ipNetToMediaTable, ipNetToMediaEntry=ipNetToMediaEntry, ipNetToMediaIfIndex=ipNetToMediaIfIndex, ipNetToMediaPhysAddress=ipNetToMediaPhysAddress, ipNetToMediaNetAddress=ipNetToMediaNetAddress, ipNetToMediaType=ipNetToMediaType, ipRoutingDiscards=ipRoutingDiscards, icmp=icmp, icmpInMsgs=icmpInMsgs, icmpInErrors=icmpInErrors, icmpInDestUnreachs=icmpInDestUnreachs, icmpInTimeExcds=icmpInTimeExcds, icmpInParmProbs=icmpInParmProbs, icmpInSrcQuenchs=icmpInSrcQuenchs, icmpInRedirects=icmpInRedirects, icmpInEchos=icmpInEchos, icmpInEchoReps=icmpInEchoReps, icmpInTimestamps=icmpInTimestamps, icmpInTimestampReps=icmpInTimestampReps, icmpInAddrMasks=icmpInAddrMasks, icmpInAddrMaskReps=icmpInAddrMaskReps, icmpOutMsgs=icmpOutMsgs, icmpOutErrors=icmpOutErrors, icmpOutDestUnreachs=icmpOutDestUnreachs, icmpOutTimeExcds=icmpOutTimeExcds, icmpOutParmProbs=icmpOutParmProbs, icmpOutSrcQuenchs=icmpOutSrcQuenchs, icmpOutRedirects=icmpOutRedirects, icmpOutEchos=icmpOutEchos, icmpOutEchoReps=icmpOutEchoReps, icmpOutTimestamps=icmpOutTimestamps, icmpOutTimestampReps=icmpOutTimestampReps, icmpOutAddrMasks=icmpOutAddrMasks, icmpOutAddrMaskReps=icmpOutAddrMaskReps, tcp=tcp, tcpRtoAlgorithm=tcpRtoAlgorithm, tcpRtoMin=tcpRtoMin, tcpRtoMax=tcpRtoMax, tcpMaxConn=tcpMaxConn, tcpActiveOpens=tcpActiveOpens, tcpPassiveOpens=tcpPassiveOpens, tcpAttemptFails=tcpAttemptFails, tcpEstabResets=tcpEstabResets) -mibBuilder.exportSymbols("RFC1213-MIB", tcpCurrEstab=tcpCurrEstab, tcpInSegs=tcpInSegs, tcpOutSegs=tcpOutSegs, tcpRetransSegs=tcpRetransSegs, tcpConnTable=tcpConnTable, tcpConnEntry=tcpConnEntry, tcpConnState=tcpConnState, tcpConnLocalAddress=tcpConnLocalAddress, tcpConnLocalPort=tcpConnLocalPort, tcpConnRemAddress=tcpConnRemAddress, tcpConnRemPort=tcpConnRemPort, tcpInErrs=tcpInErrs, tcpOutRsts=tcpOutRsts, udp=udp, udpInDatagrams=udpInDatagrams, udpNoPorts=udpNoPorts, udpInErrors=udpInErrors, udpOutDatagrams=udpOutDatagrams, udpTable=udpTable, udpEntry=udpEntry, udpLocalAddress=udpLocalAddress, udpLocalPort=udpLocalPort, egp=egp, egpInMsgs=egpInMsgs, egpInErrors=egpInErrors, egpOutMsgs=egpOutMsgs, egpOutErrors=egpOutErrors, egpNeighTable=egpNeighTable, egpNeighEntry=egpNeighEntry, egpNeighState=egpNeighState, egpNeighAddr=egpNeighAddr, egpNeighAs=egpNeighAs, egpNeighInMsgs=egpNeighInMsgs, egpNeighInErrs=egpNeighInErrs, egpNeighOutMsgs=egpNeighOutMsgs, egpNeighOutErrs=egpNeighOutErrs, egpNeighInErrMsgs=egpNeighInErrMsgs, egpNeighOutErrMsgs=egpNeighOutErrMsgs, egpNeighStateUps=egpNeighStateUps, egpNeighStateDowns=egpNeighStateDowns, egpNeighIntervalHello=egpNeighIntervalHello, egpNeighIntervalPoll=egpNeighIntervalPoll, egpNeighMode=egpNeighMode, egpNeighEventTrigger=egpNeighEventTrigger, egpAs=egpAs, transmission=transmission, 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) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-COMMUNITY-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-COMMUNITY-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-COMMUNITY-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-COMMUNITY-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-COMMUNITY-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:22:34 2006, -# Python version (2, 4, 3, 'final', 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, snmpTargetAddrEntry, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetAddrEntry") -( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") -( Bits, Integer32, Integer32, IpAddress, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "Integer32", "IpAddress", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") -( RowStatus, StorageType, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType") - -# Objects - -snmpCommunityMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 18)).setRevisions(("2000-03-06 00:00","1999-05-13 00:00",)) -snmpCommunityMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 1)) -snmpCommunityTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 1)) -snmpCommunityEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 1, 1)).setIndexNames((1, "SNMP-COMMUNITY-MIB", "snmpCommunityIndex")) -snmpCommunityIndex = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -snmpCommunityName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 2), OctetString()).setMaxAccess("readcreate") -snmpCommunitySecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") -snmpCommunityContextEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 4), SnmpEngineID()).setMaxAccess("readcreate") -snmpCommunityContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") -snmpCommunityTransportTag = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 6), SnmpTagValue().clone('')).setMaxAccess("readcreate") -snmpCommunityStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 7), StorageType()).setMaxAccess("readcreate") -snmpCommunityStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8), RowStatus()).setMaxAccess("readcreate") -snmpTargetAddrExtTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 2)) -snmpTargetAddrExtEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 2, 1)) -snmpTargetAddrTMask = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 2, 1, 1), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255)).clone('')).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,2147483647L),)).clone(484)).setMaxAccess("readcreate") -snmpTrapAddress = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 3), IpAddress()).setMaxAccess("notifyonly") -snmpTrapCommunity = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 4), OctetString()).setMaxAccess("notifyonly") -snmpCommunityMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2)) -snmpCommunityMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 1)) -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()) - -# Groups - -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"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", PYSNMP_MODULE_ID=snmpCommunityMIB) - -# Objects -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) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-FRAMEWORK-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-FRAMEWORK-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-FRAMEWORK-MIB.py 2007-02-19 08:24:10.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-FRAMEWORK-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-FRAMEWORK-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:48:05 2006, -# Python version (2, 4, 3, 'final', 0) - -try: - import socket - 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 - -# Imports - -( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") -( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") -( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") -( TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention") - -# Types - -class SnmpAdminString(TextualConvention, OctetString): - displayHint = "255t" - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(0,255) - -class SnmpEngineID(OctetString, TextualConvention): - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(5,32) - try: - # Attempt to base engine ID on local IP address - defaultValue = '\x80\x00\x4f\xb8' + '\x05' + string.join( - map(lambda x: chr(int(x)), - string.split(socket.gethostbyname(socket.gethostname()),'.')), - '' - ) + chr(os.getpid() >> 8) + chr(os.getpid() & 0xff) - except: - # ...otherwise, use rudimentary text ID - defaultValue = '\x80\x00\x4f\xb8' + '\x05' - t = int(time.time()) - while t: - defaultValue = defaultValue + chr(t & 0xff) - t = t >> 8 - -class SnmpEngineTime(Integer32): - def clone(self, value=None, tagSet=None, subtypeSpec=None): - if value is None and self._value is not None: - value = int(time.time())-self._value - return Integer32.clone(self, value, tagSet, subtypeSpec) - -class SnmpMessageProcessingModel(Integer32): - subtypeSpec = Integer32.subtypeSpec+constraint.ValueRangeConstraint(0,2147483647L) - -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) - -# Objects - -snmpFrameworkMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 10)).setRevisions(("2002-10-14 00:00","1999-01-19 00:00","1997-11-20 00:00",)) -snmpFrameworkAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1)) -snmpAuthProtocols = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 1)) -snmpPrivProtocols = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 2)) -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") -snmpEngineBoots = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("readonly") -snmpEngineTime = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 3), SnmpEngineTime().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647L))).setMaxAccess("readonly").setUnits("seconds") -snmpEngineMaxMessageSize = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 4), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(484, 2147483647L))).setMaxAccess("readonly") -snmpFrameworkMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3)) -snmpFrameworkMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 1)) -snmpFrameworkMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 2)) - -# Augmentions - -# Groups - -snmpEngineGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 10, 3, 2, 1)).setObjects(("SNMP-FRAMEWORK-MIB", "snmpEngineID"), ("SNMP-FRAMEWORK-MIB", "snmpEngineBoots"), ("SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize"), ("SNMP-FRAMEWORK-MIB", "snmpEngineTime"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", PYSNMP_MODULE_ID=snmpFrameworkMIB) - -# Types -mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", SnmpAdminString=SnmpAdminString, SnmpEngineID=SnmpEngineID, SnmpMessageProcessingModel=SnmpMessageProcessingModel, SnmpSecurityLevel=SnmpSecurityLevel, SnmpSecurityModel=SnmpSecurityModel) - -# Objects -mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpFrameworkMIB=snmpFrameworkMIB, snmpFrameworkAdmin=snmpFrameworkAdmin, snmpAuthProtocols=snmpAuthProtocols, snmpPrivProtocols=snmpPrivProtocols, snmpFrameworkMIBObjects=snmpFrameworkMIBObjects, snmpEngine=snmpEngine, snmpEngineID=snmpEngineID, snmpEngineBoots=snmpEngineBoots, snmpEngineTime=snmpEngineTime, snmpEngineMaxMessageSize=snmpEngineMaxMessageSize, snmpFrameworkMIBConformance=snmpFrameworkMIBConformance, snmpFrameworkMIBCompliances=snmpFrameworkMIBCompliances, snmpFrameworkMIBGroups=snmpFrameworkMIBGroups) - -# Groups -mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpEngineGroup=snmpEngineGroup) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-MPD-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-MPD-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-MPD-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-MPD-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-MPD-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:54:13 2006, -# Python version (2, 4, 3, 'final', 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") -( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") -( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") - -# Objects - -snmpMPDMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 11)).setRevisions(("2002-10-14 00:00","1999-05-04 16:36","1997-09-30 00:00",)) -snmpMPDAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 1)) -snmpMPDMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2)) -snmpMPDStats = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2, 1)) -snmpUnknownSecurityModels = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 1), Counter32()).setMaxAccess("readonly") -snmpInvalidMsgs = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 2), Counter32()).setMaxAccess("readonly") -snmpUnknownPDUHandlers = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 3), Counter32()).setMaxAccess("readonly") -snmpMPDMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3)) -snmpMPDMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 1)) -snmpMPDMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 2)) - -# Augmentions - -# 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"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-MPD-MIB", PYSNMP_MODULE_ID=snmpMPDMIB) - -# Objects -mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDMIB=snmpMPDMIB, snmpMPDAdmin=snmpMPDAdmin, snmpMPDMIBObjects=snmpMPDMIBObjects, snmpMPDStats=snmpMPDStats, snmpUnknownSecurityModels=snmpUnknownSecurityModels, snmpInvalidMsgs=snmpInvalidMsgs, snmpUnknownPDUHandlers=snmpUnknownPDUHandlers, snmpMPDMIBConformance=snmpMPDMIBConformance, snmpMPDMIBCompliances=snmpMPDMIBCompliances, snmpMPDMIBGroups=snmpMPDMIBGroups) - -# Groups -mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDGroup=snmpMPDGroup) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-NOTIFICATION-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-NOTIFICATION-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-NOTIFICATION-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-NOTIFICATION-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-NOTIFICATION-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:36:54 2006, -# Python version (2, 4, 3, 'final', 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, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") -( SnmpTagValue, snmpTargetBasicGroup, snmpTargetBasicGroup, snmpTargetBasicGroup, snmpTargetParamsMPModel, snmpTargetParamsName, snmpTargetParamsRowStatus, snmpTargetParamsSecurityLevel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsStorageType, snmpTargetResponseGroup, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetBasicGroup", "snmpTargetBasicGroup", "snmpTargetBasicGroup", "snmpTargetParamsMPModel", "snmpTargetParamsName", "snmpTargetParamsRowStatus", "snmpTargetParamsSecurityLevel", "snmpTargetParamsSecurityModel", "snmpTargetParamsSecurityName", "snmpTargetParamsStorageType", "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 - -snmpNotificationMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 13)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) -snmpNotifyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 1)) -snmpNotifyTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 1)) -snmpNotifyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 1, 1)).setIndexNames((1, "SNMP-NOTIFICATION-MIB", "snmpNotifyName")) -snmpNotifyName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -snmpNotifyTag = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 2), SnmpTagValue().clone('')).setMaxAccess("readcreate") -snmpNotifyType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 3), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,1,)).subtype(namedValues=namedval.NamedValues(("trap", 1), ("inform", 2), )).clone(1)).setMaxAccess("readcreate") -snmpNotifyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -snmpNotifyRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate") -snmpNotifyFilterProfileTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 2)) -snmpNotifyFilterProfileEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 2, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetParamsName")) -snmpNotifyFilterProfileName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") -snmpNotifyFilterProfileStorType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 2), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -snmpNotifyFilterProfileRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") -snmpNotifyFilterTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 3)) -snmpNotifyFilterEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 3, 1)).setIndexNames((0, "SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), (1, "SNMP-NOTIFICATION-MIB", "snmpNotifyFilterSubtree")) -snmpNotifyFilterSubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 1), ObjectIdentifier()).setMaxAccess("noaccess") -snmpNotifyFilterMask = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 16)).clone('')).setMaxAccess("readcreate") -snmpNotifyFilterType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 3), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,2,)).subtype(namedValues=namedval.NamedValues(("included", 1), ("excluded", 2), )).clone(1)).setMaxAccess("readcreate") -snmpNotifyFilterStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -snmpNotifyFilterRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 5), RowStatus()).setMaxAccess("readcreate") -snmpNotifyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3)) -snmpNotifyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 1)) -snmpNotifyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 2)) - -# Augmentions - -# 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"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", PYSNMP_MODULE_ID=snmpNotificationMIB) - -# Objects -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) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-TARGET-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-TARGET-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-TARGET-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-TARGET-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-TARGET-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:15:47 2006, -# Python version (2, 4, 3, 'final', 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, SnmpMessageProcessingModel, SnmpSecurityLevel, SnmpSecurityModel, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpMessageProcessingModel", "SnmpSecurityLevel", "SnmpSecurityModel") -( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") -( Bits, Counter32, Integer32, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") -( RowStatus, StorageType, TAddress, TDomain, TextualConvention, TestAndIncr, TimeInterval, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TAddress", "TDomain", "TextualConvention", "TestAndIncr", "TimeInterval") - -# Types - -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 - -snmpTargetMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 12)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) -snmpTargetObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 1)) -snmpTargetSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 1), TestAndIncr()).setMaxAccess("readwrite") -snmpTargetAddrTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 2)) -snmpTargetAddrEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 2, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetAddrName")) -snmpTargetAddrName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -snmpTargetAddrTDomain = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 2), TDomain()).setMaxAccess("readcreate") -snmpTargetAddrTAddress = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 3), TAddress()).setMaxAccess("readcreate") -snmpTargetAddrTimeout = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 4), TimeInterval().clone(1500)).setMaxAccess("readcreate") -snmpTargetAddrRetryCount = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 255)).clone(3)).setMaxAccess("readcreate") -snmpTargetAddrTagList = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 6), SnmpTagList().clone('')).setMaxAccess("readcreate") -snmpTargetAddrParams = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 7), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") -snmpTargetAddrStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -snmpTargetAddrRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate") -snmpTargetParamsTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 3)) -snmpTargetParamsEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 3, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetParamsName")) -snmpTargetParamsName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -snmpTargetParamsMPModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 2), SnmpMessageProcessingModel()).setMaxAccess("readcreate") -snmpTargetParamsSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 3), SnmpSecurityModel().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("readcreate") -snmpTargetParamsSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 4), SnmpAdminString()).setMaxAccess("readcreate") -snmpTargetParamsSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 5), SnmpSecurityLevel()).setMaxAccess("readcreate") -snmpTargetParamsStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 6), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -snmpTargetParamsRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 7), RowStatus()).setMaxAccess("readcreate") -snmpUnavailableContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 4), Counter32()).setMaxAccess("readonly") -snmpUnknownContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 5), Counter32()).setMaxAccess("readonly") -snmpTargetConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3)) -snmpTargetCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 1)) -snmpTargetGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 2)) - -# Augmentions - -# Groups - -snmpTargetResponseGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 2)).setObjects(("SNMP-TARGET-MIB", "snmpTargetAddrRetryCount"), ("SNMP-TARGET-MIB", "snmpTargetAddrTimeout"), ) -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"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-TARGET-MIB", PYSNMP_MODULE_ID=snmpTargetMIB) - -# Types -mibBuilder.exportSymbols("SNMP-TARGET-MIB", SnmpTagList=SnmpTagList, SnmpTagValue=SnmpTagValue) - -# Objects -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) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-USER-BASED-SM-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-USER-BASED-SM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-USER-BASED-SM-MIB.py 2007-03-29 18:36:14.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-USER-BASED-SM-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USER-BASED-SM-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:39:13 2006, -# Python version (2, 4, 3, 'final', 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, snmpAuthProtocols, snmpPrivProtocols, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID", "snmpAuthProtocols", "snmpPrivProtocols") -( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") -( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") -( AutonomousType, RowPointer, RowStatus, StorageType, TextualConvention, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "AutonomousType", "RowPointer", "RowStatus", "StorageType", "TextualConvention", "TestAndIncr") - -# Types - -class KeyChange(OctetString): - pass - - -# Objects - -usmNoAuthProtocol = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 1, 1)) -usmHMACMD5AuthProtocol = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 1, 2)) -usmHMACSHAAuthProtocol = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 1, 3)) -usmNoPrivProtocol = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 2, 1)) -usmDESPrivProtocol = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 2, 2)) -snmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 15)).setRevisions(("2002-10-16 00:00","1999-01-20 00:00","1997-11-20 00:00",)) -usmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1)) -usmStats = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1, 1)) -usmStatsUnsupportedSecLevels = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 1), Counter32()).setMaxAccess("readonly") -usmStatsNotInTimeWindows = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 2), Counter32()).setMaxAccess("readonly") -usmStatsUnknownUserNames = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 3), Counter32()).setMaxAccess("readonly") -usmStatsUnknownEngineIDs = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 4), Counter32()).setMaxAccess("readonly") -usmStatsWrongDigests = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 5), Counter32()).setMaxAccess("readonly") -usmStatsDecryptionErrors = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 6), Counter32()).setMaxAccess("readonly") -usmUser = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1, 2)) -usmUserSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 2, 1), TestAndIncr()).setMaxAccess("readwrite") -usmUserTable = MibTable((1, 3, 6, 1, 6, 3, 15, 1, 2, 2)) -usmUserEntry = MibTableRow((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1)).setIndexNames((0, "SNMP-USER-BASED-SM-MIB", "usmUserEngineID"), (0, "SNMP-USER-BASED-SM-MIB", "usmUserName")) -usmUserEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 1), SnmpEngineID()).setMaxAccess("noaccess") -usmUserName = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -# Automatically initialize this column value from index name -class UsmUserSecurityName(MibTableColumn): - def __getUsmUserName(self, name): - __usmUserEntry, = mibBuilder.importSymbols( - 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' - ) - __usmUserEngineID, __usmUserName = __usmUserEntry.getIndicesFromInstId( - name[len(self.name):] - ) - return __usmUserName - def createTest(self, name, val, idx, (acFun, acCtx)): - return MibTableColumn.createTest( - self, name, self.__getUsmUserName(name), idx, (acFun, acCtx) - ) - def createCommit(self, name, val, idx, (acFun, acCtx)): - return MibTableColumn.createCommit( - self, name, self.__getUsmUserName(name), idx, (acFun, acCtx) - ) - def createCleanup(self, name, val, idx, (acFun, acCtx)): - return MibTableColumn.createCleanup( - self, name, self.__getUsmUserName(name), idx, (acFun, acCtx) - ) - def createUndo(self, name, val, idx, (acFun, acCtx)): - return MibTableColumn.createUndo( - self, name, self.__getUsmUserName(name), idx, (acFun, acCtx) - ) -usmUserSecurityName = UsmUserSecurityName((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 3), SnmpAdminString()).setMaxAccess("readonly") -usmUserCloneFrom = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 4), RowPointer()).setMaxAccess("readcreate") -usmUserAuthProtocol = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 5), AutonomousType().clone('1.3.6.1.6.3.10.1.1.1')).setMaxAccess("readcreate") -usmUserAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 6), KeyChange().clone('')).setMaxAccess("readcreate") -usmUserOwnAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 7), KeyChange().clone('')).setMaxAccess("readcreate") -usmUserPrivProtocol = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 8), AutonomousType().clone('1.3.6.1.6.3.10.1.2.1')).setMaxAccess("readcreate") -usmUserPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 9), KeyChange().clone('')).setMaxAccess("readcreate") -usmUserOwnPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 10), KeyChange().clone('')).setMaxAccess("readcreate") -usmUserPublic = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 11), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") -usmUserStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 12), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -usmUserStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 13), RowStatus()).setMaxAccess("readcreate") -usmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2)) -usmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 1)) -usmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 2)) - -# Augmentions - -# Groups - -usmMIBBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 15, 2, 2, 1)).setObjects(("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownEngineIDs"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmStatsNotInTimeWindows"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownUserNames"), ("SNMP-USER-BASED-SM-MIB", "usmUserSecurityName"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnsupportedSecLevels"), ("SNMP-USER-BASED-SM-MIB", "usmStatsDecryptionErrors"), ("SNMP-USER-BASED-SM-MIB", "usmUserStatus"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserStorageType"), ("SNMP-USER-BASED-SM-MIB", "usmUserSpinLock"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserCloneFrom"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmStatsWrongDigests"), ("SNMP-USER-BASED-SM-MIB", "usmUserPublic"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", PYSNMP_MODULE_ID=snmpUsmMIB) - -# Types -mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", KeyChange=KeyChange) - -# Objects -mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmNoAuthProtocol=usmNoAuthProtocol, usmHMACMD5AuthProtocol=usmHMACMD5AuthProtocol, usmHMACSHAAuthProtocol=usmHMACSHAAuthProtocol, usmNoPrivProtocol=usmNoPrivProtocol, usmDESPrivProtocol=usmDESPrivProtocol, snmpUsmMIB=snmpUsmMIB, usmMIBObjects=usmMIBObjects, usmStats=usmStats, usmStatsUnsupportedSecLevels=usmStatsUnsupportedSecLevels, usmStatsNotInTimeWindows=usmStatsNotInTimeWindows, usmStatsUnknownUserNames=usmStatsUnknownUserNames, usmStatsUnknownEngineIDs=usmStatsUnknownEngineIDs, usmStatsWrongDigests=usmStatsWrongDigests, usmStatsDecryptionErrors=usmStatsDecryptionErrors, usmUser=usmUser, usmUserSpinLock=usmUserSpinLock, usmUserTable=usmUserTable, usmUserEntry=usmUserEntry, usmUserEngineID=usmUserEngineID, usmUserName=usmUserName, usmUserSecurityName=usmUserSecurityName, usmUserCloneFrom=usmUserCloneFrom, usmUserAuthProtocol=usmUserAuthProtocol, usmUserAuthKeyChange=usmUserAuthKeyChange, usmUserOwnAuthKeyChange=usmUserOwnAuthKeyChange, usmUserPrivProtocol=usmUserPrivProtocol, usmUserPrivKeyChange=usmUserPrivKeyChange, usmUserOwnPrivKeyChange=usmUserOwnPrivKeyChange, usmUserPublic=usmUserPublic, usmUserStorageType=usmUserStorageType, usmUserStatus=usmUserStatus, usmMIBConformance=usmMIBConformance, usmMIBCompliances=usmMIBCompliances, usmMIBGroups=usmMIBGroups) - -# Groups -mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmMIBBasicGroup=usmMIBBasicGroup) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-USM-AES-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-USM-AES-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-USM-AES-MIB.py 2007-07-09 13:39:49.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-USM-AES-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USM-AES-MIB -# by libsmi2pysnmp-0.0.7-alpha at Mon Jul 9 17:29:49 2007, -# Python version (2, 4, 3, 'final', 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") - -# Objects - -usmAesCfb128Protocol = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1, 2, 4)) -snmpUsmAesMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 20)).setRevisions(("2004-06-14 00:00",)) - -# Augmentions - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-USM-AES-MIB", PYSNMP_MODULE_ID=snmpUsmAesMIB) - -# Objects -mibBuilder.exportSymbols("SNMP-USM-AES-MIB", usmAesCfb128Protocol=usmAesCfb128Protocol, snmpUsmAesMIB=snmpUsmAesMIB) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-CONF.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-CONF.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-CONF.py 2005-10-26 21:27:21.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-CONF.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ - -( MibNode, NotificationType ) = mibBuilder.importSymbols('SNMPv2-SMI','MibNode','NotificationType') - -class ObjectGroup(NotificationType): pass -class NotificationGroup(NotificationType): pass -class ModuleCompliance(MibNode): pass -class AgentCapabilities(MibNode): pass - -mibBuilder.exportSymbols('SNMPv2-CONF', ObjectGroup=ObjectGroup, NotificationGroup=NotificationGroup, ModuleCompliance=ModuleCompliance, AgentCapabilities=AgentCapabilities) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,106 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMPv2-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:55:03 2006, -# Python version (2, 4, 3, 'final', 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") -( ModuleCompliance, NotificationGroup, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") -( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, TimeTicks, mib_2, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "TimeTicks", "mib-2", "snmpModules") -( DisplayString, TestAndIncr, TimeStamp, ) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TestAndIncr", "TimeStamp") - -# Objects - -system = MibIdentifier((1, 3, 6, 1, 2, 1, 1)) -sysDescr = MibScalar((1, 3, 6, 1, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readonly") -sysObjectID = MibScalar((1, 3, 6, 1, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") -sysUpTime = MibScalar((1, 3, 6, 1, 2, 1, 1, 3), TimeTicks()).setMaxAccess("readonly") -sysContact = MibScalar((1, 3, 6, 1, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") -sysName = MibScalar((1, 3, 6, 1, 2, 1, 1, 5), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") -sysLocation = MibScalar((1, 3, 6, 1, 2, 1, 1, 6), DisplayString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") -sysServices = MibScalar((1, 3, 6, 1, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 127))).setMaxAccess("readonly") -sysORLastChange = MibScalar((1, 3, 6, 1, 2, 1, 1, 8), TimeStamp()).setMaxAccess("readonly") -sysORTable = MibTable((1, 3, 6, 1, 2, 1, 1, 9)) -sysOREntry = MibTableRow((1, 3, 6, 1, 2, 1, 1, 9, 1)).setIndexNames((0, "SNMPv2-MIB", "sysORIndex")) -sysORIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("noaccess") -sysORID = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") -sysORDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 3), DisplayString()).setMaxAccess("readonly") -sysORUpTime = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 4), TimeStamp()).setMaxAccess("readonly") -snmp = MibIdentifier((1, 3, 6, 1, 2, 1, 11)) -snmpInPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 1), Counter32()).setMaxAccess("readonly") -snmpOutPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 2), Counter32()).setMaxAccess("readonly") -snmpInBadVersions = MibScalar((1, 3, 6, 1, 2, 1, 11, 3), Counter32()).setMaxAccess("readonly") -snmpInBadCommunityNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 4), Counter32()).setMaxAccess("readonly") -snmpInBadCommunityUses = MibScalar((1, 3, 6, 1, 2, 1, 11, 5), Counter32()).setMaxAccess("readonly") -snmpInASNParseErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 6), Counter32()).setMaxAccess("readonly") -snmpInTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 8), Counter32()).setMaxAccess("readonly") -snmpInNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 9), Counter32()).setMaxAccess("readonly") -snmpInBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 10), Counter32()).setMaxAccess("readonly") -snmpInReadOnlys = MibScalar((1, 3, 6, 1, 2, 1, 11, 11), Counter32()).setMaxAccess("readonly") -snmpInGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 12), Counter32()).setMaxAccess("readonly") -snmpInTotalReqVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 13), Counter32()).setMaxAccess("readonly") -snmpInTotalSetVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 14), Counter32()).setMaxAccess("readonly") -snmpInGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 15), Counter32()).setMaxAccess("readonly") -snmpInGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 16), Counter32()).setMaxAccess("readonly") -snmpInSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 17), Counter32()).setMaxAccess("readonly") -snmpInGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 18), Counter32()).setMaxAccess("readonly") -snmpInTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 19), Counter32()).setMaxAccess("readonly") -snmpOutTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 20), Counter32()).setMaxAccess("readonly") -snmpOutNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 21), Counter32()).setMaxAccess("readonly") -snmpOutBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 22), Counter32()).setMaxAccess("readonly") -snmpOutGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 24), Counter32()).setMaxAccess("readonly") -snmpOutGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 25), Counter32()).setMaxAccess("readonly") -snmpOutGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 26), Counter32()).setMaxAccess("readonly") -snmpOutSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 27), Counter32()).setMaxAccess("readonly") -snmpOutGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 28), Counter32()).setMaxAccess("readonly") -snmpOutTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 29), Counter32()).setMaxAccess("readonly") -snmpEnableAuthenTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 30), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,1,)).subtype(namedValues=namedval.NamedValues(("enabled", 1), ("disabled", 2), ))).setMaxAccess("readwrite") -snmpSilentDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 31), Counter32()).setMaxAccess("readonly") -snmpProxyDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 32), Counter32()).setMaxAccess("readonly") -snmpMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 1)).setRevisions(("2002-10-16 00:00","1995-11-09 00:00","1993-04-01 00:00",)) -snmpMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1)) -snmpTrap = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 4)) -snmpTrapOID = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 1), ObjectIdentifier()).setMaxAccess("notifyonly") -snmpTrapEnterprise = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 3), ObjectIdentifier()).setMaxAccess("notifyonly") -snmpTraps = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5)) -snmpSet = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 6)) -snmpSetSerialNo = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 6, 1), TestAndIncr()).setMaxAccess("readwrite") -snmpMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2)) -snmpMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 1)) -snmpMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 2)) - -# Augmentions - -# 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() - -# 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 = ObjectGroup((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"), ) -snmpBasicNotificationsGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 7)).setObjects(("SNMPv2-MIB", "authenticationFailure"), ("SNMPv2-MIB", "coldStart"), ) -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"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMPv2-MIB", PYSNMP_MODULE_ID=snmpMIB) - -# Objects -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) - -# Groups -mibBuilder.exportSymbols("SNMPv2-MIB", snmpGroup=snmpGroup, snmpWarmStartNotificationGroup=snmpWarmStartNotificationGroup, snmpObsoleteGroup=snmpObsoleteGroup, snmpBasicNotificationsGroup=snmpBasicNotificationsGroup, snmpCommunityGroup=snmpCommunityGroup, snmpNotificationGroup=snmpNotificationGroup, systemGroup=systemGroup, snmpSetGroup=snmpSetGroup) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-SMI.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-SMI.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-SMI.py 2007-03-25 20:41:32.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-SMI.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,1006 +0,0 @@ -import string -from pysnmp.smi.indices import OidOrderedDict -from pysnmp.smi import exval, error -from pysnmp.proto import rfc1902 -from pyasn1.type import constraint -from pyasn1.error import ValueConstraintError -from pysnmp import debug - -( Integer, ObjectIdentifier, Null ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "Null") - -# syntax of objects - -OctetString = rfc1902.OctetString -Bits = rfc1902.Bits -Integer32 = rfc1902.Integer32 -IpAddress = rfc1902.IpAddress -Counter32 = rfc1902.Counter32 -Gauge32 = rfc1902.Gauge32 -Unsigned32 = rfc1902.Unsigned32 -TimeTicks = rfc1902.TimeTicks -Opaque = rfc1902.Opaque -Counter64 = rfc1902.Counter64 - -class ExtUTCTime(OctetString): - subtypeSpec = OctetString.subtypeSpec+constraint.ConstraintsUnion(constraint.ValueSizeConstraint(11,11), constraint.ValueSizeConstraint(13,13)) - -# MIB tree foundation classes - -class MibNode: - label = '' - def __init__(self, name): - self.name = name - - def __repr__(self): - return '%s(%s)' % (self.__class__.__name__, self.name) - - def getName(self): return self.name - - def getLabel(self): return self.label - def setLabel(self, label): - self.label = label - return self - - def clone(self, name=None): - myClone = self.__class__(self.name) - if name is not None: - myClone.name = name - if self.label is not None: - myClone.label = self.label - return myClone - -# definitions for information modules - -class ModuleIdentity(MibNode): - def getLastUpdated(self): - return getattr(self, 'lastUpdated', '') - def setLastUpdated(self, v): - self.lastUpdated = v - return self - def getOrganization(self): - return getattr(self, 'organization', '') - def setOrganization(self, v): - self.organization = v - return self - def getContactInfo(self): - return getattr(self, 'contactInfo', '') - def setContactInfo(self, v): - self.contactInfo = v - return self - def getDescription(self): - return getattr(self, 'description', '') - def setDescription(self, v): - self.description = v - return self - def getRevisions(self): - return getattr(self, 'revisions', ()) - def setRevisions(self, args): - self.revisions = args - return self - - def asn1Print(self): - return '\ -MODULE-IDENTITY\n\ - LAST-UPDATED %s\n\ - ORGANIZATION \"%s\"\n\ - CONTACT-INFO \"%s\"\n\ - DESCRIPTION \"%s\"\n\ - %s\ -' % (self.getLastUpdated(), - self.getOrganization(), - self.getContactInfo(), - self.getDescription(), - string.join(map(lambda x: "REVISON \"%s\"\n" % x, self.getRevisions()))) - -class ObjectIdentity(MibNode): - def getStatus(self): - return getattr(self, 'status', 'current') - def setStatus(self, v): - self.status = v - return self - def getDescription(self): - return getattr(self, 'description', '') - def setDescription(self, v): - self.description = v - return self - def getReference(self): - return getattr(self, 'reference', '') - def setReference(self, v): - self.reference = v - return self - - def asn1Print(self): - return '\ -OBJECT-IDENTITY\n\ - STATUS %s\n\ - DESCRIPTION \"%s\"\n\ - REFERENCE \"%s\"\ -' % (self.getStatus(), - self.getDescription(), - self.getReference()) - -# definition for objects - -class NotificationType(MibNode): - def getObjects(self): - return getattr(self, 'objects', ()) - def setObjects(self, *args): - self.objects = args - return self - def getStatus(self): - return getattr(self, 'status', 'current') - def setStatus(self, v): - self.status = v - return self - def getDescription(self): - return getattr(self, 'description', '') - def setDescription(self, v): - self.description = v - return self - def getRevisions(self): - return getattr(self, 'revisions', ()) - def setRevisions(self, args): - self.revisions = args - return self - - def asn1Print(self): - return '\ -NOTIFICATION-TYPE\n\ - OBJECTS { %s }\n\ - STATUS %s\n\ - DESCRIPTION \"%s\"\n\ - %s\ -' % (reduce(lambda x,y: '%s, %s' % (x[1],y[1]), self.getObjects(), ("","")), - self.getStatus(), - self.getDescription(), - string.join(map(lambda x: "REVISON \"%s\"\n" % x, self.getRevisions()))) - -class MibIdentifier(MibNode): - def asn1Print(self): - return 'OBJECT IDENTIFIER' - -class ObjectType(MibNode): - maxAccess = None - def __init__(self, name, syntax=None): - MibNode.__init__(self, name) - self.syntax = syntax - - # XXX - def __cmp__(self, other): return cmp(self.syntax, other) - - def __repr__(self): - return '%s(%s, %s)' % ( - self.__class__.__name__, self.name, self.syntax - ) - def getSyntax(self): - return self.syntax - def getUnits(self): - return getattr(self, 'units', '') - def setUnits(self, v): - self.units = v - return self - def getMaxAccess(self): - return getattr(self, 'maxAccess', 'not-accessible') - def setMaxAccess(self, v): - self.maxAccess = v - return self - def getStatus(self): - return getattr(self, 'status', 'current') - def setStatus(self, v): - self.status = v - return self - def getDescription(self): - return getattr(self, 'description', '') - def setDescription(self, v): - self.description = v - return self - def getReference(self): - return getattr(self, 'reference', '') - def setReference(self, v): - self.reference = v - return self - - def asn1Print(self): - return '\ -OBJECT-TYPE\n\ - SYNTAX %s\n\ - UNITS \"%s\"\n\ - MAX-ACCESS %s\n\ - STATUS %s\n\ - DESCRIPTION \"%s\"\n\ - REFERENCE \"%s\"\ -' % (self.getSyntax().__class__.__name__, - self.getUnits(), - self.getMaxAccess(), - self.getStatus(), - self.getDescription(), - self.getReference()) - -class MibTree(ObjectType): - branchVersionId = 0L # increments on tree structure change XXX - maxAccess = 'not-accessible' - def __init__(self, name, syntax=None): - ObjectType.__init__(self, name, syntax) - self._vars = OidOrderedDict() - - # Subtrees registration - - def registerSubtrees(self, *subTrees): - """Register subtrees at this tree. Subtrees are always attached - at the level of this tree, not subtrees.""" - for subTree in subTrees: - if self._vars.has_key(subTree.name): - continue -# XXX complain? -# if self._vars[subTree.name] is subTree: -# continue -# raise error.SmiError( -# 'MIB subtree %s already registered %s' % \ -# (subTree.name, self) -# ) - self._vars[subTree.name] = subTree - MibTree.branchVersionId = MibTree.branchVersionId + 1 - - def unregisterSubtrees(self, *subTrees): - """Detach subtrees from this tree""" - for subTree in subTrees: - if self._vars.has_key(subTree.name): - del self._vars[subTree.name] - MibTree.branchVersionId = MibTree.branchVersionId + 1 - - # Tree traversal - - def getBranch(self, name, idx): - """Return a branch of this tree where the 'name' OID may reside""" - name = tuple(name) # XXX - if len(self.name) < len(name): - for keyLen in self._vars.getKeysLens(): - subName = name[:keyLen] - if self._vars.has_key(subName): - return self._vars[subName] - raise error.NoSuchObjectError(name=name, idx=idx) - - def getNode(self, name, idx=None): - """Return tree node found by name""" - if name == self.name: - return self - else: - return self.getBranch(name, idx).getNode(name, idx) - - def getNextNode(self, name, idx=None): - """Return tree node next to name""" - try: - 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]] - else: - # Try following the white rabbit at our level - try: - return self._vars[self._vars.nextKey(name)] - except KeyError: - raise error.NoSuchObjectError(idx=idx, name=name) - else: - try: - return nextNode.getNextNode(name, idx) - except error.NoSuchObjectError: - try: - return self._vars[self._vars.nextKey(nextNode.name)] - except KeyError: - raise error.NoSuchObjectError(idx=idx, name=name) - - # MIB instrumentation - - # Read operation - - def readTest(self, name, val, idx, (acFun, acCtx)): - if name == self.name: - if acFun and \ - self.maxAccess != 'readonly' and \ - self.maxAccess != 'readwrite' and \ - self.maxAccess != 'readcreate' or \ - acFun and acFun(name, idx, 'read', acCtx): - raise error.NoAccessError(idx=idx, name=name) - else: - try: - node = self.getBranch(name, idx) - except error.NoSuchObjectError: - return # missing object is not an error here - - node.readTest(name, val, idx, (acFun, acCtx)) - - def readGet(self, name, val, idx, (acFun, acCtx)): - try: - node = self.getBranch(name, idx) - except error.NoSuchObjectError: - return name, exval.noSuchInstance - else: - return node.readGet(name, val, idx, (acFun, acCtx)) - - # Read next operation is subtree-specific - - def readTestNext(self, name, val, idx, (acFun, acCtx)): - nextName = name - while 1: # XXX linear search here - try: - nextName = self.getNextNode(nextName, idx).name - except error.NoSuchObjectError: - return # missing object is not an error here - try: - return self.readTest(nextName, val, idx, (acFun, acCtx)) - except error.NoAccessError: - continue - - def readGetNext(self, name, val, idx, (acFun, acCtx)): - nextName = name - while 1: - try: - nextName = self.getNextNode(nextName, idx).name - except error.NoSuchObjectError: - return name, exval.endOfMib - try: - self.readTest(nextName, val, idx, (acFun, acCtx)) # XXX - except error.NoAccessError: - continue - else: - return self.readGet(nextName, val, idx, (acFun, acCtx)) - - # Write operation - - def writeTest(self, name, val, idx, (acFun, acCtx)): - if name == self.name: - # Make sure variable is writable - if acFun and \ - self.maxAccess != 'readwrite' and \ - self.maxAccess != 'readcreate' or \ - acFun and acFun(name, idx, 'write', acCtx): - raise error.NotWritableError(idx=idx, name=name) - else: - node = self.getBranch(name, idx) - node.writeTest(name, val, idx, (acFun, acCtx)) - - def writeCommit(self, name, val, idx, (acFun, acCtx)): - self.getBranch(name, idx).writeCommit(name, val, idx, (acFun, acCtx)) - - def writeCleanup(self, name, val, idx, (acFun, acCtx)): - self.getBranch(name, idx).writeCleanup(name, val, idx, (acFun, acCtx)) - - def writeUndo(self, name, val, idx, (acFun, acCtx)): - self.getBranch(name, idx).writeUndo(name, val, idx, (acFun, acCtx)) - -class MibScalar(MibTree): - """Scalar MIB variable. Implements access control checking.""" - maxAccess = 'readonly' - - # MIB instrumentation methods - - # Read operation - - def readTest(self, name, val, idx, (acFun, acCtx)): - if name == self.name: - raise error.NoAccessError(idx=idx, name=name) - else: - MibTree.readTest(self, name, val, idx, (acFun, acCtx)) - # If instance exists, check permissions - if acFun and \ - self.maxAccess != 'readonly' and \ - self.maxAccess != 'readwrite' and \ - self.maxAccess != 'readcreate' or \ - acFun and acFun(name, idx, 'read', acCtx): - raise error.NoAccessError(idx=idx, name=name) - - # Two-phase commit implementation - - def writeTest(self, name, val, idx, (acFun, acCtx)): - if name == self.name: - raise error.NoAccessError(idx=idx, name=name) - else: - MibTree.writeTest(self, name, val, idx, (acFun, acCtx)) - # If instance exists, check permissions - if acFun and \ - self.maxAccess != 'readwrite' and \ - self.maxAccess != 'readcreate' or \ - acFun and acFun(name, idx, 'write', acCtx): - raise error.NotWritableError(idx=idx, name=name) - -class MibScalarInstance(MibTree): - """Scalar MIB variable instance. Implements read/write operations.""" - def __init__(self, typeName, instId, syntax): - MibTree.__init__(self, typeName+instId, syntax) - self.typeName = typeName - self.instId = instId - - def getNode(self, name, idx=None): - # Recursion terminator - if name == self.name: - return self - raise error.NoSuchInstanceError(idx=idx, name=name) - - def getNextNode(self, name, idx=None): - raise error.NoSuchInstanceError(idx=idx, name=name) - - # MIB instrumentation methods - - # Read operation - - def readTest(self, name, val, idx, (acFun, acCtx)): - if name != self.name: - raise error.NoSuchObjectError(idx=idx, name=name) - - def readGet(self, name, val, idx, (acFun, acCtx)): - # Return current variable (name, value). This is the only API method - # capable of returning anything! - if name == self.name: - debug.logger & debug.flagIns and debug.logger('readGet: %s=%s' % (self.name, self.syntax)) - if hasattr(self.syntax, 'smiRead'): - return self.name, self.syntax.smiRead(name, val, idx) - else: - return self.name, self.syntax.clone() - else: - raise error.NoSuchObjectError(idx=idx, name=name) - - # Write operation: two-phase commit - - def writeTest(self, name, val, idx, (acFun, acCtx)): - # Make sure write's allowed - if name == self.name: - if hasattr(self.syntax, 'smiWrite'): - self.__newSyntax = self.syntax.smiWrite(name, val, idx) - else: - self.__newSyntax = self.syntax.clone(val) - if hasattr(self.__newSyntax, 'smiRaisePendingError'): - self.__newSyntax.smiRaisePendingError() - else: - raise error.NoSuchObjectError(idx=idx, name=name) - - def writeCommit(self, name, val, idx, (acFun, acCtx)): - # Commit new value - self.syntax, self.__newSyntax = self.__newSyntax, self.syntax - - def writeCleanup(self, name, val, idx, (acFun, acCtx)): - debug.logger & debug.flagIns and debug.logger('writeCleanup: %s=%s' % (name, val)) - # Drop previous value - self.__newSyntax = None - - def writeUndo(self, name, val, idx, (acFun, acCtx)): - # Revive previous value - self.syntax, self.__newSyntax = self.__newSyntax, None - - # Table column instance specifics - - # Create operation - - def createTest(self, name, val, idx, (acFun, acCtx)): - if name == self.name: - if hasattr(self.syntax, 'smiCreate'): - self.__newSyntax = self.syntax.smiCreate(name, val, idx) - else: - self.__newSyntax = self.syntax.clone(val) - else: - raise error.NoSuchObjectError(idx=idx, name=name) - def createCommit(self, name, val, idx, (acFun, acCtx)): - if val is not None: - self.writeCommit(name, val, idx, (acFun, acCtx)) - def createCleanup(self, name, val, idx, (acFun, acCtx)): - debug.logger & debug.flagIns and debug.logger('createCleanup: %s=%s' % (name, val)) - if val is not None: - self.writeCleanup(name, val, idx, (acFun, acCtx)) - def createUndo(self, name, val, idx, (acFun, acCtx)): - if val is not None: - self.writeCleanup(name, val, idx, (acFun, acCtx)) - - # Destroy operation - - def destroyTest(self, name, val, idx, (acFun, acCtx)): - if name == self.name: - if hasattr(self.syntax, 'smiDestroy'): - self.__newSyntax = self.syntax.smiDestoy(name, val) - else: - 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 - -# Conceptual table classes - -class MibTableColumn(MibScalar): - """MIB table column. Manages a set of column instance variables""" - protoInstance = MibScalarInstance - def __init__(self, name, syntax): - MibScalar.__init__(self, name, syntax) - self.__createdInstances = {}; self.__destroyedInstances = {} - self.__rowOpWanted = {} - - def getNode(self, name, idx=None): - try: - return MibScalar.getNode(self, name, idx=None) - except error.NoSuchObjectError: - raise error.NoSuchInstanceError(idx=idx, name=name) - - def getNextNode(self, name, idx=None): - try: - return MibScalar.getNextNode(self, name, idx=None) - except error.NoSuchObjectError: - raise error.NoSuchInstanceError(idx=idx, name=name) - - def setProtoInstance(self, protoInstance): - self.protoInstance = protoInstance - - # Column creation (this should probably be converted into some state - # 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)): - # Make sure creation allowed, create a new column instance but - # do not replace the old one - if name == self.name: - raise error.NoAccessError(idx=idx, name=name) - if acFun and \ - val is not None and \ - self.maxAccess != 'readcreate' or \ - acFun and acFun(name, idx, 'write', acCtx): - raise error.NoCreationError(idx=idx, name=name) - # Create instances if either is does not yet exist (row creation) - # or a value is passed (multiple OIDs in SET PDU) - if val is None and self.__createdInstances.has_key(name): - return - self.__createdInstances[name] = self.protoInstance( - self.name, name[len(self.name):], self.syntax.clone() - ) - self.__createdInstances[name].createTest( - name, val, idx, (acFun, acCtx) - ) - - def createCommit(self, name, val, idx, (acFun, acCtx)): - # Commit new instance value - if self._vars.has_key(name): # XXX - if self.__createdInstances.has_key(name): - self._vars[name].createCommit(name, val, idx, (acFun, acCtx)) - return - self.__createdInstances[name].createCommit( - name, val, idx, (acFun, acCtx) - ) - # ...commit new column instance - self._vars[name], self.__createdInstances[name] = \ - self.__createdInstances[name], self._vars.get(name) - - def createCleanup(self, name, val, idx, (acFun, acCtx)): - # Drop previous column instance - if self.__createdInstances.has_key(name): - if self.__createdInstances[name] is not None: - self.__createdInstances[name].createCleanup( - name, val, idx, (acFun, acCtx) - ) - del self.__createdInstances[name] - elif self._vars.has_key(name): - self._vars[name].createCleanup(name, val, idx, (acFun, acCtx)) - - def createUndo(self, name, val, idx, (acFun, acCtx)): - # Set back previous column instance, drop the new one - if self.__createdInstances.has_key(name): - self._vars[name] = self.__createdInstances[name] - del self.__createdInstances[name] - # Remove new instance on rollback - if self._vars[name] is None: - del self._vars[name] - else: - self._vars[name].createUndo(name, val, idx, (acFun, acCtx)) - - # Column destruction - - def destroyTest(self, name, val, idx, (acFun, acCtx)): - # Make sure destruction is allowed - if name == self.name: - raise error.NoAccessError(idx=idx, name=name) - if not self._vars.has_key(name): - return - if acFun and \ - val is not None and \ - self.maxAccess != 'readcreate' or \ - acFun and acFun(name, idx, 'write', acCtx): - raise error.NoAccessError(idx=idx, name=name) - self._vars[name].destroyTest( - name, val, idx, (acFun, acCtx) - ) - - def destroyCommit(self, name, val, idx, (acFun, acCtx)): - # Make a copy of column instance and take it off the tree - if self._vars.has_key(name): - self._vars[name].destroyCommit( - name, val, idx, (acFun, acCtx) - ) - self.__destroyedInstances[name] = self._vars[name] - del self._vars[name] - - def destroyCleanup(self, name, val, idx, (acFun, acCtx)): - # Drop instance copy - if self.__destroyedInstances.has_key(name): - self.__destroyedInstances[name].destroyCleanup( - name, val, idx, (acFun, acCtx) - ) - debug.logger & debug.flagIns and debug.logger('destroyCleanup: %s=%s' % (name, val)) - del self.__destroyedInstances[name] - - def destroyUndo(self, name, val, idx, (acFun, acCtx)): - # Set back column instance - if self.__destroyedInstances.has_key(name): - self._vars[name] = self.__destroyedInstances[name] - self._vars[name].destroyUndo( - name, val, idx, (acFun, acCtx) - ) - del self.__destroyedInstances[name] - - # Set/modify column - - def writeTest(self, name, val, idx, (acFun, acCtx)): - # Besides common checks, request row creation on no-instance - try: - # First try the instance - MibScalar.writeTest( - self, name, val, idx, (acFun, acCtx) - ) - # ...otherwise proceed with creating new column - except (error.NoSuchObjectError, error.RowCreationWanted): - self.__rowOpWanted[name] = error.RowCreationWanted() - self.createTest(name, val, idx, (acFun, acCtx)) - except error.RowDestructionWanted: - self.__rowOpWanted[name] = error.RowDestructionWanted() - self.destroyTest(name, val, idx, (acFun, acCtx)) - if self.__rowOpWanted.has_key(name): - debug.logger & debug.flagIns and debug.logger('%s flagged by %s=%s' % (self.__rowOpWanted[name], name, val)) - raise self.__rowOpWanted[name] - - def __delegateWrite(self, subAction, name, val, idx, (acFun, acCtx)): - if not self.__rowOpWanted.has_key(name): - getattr(MibScalar, 'write'+subAction)( - self, name, val, idx, (acFun, acCtx) - ) - return - if isinstance(self.__rowOpWanted[name], error.RowCreationWanted): - getattr(self, 'create'+subAction)( - name, val, idx, (acFun, acCtx) - ) - if isinstance(self.__rowOpWanted[name], error.RowDestructionWanted): - getattr(self, 'destroy'+subAction)( - name, val, idx, (acFun, acCtx) - ) - - def writeCommit(self, name, val, idx, (acFun, acCtx)): - self.__delegateWrite( - 'Commit', name, val, idx, (acFun, acCtx) - ) - if self.__rowOpWanted.has_key(name): - raise self.__rowOpWanted[name] - - def writeCleanup(self, name, val, idx, (acFun, acCtx)): - self.__delegateWrite( - 'Cleanup', name, val, idx, (acFun, acCtx) - ) - if self.__rowOpWanted.has_key(name): - e = self.__rowOpWanted[name] - del self.__rowOpWanted[name] - debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%s' % (e, name, val)) - raise e - - def writeUndo(self, name, val, idx, (acFun, acCtx)): - self.__delegateWrite( - 'Undo', name, val, idx, (acFun, acCtx) - ) - if self.__rowOpWanted.has_key(name): - e = self.__rowOpWanted[name] - del self.__rowOpWanted[name] - debug.logger & debug.flagIns and debug.logger('%s dropped by %s=%s' % (e, name, val)) - raise e - -class MibTableRow(MibTree): - """MIB table row (SMI 'Entry'). Manages a set of table columns. - Implements row creation/destruction. - """ - def __init__(self, name): - MibTree.__init__(self, name) - self.indexNames = () - self.augmentingRows = {} - - # Table indices resolution. Handle almost all possible rfc1902 types - # explicitly rather than by means of isSuperTypeOf() method because - # some subtypes may be implicitly tagged what renders base tag - # unavailable. - - __intValue = Integer() - __counter32Value = Counter32() - __uint32Value = Unsigned32() - __timeticksValue = TimeTicks() - __counter64Value = Counter64() - __strValue = OctetString() - __oidValue = ObjectIdentifier() - __ipaddrValue = IpAddress() - __bitsValue = Bits() - - def setFromName(self, obj, value, impliedFlag=None): - if not value: - raise error.SmiError('Short OID for index %s' % repr(obj)) - if self.__intValue.isSuperTypeOf(obj) or \ - self.__uint32Value.isSuperTypeOf(obj) or \ - self.__timeticksValue.isSuperTypeOf(obj) or \ - self.__counter32Value.isSuperTypeOf(obj) or \ - self.__counter64Value.isSuperTypeOf(obj): - return obj.clone(value[0]), value[1:] - elif self.__ipaddrValue.isSuperTypeOf(obj): - return obj.clone(string.join(map(str, value[:4]), '.')), value[4:] - elif self.__strValue.isSuperTypeOf(obj): - # rfc1902, 7.7 - if impliedFlag: - s = reduce(lambda x,y: x+y, map(lambda x: chr(x), value)) - return obj.clone(s), () - elif obj.isFixedLength(): - len = obj.getFixedLength() - s = reduce(lambda x,y: x+y, map(lambda x: chr(x), value[:len])) - return obj.clone(s), value[len:] - else: - s = reduce(lambda x,y: x+y, - map(lambda x: chr(x), value[1:value[0]+1]), '') - return obj.clone(s), value[value[0]+1:] - elif self.__oidValue.isSuperTypeOf(obj): - if impliedFlag: - return obj.clone(value), () - else: - return obj.clone(value[1:value[0]+1]), value[value[0]+1:] - # rfc2578, 7.1 - elif self.__bitsValue.isSuperTypeOf(obj): - s = reduce( - lambda x,y: x+y, map(lambda x: chr(x),value[1:value[0]+1]),'' - ) - return obj.clone(s), value[value[0]+1:] - else: - raise error.SmiError('Unknown value type for index %s' % repr(obj)) - - def getAsName(self, obj, impliedFlag=None): - if self.__intValue.isSuperTypeOf(obj) or \ - self.__uint32Value.isSuperTypeOf(obj) or \ - self.__timeticksValue.isSuperTypeOf(obj) or \ - self.__counter32Value.isSuperTypeOf(obj) or \ - self.__counter64Value.isSuperTypeOf(obj): - return (int(obj),) - elif self.__ipaddrValue.isSuperTypeOf(obj): - return tuple(map(ord, obj)) - elif self.__strValue.isSuperTypeOf(obj): - if impliedFlag or obj.isFixedLength(): - initial = () - else: - initial = (len(obj),) - return reduce( - lambda x,y: x+(y,), map(lambda x: ord(x), obj), initial - ) - elif self.__oidValue.isSuperTypeOf(obj): - if impliedFlag: - return tuple(obj) - else: - return (len(self.name),) + tuple(obj) - # rfc2578, 7.1 - elif self.__bitsValue.isSuperTypeOf(obj): - return reduce( - lambda x,y: x+(y,), map(lambda x: ord(x), obj),(len(obj),) - ) - else: - raise error.SmiError('Unknown value type for index %s' % repr(obj)) - - # Fate sharing mechanics - - def announceManagementEvent(self, action, name, val, idx, (acFun, acCtx)): - # Convert OID suffix into index vals - instId = name[len(self.name)+1:] - baseIndices = [] - for impliedFlag, modName, symName in self.indexNames: - mibObj, = mibBuilder.importSymbols(modName, symName) - syntax, instId = self.setFromName( - mibObj.syntax, instId, impliedFlag - ) - if self.name == mibObj.name[:-1]: - baseIndices.append((mibObj.name, syntax)) - if instId: - raise error.SmiError( - 'Excessive instance identifier sub-OIDs left at %s: %s' % - (self, instId) - ) - if not baseIndices: - return - for modName, mibSym in self.augmentingRows.keys(): - mibObj, = mibBuilder.importSymbols(modName, mibSym) - debug.logger & debug.flagIns and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) - mibObj.receiveManagementEvent( - action, baseIndices, val, idx, (acFun, acCtx) - ) - - def receiveManagementEvent( - self, action, baseIndices, val, idx, (acFun, acCtx) - ): - # The default implementation supports one-to-one rows dependency - newSuffix = () - # Resolve indices intersection - for impliedFlag, modName, symName in self.indexNames: - mibObj, = mibBuilder.importSymbols(modName, symName) - for name, syntax in baseIndices: - if name == mibObj.name: - newSuffix = newSuffix + self.getAsName(syntax, impliedFlag) - if newSuffix: - debug.logger & debug.flagIns and debug.logger('receiveManagementEvent %s for suffix %s' % (action, newSuffix)) - self.__manageColumns(action, (), newSuffix, val, idx, - (acFun, acCtx)) - - def registerAugmentions(self, *names): - for modName, symName in names: - if self.augmentingRows.has_key((modName, symName)): - raise error.SmiError( - 'Row %s already augmented by %s::%s' % \ - (self.name, modName, symName) - ) - self.augmentingRows[(modName, symName)] = 1 - return self - - def setIndexNames(self, *names): - for name in names: - self.indexNames = self.indexNames + (name,) - return self - - def getIndexNames(self): - return self.indexNames - - def __manageColumns(self, action, excludeName, nameSuffix, - val, idx, (acFun, acCtx)): - # Build a map of index names and values for automatic initialization - indexVals = {}; instId = nameSuffix - for impliedFlag, modName, symName in self.indexNames: - mibObj, = mibBuilder.importSymbols(modName, symName) - syntax, instId = self.setFromName( - mibObj.syntax, instId, impliedFlag - ) - indexVals[mibObj.name] = syntax - for name, var in self._vars.items(): - if name == excludeName: - continue - if indexVals.has_key(name): - getattr(var, action)(name + nameSuffix, indexVals[name], idx, - (None, None)) - else: - getattr(var, action)(name + nameSuffix, val, idx, - (acFun, acCtx)) - debug.logger & debug.flagIns and debug.logger('__manageColumns: action %s name %s suffix %s %svalue %s' % (action, name, nameSuffix, indexVals.has_key(name) and "index " or "", indexVals.get(name, val))) - - def __delegate(self, subAction, name, val, idx, (acFun, acCtx)): - # 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: - self.__manageColumns( - 'create'+subAction, name[:len(self.name)+1], - name[len(self.name)+1:], None, idx, (acFun, acCtx) - ) - self.announceManagementEvent( - 'create'+subAction, name, None, idx, (acFun, acCtx) - ) - except error.RowDestructionWanted, why: - self.__manageColumns( - 'destroy'+subAction, name[:len(self.name)+1], - name[len(self.name)+1:], None, idx, (acFun, acCtx) - ) - self.announceManagementEvent( - '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)) - - # Table row management - - # Table row access by instance name - - def getInstName(self, colId, instId): - return self.name + (colId,) + instId - - # Table index management - - def getIndicesFromInstId(self, instId): - """Return index values for instance identification""" - indices = [] - for impliedFlag, modName, symName in self.indexNames: - mibObj, = mibBuilder.importSymbols(modName, symName) - syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag) - indices.append(syntax) # to avoid cyclic refs - if instId: - raise error.SmiError( - 'Excessive instance identifier sub-OIDs left at %s: %s' % - (self, instId) - ) - return tuple(indices) - - def getInstIdFromIndices(self, *indices): - """Return column instance identification from indices""" - idx = 0; instId = () - for impliedFlag, modName, symName in self.indexNames: - mibObj, = mibBuilder.importSymbols(modName, symName) - if idx < len(indices): - instId = instId + self.getAsName( - mibObj.syntax.clone(indices[idx]), - impliedFlag - ) - else: - break - idx = idx + 1 - return instId - - # Table access by index - - def getInstNameByIndex(self, colId, *indices): - """Build column instance name from components""" - return self.name + (colId,) + apply( - 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) - ) - return tuple(instNames) - -class MibTable(MibTree): - """MIB table. Manages a set of TableRow's""" - def __init__(self, name): - MibTree.__init__(self, name) - -zeroDotZero = ObjectIdentity((0,0)) - -#dot = MibTree() -iso = MibTree((1,)) -org = MibIdentifier(iso.name + (3,)) -dod = MibIdentifier(org.name + (6,)) -internet = MibIdentifier(dod.name + (1,)) -directory = MibIdentifier(internet.name + (1,)) -mgmt = MibIdentifier(internet.name + (2,)) -mib_2 = MibIdentifier(mgmt.name + (1,)); mib_2.label = 'mib-2' -transmission = MibIdentifier(mib_2.name + (10,)) -experimental = MibIdentifier(internet.name + (3,)) -private = MibIdentifier(internet.name + (4,)) -enterprises = MibIdentifier(private.name + (1,)) -security = MibIdentifier(internet.name + (5,)) -snmpV2 = MibIdentifier(internet.name + (6,)) - -snmpDomains = MibIdentifier(snmpV2.name + (1,)) -snmpProxys = MibIdentifier(snmpV2.name +(2,)) -snmpModules = MibIdentifier(snmpV2.name +(3,)) - -mibBuilder.exportSymbols( - 'SNMPv2-SMI', Integer32=Integer32, Bits=Bits, IpAddress=IpAddress, - Counter32=Counter32, Gauge32=Gauge32, Unsigned32=Unsigned32, - TimeTicks=TimeTicks, Opaque=Opaque, Counter64=Counter64, - ExtUTCTime=ExtUTCTime, MibNode=MibNode, - ModuleIdentity=ModuleIdentity, ObjectIdentity=ObjectIdentity, - NotificationType=NotificationType, MibScalar=MibScalar, - MibScalarInstance=MibScalarInstance, - MibIdentifier=MibIdentifier, MibTree=MibTree, - MibTableColumn=MibTableColumn, MibTableRow=MibTableRow, - MibTable=MibTable, zeroDotZero=zeroDotZero, - iso=iso, org=org, dod=dod, internet=internet, - directory=directory, mgmt=mgmt, mib_2=mib_2, transmission=transmission, - experimental=experimental, private=private, enterprises=enterprises, - security=security, snmpV2=snmpV2, snmpDomains=snmpDomains, - snmpProxys=snmpProxys, snmpModules=snmpModules - ) - -# XXX -# getAsName/setFromName goes out of MibRow? -# revisit getNextNode() -- needs optimization diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-TC.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-TC.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-TC.py 2007-02-07 13:01:32.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-TC.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,343 +0,0 @@ -from string import split, digits -from pysnmp.smi import error -from pyasn1.type import constraint, namedval -from pysnmp import debug - -OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols( - 'ASN1', 'OctetString', 'Integer', 'ObjectIdentifier' - ) -Counter32, Unsigned32, TimeTicks, Counter64 = mibBuilder.importSymbols( - 'SNMPv2-SMI', 'Counter32', 'Unsigned32', 'TimeTicks', 'Counter64' - ) - -class TextualConvention: - displayHint = '' - status = 'current' - description = '' - reference = '' - bits = () - __integer = Integer() - __counter32 = Counter32() - __unsigned32 = Unsigned32() - __timeticks = TimeTicks() - __counter64 = Counter64() - __octetString = OctetString() - __objectIdentifier = ObjectIdentifier() - def getDisplayHint(self): return self.displayHint - def getStatus(self): return self.status - def getDescription(self): return self.description - def getReference(self): return self.reference - - def prettyOut(self, value): # override asn1 type method - """Implements DISPLAY-HINT evaluation""" - if self.displayHint and ( - self.__integer.isSuperTypeOf(self) or - self.__unsigned32.isSuperTypeOf(self) or - self.__timeticks.isSuperTypeOf(self) or - self.__counter32.isSuperTypeOf(self) or - self.__counter64.isSuperTypeOf(self) - ): - t, f = apply(lambda t, f=0: (t, f), split(self.displayHint, '-')) - if t == 'x': - return '0x%x' % value - elif t == 'd': - try: - return '%.*f' % (int(f), float(value)/pow(10, int(f))) - except StandardError, why: - raise error.SmiError( - 'float num evaluation error: %s' % why - ) - elif t == 'o': - return '0%o' % value - elif t == 'b': - v = value; r = ['B'] - while v: - r.insert(0, '%d' % (v&0x01)) - v = v>>1 - 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) - d = self.displayHint - while v and d: - # 1 - if d[0] == '*': - repeatIndicator = repeatCount = int(v[0]) - d = d[1:]; v = v[1:] - else: - repeatCount = 1; repeatIndicator = None - - # 2 - octetLength = '' - while d and d[0] in digits: - octetLength = octetLength + d[0] - d = d[1:] - try: - octetLength = int(octetLength) - except StandardError, why: - raise error.SmiError( - 'Bad octet length: %s' % octetLength - ) - if not d: - raise error.SmiError( - 'Short octet length: %s' % self.displayHint - ) - # 3 - displayFormat = d[0] - d = d[1:] - - # 4 - if d and d[0] not in digits and d[0] != '*': - displaySep = d[0] - d = d[1:] - else: - displaySep = '' - - # 5 - if d and displaySep and repeatIndicator is not None: - repeatTerminator = d[0] - displaySep = '' - d = d[1:] - else: - repeatTerminator = None - - while repeatCount: - repeatCount = repeatCount - 1 - # 't' stands for UTF-8, does it need any special support? - if displayFormat == 'a' or displayFormat == 't': - r = r + v[:octetLength] - elif displayFormat in ('x', 'd', 'o'): - n = 0L; vv = v[:octetLength] - while vv: - n = n << 8 - try: - n = n | ord(vv[0]) - vv = vv[1:] - except StandardError, why: - raise error.SmiError( - 'Display format eval failure: %s: %s' - % (vv, why) - ) - if displayFormat == 'x': - r = r + '%02x' % n - elif displayFormat == 'o': - r = r + '%03o' % n - else: - r = r + '%d' % n - else: - raise error.SmiError( - 'Unsupported display format char: %s' % \ - displayFormat - ) - if v and repeatTerminator: - r = r + repeatTerminator - v = v[octetLength:] - if v and displaySep: - r = r + displaySep - if not d: - d = self.displayHint -# if d: -# raise error.SmiError( -# 'Unparsed display hint left: %s' % d -# ) - return r - elif self.displayHint and self.__objectIdentifier.isSuperTypeOf(self): - return str(value) - else: - return str(value) - -# elif self.bits: -# try: -# return self.bits[value] -# except StandardError, why: -# raise error.SmiError( -# 'Enumeratin resolution failure for %s: %s' % (self, why) -# ) - -# XXX -# def prettyIn(self, value): -# # XXX parse TC syntax -# return str(value) - -class DisplayString(TextualConvention, OctetString): - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(0,255) - displayHint = "255a" - -class PhysAddress(TextualConvention, OctetString): - displayHint = "1x:" - -class MacAddress(TextualConvention, OctetString): - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(6,6) - displayHint = "1x:" - fixedLength = 6 - -class TruthValue(Integer, TextualConvention): - subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(1, 2) - namedValues = namedval.NamedValues(('true', 1), ('false', 2)) - -class TestAndIncr(Integer, TextualConvention): - subtypeSpec = Integer.subtypeSpec+constraint.ValueRangeConstraint(0, 2147483647L) - defaultValue = 0 - def smiWrite(self, name, value, idx): - if value != self: - raise error.InconsistentValueError(idx=idx, name=name) - value = value + 1 - if value > 2147483646: - value = 0 - return self.clone(value) - -class AutonomousType(ObjectIdentifier, TextualConvention): pass -class InstancePointer(ObjectIdentifier, TextualConvention): - status = 'obsolete' -class VariablePointer(ObjectIdentifier, TextualConvention): pass -class RowPointer(ObjectIdentifier, TextualConvention): pass - -class RowStatus(Integer, TextualConvention): - """A special kind of scalar MIB variable responsible for - MIB table row creation/destruction. - """ - subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(0, 1, 2, 3, 4, 5, 6) - namedValues = namedval.NamedValues( - ('notExists', 0), ('active', 1), ('notInService', 2), ('notReady', 3), - ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6) - ) - # Known row states - stNotExists, stActive, stNotInService, stNotReady, \ - stCreateAndGo, stCreateAndWait, stDestroy = range(7) - # States transition matrix (see RFC-1903) - stateMatrix = { - # (new-state, current-state) -> (error, new-state) - ( stCreateAndGo, stNotExists ): ( - error.RowCreationWanted, stActive - ), - ( stCreateAndGo, stNotReady ): ( - error.InconsistentValueError, stNotReady - ), - ( stCreateAndGo, stNotInService ): ( - error.InconsistentValueError, stNotInService - ), - ( stCreateAndGo, stActive ): ( - error.InconsistentValueError, stActive - ), - # - ( stCreateAndWait, stNotExists ): ( - error.RowCreationWanted, stActive - ), - ( stCreateAndWait, stNotReady ): ( - error.InconsistentValueError, stNotReady - ), - ( stCreateAndWait, stNotInService ): ( - error.InconsistentValueError, stNotInService - ), - ( stCreateAndWait, stActive ): ( - error.InconsistentValueError, stActive - ), - # - ( stActive, stNotExists ): ( - error.InconsistentValueError, stNotExists - ), - ( stActive, stNotReady ): ( - error.InconsistentValueError, stNotReady - ), - ( stActive, stNotInService ): ( - None, stActive - ), - ( stActive, stActive ): ( - None, stActive - ), - # - ( stNotInService, stNotExists ): ( - error.InconsistentValueError, stNotExists - ), - ( stNotInService, stNotReady ): ( - error.InconsistentValueError, stNotReady - ), - ( stNotInService, stNotInService ): ( - None, stNotInService - ), - ( stNotInService, stActive ): ( - None, stActive - ), - # - ( stDestroy, stNotExists ): ( - error.RowDestructionWanted, stNotExists - ), - ( stDestroy, stNotReady ): ( - error.RowDestructionWanted, stNotExists - ), - ( stDestroy, stNotInService ): ( - error.RowDestructionWanted, stNotExists - ), - ( stDestroy, stActive ): ( - error.RowDestructionWanted, stNotExists - ), - # This is used on instantiation - ( stNotExists, stNotExists ): ( - None, stNotExists - ) - } - defaultValue = stNotExists - pendingError = None - - def smiWrite(self, name, value, idx): - # Run through states transition matrix, resolve new instance value - err, val = self.stateMatrix.get( - (self.clone(value), int(self)), (error.MibOperationError, None) - ) - debug.logger & debug.flagIns and debug.logger('RowStatus state resolution: %s, %s -> %s, %s' % (value, int(self), err, val)) - if val is None: - val = self - else: - val = self.clone(val) - if err is not None: - err = err( - msg='Exception at row state transition %s->%s' % (self, value), - idx=idx - ) - val.smiSetPendingError(err) - return val - - def smiCreate(self, name, value, idx): - return self.smiWrite(name, value, idx) - - def smiRaisePendingError(self): - if self.pendingError: - err, self.pendingError = self.pendingError, None - raise err - def smiSetPendingError(self, err): - self.pendingError = err - -class TimeStamp(TimeTicks, TextualConvention): pass - -class TimeInterval(Integer, TextualConvention): - subtypeSpec = Integer.subtypeSpec+constraint.ValueRangeConstraint(0, 2147483647L) - -class DateAndTime(TextualConvention, OctetString): - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(8, 11) - displayHint = "2d-1d-1d,1d:1d:1d.1d,1a1d:1d" - -class StorageType(Integer, TextualConvention): - subtypeSpec = Integer.subtypeSpec+constraint.SingleValueConstraint(1, 2, 3, 4, 5) - namedValues = namedval.NamedValues( - ('other', 1), ('volatile', 2), ('nonVolatile', 3), - ('permanent', 4), ('readOnly', 5) - ) - -class TDomain(ObjectIdentifier, TextualConvention): pass - -class TAddress(OctetString, TextualConvention): - subtypeSpec = OctetString.subtypeSpec+constraint.ValueSizeConstraint(1, 255) - -mibBuilder.exportSymbols( - 'SNMPv2-TC', TextualConvention=TextualConvention, DisplayString=DisplayString, - PhysAddress=PhysAddress, MacAddress=MacAddress, TruthValue=TruthValue, - TestAndIncr=TestAndIncr, AutonomousType=AutonomousType, - InstancePointer=InstancePointer, VariablePointer=VariablePointer, - RowPointer=RowPointer, RowStatus=RowStatus, TimeStamp=TimeStamp, - TimeInterval=TimeInterval, DateAndTime=DateAndTime, StorageType=StorageType, - TDomain=TDomain, TAddress=TAddress - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-TM.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-TM.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMPv2-TM.py 2006-10-01 19:30:45.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMPv2-TM.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -import types, string -from pyasn1.type import constraint - -OctetString, = mibBuilder.importSymbols('ASN1', 'OctetString') -( ModuleIdentity, MibIdentifier, ObjectIdentity, snmpModules, - snmpDomains, snmpProxys ) = mibBuilder.importSymbols( - 'SNMPv2-SMI', 'ModuleIdentity', 'MibIdentifier', 'ObjectIdentity', - 'snmpModules', 'snmpDomains', 'snmpProxys' - ) -TextualConvention, = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention') - -snmpv2tm = ModuleIdentity(snmpModules.name + (19,)).setRevisions(("2002-10-16 00:00",)) - -snmpUDPDomain = ObjectIdentity(snmpDomains.name + (1,)) - -class SnmpUDPAddress(TextualConvention, OctetString): - subtypeSpec = OctetString.subtypeSpec + constraint.ValueSizeConstraint(6, 6) - displayHint = "1d.1d.1d.1d/2d" - - def prettyIn(self, value): - if type(value) == types.TupleType: - # 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) - - # Socket address syntax coercion - def __getitem__(self, i): - value = ( - string.join(map(lambda x: str(ord(x)), self._value[:4]), '.'), - (ord(self._value[4:5])) << 8 | ord(self._value[5:6]) - ) - return value[i] - -snmpCLNSDomain = ObjectIdentity(snmpDomains.name + (2,)) -snmpCONSDomain = ObjectIdentity(snmpDomains.name + (3,)) - -class SnmpOSIAddress(TextualConvention, OctetString): - subtypeSpec = OctetString.subtypeSpec + constraint.ValueSizeConstraint(1, 85) - displayHint = "*1x:/1x:" - -snmpDDPDomain = ObjectIdentity(snmpDomains.name + (4,)) - -class SnmpNBPAddress(OctetString, TextualConvention): - subtypeSpec = OctetString.subtypeSpec + constraint.ValueSizeConstraint(3, 99) - -snmpIPXDomain = ObjectIdentity(snmpDomains.name + (5,)) - -class SnmpIPXAddress(TextualConvention, OctetString): - subtypeSpec = OctetString.subtypeSpec + constraint.ValueSizeConstraint(12, 12) - displayHint = "4x.1x:1x:1x:1x:1x:1x.2d" - -rfc1157Proxy = MibIdentifier(snmpProxys.name + (1,)) -rfc1157Domain = MibIdentifier(rfc1157Proxy.name + (1,)) - -# Module identity -mibBuilder.exportSymbols("SNMPv2-TM", PYSNMP_MODULE_ID=snmpv2tm) - -mibBuilder.exportSymbols( - 'SNMPv2-TM', snmpv2tm=snmpv2tm, snmpUDPDomain=snmpUDPDomain, - SnmpUDPAddress=SnmpUDPAddress, - snmpCLNSDomain=snmpCLNSDomain, snmpCONSDomain=snmpCONSDomain, - SnmpOSIAddress=SnmpOSIAddress, snmpDDPDomain=snmpDDPDomain, - SnmpNBPAddress=SnmpNBPAddress, snmpIPXDomain=snmpIPXDomain, - SnmpIPXAddress=SnmpIPXAddress, rfc1157Proxy=rfc1157Proxy, - rfc1157Domain=rfc1157Domain - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py 2006-11-16 17:30:42.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python SNMP-VIEW-BASED-ACM-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:34:21 2006, -# Python version (2, 4, 3, 'final', 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, SnmpSecurityLevel, SnmpSecurityModel, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpSecurityLevel", "SnmpSecurityModel") -( 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, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TestAndIncr") - -# Objects - -snmpVacmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 16)).setRevisions(("2002-10-16 00:00","1999-01-20 00:00","1997-11-20 00:00",)) -vacmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1)) -vacmContextTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 1)) -vacmContextEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 1, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmContextName")) -vacmContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32))).setMaxAccess("readonly") -vacmSecurityToGroupTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 2)) -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")) -vacmSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 1), SnmpSecurityModel().subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 2147483647L))).setMaxAccess("noaccess") -vacmSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -vacmGroupName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") -vacmSecurityToGroupStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -vacmSecurityToGroupStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") -vacmAccessTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 4)) -vacmAccessEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 4, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextPrefix"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessSecurityModel"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessSecurityLevel")) -vacmAccessContextPrefix = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32))).setMaxAccess("noaccess") -vacmAccessSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 2), SnmpSecurityModel()).setMaxAccess("noaccess") -vacmAccessSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 3), SnmpSecurityLevel()).setMaxAccess("noaccess") -vacmAccessContextMatch = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 4), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(2,1,)).subtype(namedValues=namedval.NamedValues(("exact", 1), ("prefix", 2), )).clone(1)).setMaxAccess("readcreate") -vacmAccessReadViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 5), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") -vacmAccessWriteViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 6), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") -vacmAccessNotifyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 7), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") -vacmAccessStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -vacmAccessStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 9), RowStatus()).setMaxAccess("readcreate") -vacmMIBViews = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1, 5)) -vacmViewSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 16, 1, 5, 1), TestAndIncr()).setMaxAccess("readwrite") -vacmViewTreeFamilyTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 5, 2)) -vacmViewTreeFamilyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyViewName"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilySubtree")) -vacmViewTreeFamilyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") -vacmViewTreeFamilySubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 2), ObjectIdentifier()).setMaxAccess("noaccess") -vacmViewTreeFamilyMask = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 3), OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 16)).clone('')).setMaxAccess("readcreate") -vacmViewTreeFamilyType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 4), Integer().subtype(subtypeSpec=constraint.SingleValueConstraint(1,2,)).subtype(namedValues=namedval.NamedValues(("included", 1), ("excluded", 2), )).clone(1)).setMaxAccess("readcreate") -vacmViewTreeFamilyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 5), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") -vacmViewTreeFamilyStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 6), RowStatus()).setMaxAccess("readcreate") -vacmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2)) -vacmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 1)) -vacmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 2)) - -# Augmentions - -# 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"), ) - -# Exports - -# Module identity -mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", PYSNMP_MODULE_ID=snmpVacmMIB) - -# Objects -mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", snmpVacmMIB=snmpVacmMIB, vacmMIBObjects=vacmMIBObjects, vacmContextTable=vacmContextTable, vacmContextEntry=vacmContextEntry, vacmContextName=vacmContextName, vacmSecurityToGroupTable=vacmSecurityToGroupTable, vacmSecurityToGroupEntry=vacmSecurityToGroupEntry, vacmSecurityModel=vacmSecurityModel, vacmSecurityName=vacmSecurityName, vacmGroupName=vacmGroupName, vacmSecurityToGroupStorageType=vacmSecurityToGroupStorageType, vacmSecurityToGroupStatus=vacmSecurityToGroupStatus, vacmAccessTable=vacmAccessTable, vacmAccessEntry=vacmAccessEntry, vacmAccessContextPrefix=vacmAccessContextPrefix, vacmAccessSecurityModel=vacmAccessSecurityModel, vacmAccessSecurityLevel=vacmAccessSecurityLevel, vacmAccessContextMatch=vacmAccessContextMatch, vacmAccessReadViewName=vacmAccessReadViewName, vacmAccessWriteViewName=vacmAccessWriteViewName, vacmAccessNotifyViewName=vacmAccessNotifyViewName, vacmAccessStorageType=vacmAccessStorageType, vacmAccessStatus=vacmAccessStatus, vacmMIBViews=vacmMIBViews, vacmViewSpinLock=vacmViewSpinLock, vacmViewTreeFamilyTable=vacmViewTreeFamilyTable, vacmViewTreeFamilyEntry=vacmViewTreeFamilyEntry, vacmViewTreeFamilyViewName=vacmViewTreeFamilyViewName, vacmViewTreeFamilySubtree=vacmViewTreeFamilySubtree, vacmViewTreeFamilyMask=vacmViewTreeFamilyMask, vacmViewTreeFamilyType=vacmViewTreeFamilyType, vacmViewTreeFamilyStorageType=vacmViewTreeFamilyStorageType, vacmViewTreeFamilyStatus=vacmViewTreeFamilyStatus, vacmMIBConformance=vacmMIBConformance, vacmMIBCompliances=vacmMIBCompliances, vacmMIBGroups=vacmMIBGroups) - -# Groups -mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmBasicGroup=vacmBasicGroup) diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/TRANSPORT-ADDRESS-MIB.py python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/TRANSPORT-ADDRESS-MIB.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/mibs/TRANSPORT-ADDRESS-MIB.py 2007-02-07 13:01:32.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/mibs/TRANSPORT-ADDRESS-MIB.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,96 +0,0 @@ -# PySNMP SMI module. Autogenerated from smidump -f python TRANSPORT-ADDRESS-MIB -# by libsmi2pysnmp-0.0.7-alpha at Thu Nov 16 18:57:07 2006, -# Python version (2, 4, 3, 'final', 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") -( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, TimeTicks, mib_2, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "TimeTicks", "mib-2") -( TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention") - -# Types - -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 - pass - -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 - pass - -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,) - 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 - - -# Objects - -transportAddressMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 100)).setRevisions(("2002-11-01 00:00",)) -transportDomains = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1)) -transportDomainUdpIpv4 = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 1)) -transportDomainUdpIpv6 = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 2)) -transportDomainUdpIpv4z = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 3)) -transportDomainUdpIpv6z = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 4)) -transportDomainTcpIpv4 = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 5)) -transportDomainTcpIpv6 = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 6)) -transportDomainTcpIpv4z = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 7)) -transportDomainTcpIpv6z = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 8)) -transportDomainSctpIpv4 = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 9)) -transportDomainSctpIpv6 = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 10)) -transportDomainSctpIpv4z = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 11)) -transportDomainSctpIpv6z = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 12)) -transportDomainLocal = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 13)) -transportDomainUdpDns = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 14)) -transportDomainTcpDns = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 15)) -transportDomainSctpDns = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1, 16)) - -# Augmentions - -# Exports - -# Module identity -mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", PYSNMP_MODULE_ID=transportAddressMIB) - -# Types -mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", TransportAddress=TransportAddress, TransportAddressDns=TransportAddressDns, TransportAddressIPv4=TransportAddressIPv4, TransportAddressIPv4z=TransportAddressIPv4z, TransportAddressIPv6=TransportAddressIPv6, TransportAddressIPv6z=TransportAddressIPv6z, TransportAddressLocal=TransportAddressLocal, TransportAddressType=TransportAddressType, TransportDomain=TransportDomain) - -# Objects -mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", transportAddressMIB=transportAddressMIB, transportDomains=transportDomains, transportDomainUdpIpv4=transportDomainUdpIpv4, transportDomainUdpIpv6=transportDomainUdpIpv6, transportDomainUdpIpv4z=transportDomainUdpIpv4z, transportDomainUdpIpv6z=transportDomainUdpIpv6z, transportDomainTcpIpv4=transportDomainTcpIpv4, transportDomainTcpIpv6=transportDomainTcpIpv6, transportDomainTcpIpv4z=transportDomainTcpIpv4z, transportDomainTcpIpv6z=transportDomainTcpIpv6z, transportDomainSctpIpv4=transportDomainSctpIpv4, transportDomainSctpIpv6=transportDomainSctpIpv6, transportDomainSctpIpv4z=transportDomainSctpIpv4z, transportDomainSctpIpv6z=transportDomainSctpIpv6z, transportDomainLocal=transportDomainLocal, transportDomainUdpDns=transportDomainUdpDns, transportDomainTcpDns=transportDomainTcpDns, transportDomainSctpDns=transportDomainSctpDns) - diff -Nru python-pysnmp4-4.1.9a/pysnmp/v4/smi/view.py python-pysnmp4-4.2.2/pysnmp/v4/smi/view.py --- python-pysnmp4-4.1.9a/pysnmp/v4/smi/view.py 2007-01-09 19:14:30.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp/v4/smi/view.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,307 +0,0 @@ -# MIB modules management -from types import ClassType, InstanceType, TupleType -from pysnmp.smi.indices import OrderedDict, OidOrderedDict -from pysnmp.smi import error -from pysnmp import debug - -__all__ = [ 'MibViewController' ] - -class MibViewController: - def __init__(self, mibBuilder): - self.mibBuilder = mibBuilder - self.lastBuildId = -1 - - # Indexing part - - def __indexMib(self): - if self.lastBuildId == self.mibBuilder.lastBuildId: - return - - debug.logger & debug.flagMIB and debug.logger('__indexMib: re-indexing MIB view') - - MibScalarInstance, = self.mibBuilder.importSymbols( - 'SNMPv2-SMI', 'MibScalarInstance' - ) - - # - # Create indices - # - - # Module name -> module-scope indices - self.__mibSymbolsIdx = OrderedDict() - - # Oid <-> label indices - - # This is potentionally ambiguous mapping. Sort modules in - # ascending age for resolution - def __sortFun(x, y, s=self.mibBuilder.mibSymbols): - m1 = s[x].get("PYSNMP_MODULE_ID") - m2 = s[y].get("PYSNMP_MODULE_ID") - 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) - - modNames = self.mibBuilder.mibSymbols.keys() - modNames.sort(__sortFun) - - # Index modules names - for modName in [ '' ] + modNames: - # Modules index - self.__mibSymbolsIdx[modName] = mibMod = { - 'oidToLabelIdx': OidOrderedDict(), - 'labelToOidIdx': {}, - 'varToNameIdx': {}, - 'typeToModIdx': OrderedDict(), - 'oidToModIdx': {} - } - - if not modName: - globMibMod = mibMod - continue - - # Types & MIB vars indices - 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 mibMod['typeToModIdx'].has_key(n): - raise error.SmiError( - 'Duplicate SMI type %s::%s, has %s' % \ - (modName, n, mibMod['typeToModIdx'][n]) - ) - globMibMod['typeToModIdx'][n] = modName - mibMod['typeToModIdx'][n] = modName - elif type(v) == InstanceType: - if isinstance(v, MibScalarInstance): - continue - if mibMod['varToNameIdx'].has_key(n): - raise error.SmiError( - 'Duplicate MIB variable %s::%s has %s' % \ - (modName, n, mibMod['varToNameIdx'][n]) - ) - globMibMod['varToNameIdx'][n] = v.name - mibMod['varToNameIdx'][n] = v.name - # Potentionally ambiguous mapping ahead - globMibMod['oidToModIdx'][v.name] = modName - mibMod['oidToModIdx'][v.name] = modName - globMibMod['oidToLabelIdx'][v.name] = (n, ) - mibMod['oidToLabelIdx'][v.name] = (n, ) - else: - raise error.SmiError( - 'Unexpected object %s::%s' % (modName, n) - ) - - # Build oid->long-label index - oidToLabelIdx = self.__mibSymbolsIdx['']['oidToLabelIdx'] - labelToOidIdx = self.__mibSymbolsIdx['']['labelToOidIdx'] - if oidToLabelIdx: - prevOid = oidToLabelIdx.keys()[0] - else: - prevOid = () - baseLabel = () - for key in oidToLabelIdx.keys(): - keydiff = len(key) - len(prevOid) - if keydiff > 0: - baseLabel = oidToLabelIdx[prevOid] - if keydiff > 1: - baseLabel = baseLabel + key[-keydiff:-1] - if keydiff < 0: - keyLen = len(key) - i = keyLen-1 - while i: - baseLabel = oidToLabelIdx.get(key[:i]) - if baseLabel: - if i != keyLen-1: - baseLabel = baseLabel + key[i:-1] - break - i = i - 1 - # Build oid->long-label index - oidToLabelIdx[key] = baseLabel + oidToLabelIdx[key] - # Build label->oid index - labelToOidIdx[oidToLabelIdx[key]] = key - prevOid = key - - # Build module-scope oid->long-label index - for mibMod in self.__mibSymbolsIdx.values(): - for oid in mibMod['oidToLabelIdx'].keys(): - mibMod['oidToLabelIdx'][oid] = oidToLabelIdx[oid] - mibMod['labelToOidIdx'][oidToLabelIdx[oid]] = oid - - self.lastBuildId = self.mibBuilder.lastBuildId - - # Module management - - def getFirstModuleName(self): - self.__indexMib() - modNames = self.__mibSymbolsIdx.keys() - if modNames: - return modNames[0] - raise error.SmiError('No modules loaded at %s' % self) - - def getNextModuleName(self, modName): - self.__indexMib() - try: - return self.__mibSymbolsIdx.nextKey(modName) - except KeyError: - raise error.SmiError( - 'No module next to %s at %s' % (modName, self) - ) - - # MIB tree node management - - def __getOidLabel(self, nodeName, oidToLabelIdx, labelToOidIdx): - """getOidLabel(nodeName) -> (oid, label, suffix)""" - if not nodeName: - return nodeName, nodeName, () - oid = labelToOidIdx.get(nodeName) - if oid: - return oid, nodeName, () - label = oidToLabelIdx.get(nodeName) - if label: - return nodeName, label, () - if len(nodeName) < 2: - return nodeName, nodeName, () - oid, label, suffix = self.__getOidLabel( - nodeName[:-1], oidToLabelIdx, labelToOidIdx - ) - suffix = suffix + nodeName[-1:] - resLabel = label + suffix - resOid = labelToOidIdx.get(resLabel) - if resOid: - return resOid, resLabel, () - resOid = oid + suffix - resLabel = oidToLabelIdx.get(resOid) - if resLabel: - return resOid, resLabel, () - return oid, label, suffix - - def getNodeNameByOid(self, nodeName, modName=''): - self.__indexMib() - mibMod = self.__mibSymbolsIdx.get(modName) - if mibMod is None: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - oid, label, suffix = self.__getOidLabel( - nodeName, mibMod['oidToLabelIdx'], mibMod['labelToOidIdx'] - ) - if oid == label: - raise error.NoSuchObjectError( - str='Can\'t resolve node name %s::%s at %s' % - (modName, nodeName, self) - ) - debug.logger & debug.flagMIB and debug.logger('getNodeNameByOid: resolved %s:%s -> %s' % (modName, nodeName, label + suffix)) - return oid, label, suffix - - def getNodeNameByDesc(self, nodeName, modName=''): - self.__indexMib() - mibMod = self.__mibSymbolsIdx.get(modName) - if mibMod is None: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - oid = mibMod['varToNameIdx'].get(nodeName) - if oid is None: - raise error.NoSuchObjectError( - str='No such symbol %s::%s at %s' % (modName, nodeName, self) - ) - debug.logger & debug.flagMIB and debug.logger('getNodeNameByDesc: resolved %s:%s -> %s' % (modName, nodeName, oid)) - return self.getNodeNameByOid(oid, modName) - - def getNodeName(self, nodeName, modName=''): - # nodeName may be either an absolute OID/label or a - # ( MIB-symbol, su, ff, ix) - try: - # First try nodeName as an OID/label - return self.getNodeNameByOid(nodeName, modName) - except error.NoSuchObjectError: - # ...on failure, try as MIB symbol - oid, label, suffix = self.getNodeNameByDesc( - nodeName[0], modName - ) - # ...with trailing suffix - return self.getNodeNameByOid( - oid + suffix + nodeName[1:], modName - ) - - def getFirstNodeName(self, modName=''): - self.__indexMib() - mibMod = self.__mibSymbolsIdx.get(modName) - if mibMod is None: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - if not mibMod['oidToLabelIdx']: - raise error.NoSuchObjectError( - str='No variables at MIB module %s at %s' % (modName, self) - ) - oid, label = mibMod['oidToLabelIdx'].items()[0] - return oid, label, () - - def getNextNodeName(self, nodeName, modName=''): - oid, label, suffix = self.getNodeName(nodeName, modName) - try: - return self.getNodeName( - self.__mibSymbolsIdx[modName]['oidToLabelIdx'].nextKey(oid) + suffix, modName - ) - except KeyError: - raise error.NoSuchObjectError( - str='No name next to %s::%s at %s' % (modName, nodeName, self) - ) - - def getParentNodeName(self, nodeName, modName=''): - oid, label, suffix = self.getNodeName(nodeName, modName) - if len(oid) < 2: - raise error.NoSuchObjectError( - str='No parent name for %s::%s at %s' % - (modName, nodeName, self) - ) - return oid[:-1], label[:-1], oid[-1:] + suffix - - def getNodeLocation(self, nodeName, modName=''): - oid, label, suffix = self.getNodeName(nodeName, modName) - return self.__mibSymbolsIdx['']['oidToModIdx'][oid], label[-1], suffix - - # MIB type management - - def getTypeName(self, typeName, modName=''): - self.__indexMib() - mibMod = self.__mibSymbolsIdx.get(modName) - if mibMod is None: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - m = mibMod['typeToModIdx'].get(typeName) - if m is None: - raise error.NoSuchObjectError( - str='No such type %s::%s at %s' % (modName, typeName, self) - ) - return m, typeName - - def getFirstTypeName(self, modName=''): - self.__indexMib() - mibMod = self.__mibSymbolsIdx.get(modName) - if mibMod is None: - raise error.SmiError( - 'No module %s at %s' % (modName, self) - ) - if not mibMod['typeToModIdx']: - raise error.NoSuchObjectError( - str='No types at MIB module %s at %s' % (modName, self) - ) - t = mibMod['typeToModIdx'].keys()[0] - return mibMod['typeToModIdx'][t], t - - def getNextType(self, typeName, modName=''): - m, t = self.getTypeName(typeName, modName) - try: - return self.__mibSymbolsIdx[m]['typeToModIdx'].nextKey(t) - except KeyError: - raise error.NoSuchObjectError( - str='No type next to %s::%s at %s' % (modName, typeName, self) - ) diff -Nru python-pysnmp4-4.1.9a/pysnmp.egg-info/dependency_links.txt python-pysnmp4-4.2.2/pysnmp.egg-info/dependency_links.txt --- python-pysnmp4-4.1.9a/pysnmp.egg-info/dependency_links.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp.egg-info/dependency_links.txt 2012-04-21 09:48:06.000000000 +0000 @@ -0,0 +1 @@ + diff -Nru python-pysnmp4-4.1.9a/pysnmp.egg-info/PKG-INFO python-pysnmp4-4.2.2/pysnmp.egg-info/PKG-INFO --- python-pysnmp4-4.1.9a/pysnmp.egg-info/PKG-INFO 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp.egg-info/PKG-INFO 2012-04-21 09:48:06.000000000 +0000 @@ -0,0 +1,23 @@ +Metadata-Version: 1.0 +Name: pysnmp +Version: 4.2.2 +Summary: SNMP framework +Home-page: http://sourceforge.net/projects/pysnmp/ +Author: Ilya Etingof +Author-email: ilya@glas.net +License: BSD +Description: UNKNOWN +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: Telecommunications Industry +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Security +Classifier: Topic :: Communications +Classifier: Topic :: System :: Monitoring +Classifier: Topic :: System :: Networking :: Monitoring +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: License :: OSI Approved :: BSD License diff -Nru python-pysnmp4-4.1.9a/pysnmp.egg-info/requires.txt python-pysnmp4-4.2.2/pysnmp.egg-info/requires.txt --- python-pysnmp4-4.1.9a/pysnmp.egg-info/requires.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp.egg-info/requires.txt 2012-04-21 09:48:06.000000000 +0000 @@ -0,0 +1,2 @@ +pyasn1>=0.1.2 +pycrypto>=2.4.1 \ No newline at end of file diff -Nru python-pysnmp4-4.1.9a/pysnmp.egg-info/SOURCES.txt python-pysnmp4-4.2.2/pysnmp.egg-info/SOURCES.txt --- python-pysnmp4-4.1.9a/pysnmp.egg-info/SOURCES.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp.egg-info/SOURCES.txt 2012-04-21 09:48:07.000000000 +0000 @@ -0,0 +1,180 @@ +CHANGES +LICENSE +MANIFEST.in +README +THANKS +TODO +setup.cfg +setup.py +docs/pysnmp-arch.gif +docs/pysnmp-tutorial.html +docs/mibs/PYSNMP-COMMUNITY-MIB.txt +docs/mibs/PYSNMP-MIB.txt +docs/mibs/PYSNMP-PROXY-MIB.txt +docs/mibs/PYSNMP-USM-MIB.txt +examples/smi/backend.py +examples/smi/instrum.py +examples/smi/view.py +examples/v1arch/agent/cmdrsp.py +examples/v1arch/agent/ntforg.py +examples/v1arch/manager/bulkgen.py +examples/v1arch/manager/getgen.py +examples/v1arch/manager/nextgen.py +examples/v1arch/manager/ntfrcv.py +examples/v1arch/manager/setgen.py +examples/v3arch/agent/cmdrsp.py +examples/v3arch/agent/ntforg.py +examples/v3arch/manager/bulkgen.py +examples/v3arch/manager/getgen.py +examples/v3arch/manager/nextgen.py +examples/v3arch/manager/ntfrcv.py +examples/v3arch/manager/setgen.py +examples/v3arch/oneliner/agent/ntforg.py +examples/v3arch/oneliner/manager/bulkgen.py +examples/v3arch/oneliner/manager/getgen.py +examples/v3arch/oneliner/manager/nextgen.py +examples/v3arch/oneliner/manager/setgen.py +examples/v3arch/oneliner/manager/async/nextgen.py +examples/v3arch/oneliner/manager/withmib/nextgen.py +examples/v3arch/oneliner/manager/withmib/setgen.py +examples/v3arch/proxy/cmdproxy.py +examples/v3arch/twisted/agent/cmdrsp.py +examples/v3arch/twisted/agent/ntforg.py +examples/v3arch/twisted/manager/bulkgen.py +examples/v3arch/twisted/manager/getgen.py +examples/v3arch/twisted/manager/nextgen.py +examples/v3arch/twisted/manager/ntfrcv.py +examples/v3arch/twisted/manager/setgen.py +pysnmp/__init__.py +pysnmp/cache.py +pysnmp/debug.py +pysnmp/error.py +pysnmp/nextid.py +pysnmp.egg-info/PKG-INFO +pysnmp.egg-info/SOURCES.txt +pysnmp.egg-info/dependency_links.txt +pysnmp.egg-info/requires.txt +pysnmp.egg-info/top_level.txt +pysnmp.egg-info/zip-safe +pysnmp/carrier/__init__.py +pysnmp/carrier/base.py +pysnmp/carrier/error.py +pysnmp/carrier/asynsock/__init__.py +pysnmp/carrier/asynsock/base.py +pysnmp/carrier/asynsock/dispatch.py +pysnmp/carrier/asynsock/dgram/__init__.py +pysnmp/carrier/asynsock/dgram/base.py +pysnmp/carrier/asynsock/dgram/udp.py +pysnmp/carrier/asynsock/dgram/udp6.py +pysnmp/carrier/asynsock/dgram/unix.py +pysnmp/carrier/twisted/__init__.py +pysnmp/carrier/twisted/base.py +pysnmp/carrier/twisted/dispatch.py +pysnmp/carrier/twisted/dgram/__init__.py +pysnmp/carrier/twisted/dgram/base.py +pysnmp/carrier/twisted/dgram/udp.py +pysnmp/carrier/twisted/dgram/unix.py +pysnmp/entity/__init__.py +pysnmp/entity/config.py +pysnmp/entity/engine.py +pysnmp/entity/rfc3413/__init__.py +pysnmp/entity/rfc3413/cmdgen.py +pysnmp/entity/rfc3413/cmdrsp.py +pysnmp/entity/rfc3413/config.py +pysnmp/entity/rfc3413/context.py +pysnmp/entity/rfc3413/mibvar.py +pysnmp/entity/rfc3413/ntforg.py +pysnmp/entity/rfc3413/ntfrcv.py +pysnmp/entity/rfc3413/oneliner/__init__.py +pysnmp/entity/rfc3413/oneliner/cmdgen.py +pysnmp/entity/rfc3413/oneliner/ntforg.py +pysnmp/entity/rfc3413/twisted/__init__.py +pysnmp/entity/rfc3413/twisted/cmdgen.py +pysnmp/entity/rfc3413/twisted/ntforg.py +pysnmp/proto/__init__.py +pysnmp/proto/cache.py +pysnmp/proto/errind.py +pysnmp/proto/error.py +pysnmp/proto/rfc1155.py +pysnmp/proto/rfc1157.py +pysnmp/proto/rfc1902.py +pysnmp/proto/rfc1905.py +pysnmp/proto/rfc3411.py +pysnmp/proto/rfc3412.py +pysnmp/proto/acmod/__init__.py +pysnmp/proto/acmod/rfc3415.py +pysnmp/proto/acmod/void.py +pysnmp/proto/api/__init__.py +pysnmp/proto/api/v1.py +pysnmp/proto/api/v2c.py +pysnmp/proto/api/verdec.py +pysnmp/proto/mpmod/__init__.py +pysnmp/proto/mpmod/base.py +pysnmp/proto/mpmod/cache.py +pysnmp/proto/mpmod/rfc2576.py +pysnmp/proto/mpmod/rfc3412.py +pysnmp/proto/proxy/__init__.py +pysnmp/proto/proxy/rfc2576.py +pysnmp/proto/secmod/__init__.py +pysnmp/proto/secmod/base.py +pysnmp/proto/secmod/cache.py +pysnmp/proto/secmod/rfc2576.py +pysnmp/proto/secmod/eso/__init__.py +pysnmp/proto/secmod/eso/priv/__init__.py +pysnmp/proto/secmod/eso/priv/aes192.py +pysnmp/proto/secmod/eso/priv/aes256.py +pysnmp/proto/secmod/eso/priv/des3.py +pysnmp/proto/secmod/rfc3414/__init__.py +pysnmp/proto/secmod/rfc3414/localkey.py +pysnmp/proto/secmod/rfc3414/service.py +pysnmp/proto/secmod/rfc3414/auth/__init__.py +pysnmp/proto/secmod/rfc3414/auth/base.py +pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py +pysnmp/proto/secmod/rfc3414/auth/hmacsha.py +pysnmp/proto/secmod/rfc3414/auth/noauth.py +pysnmp/proto/secmod/rfc3414/priv/__init__.py +pysnmp/proto/secmod/rfc3414/priv/base.py +pysnmp/proto/secmod/rfc3414/priv/des.py +pysnmp/proto/secmod/rfc3414/priv/nopriv.py +pysnmp/proto/secmod/rfc3826/__init__.py +pysnmp/proto/secmod/rfc3826/priv/__init__.py +pysnmp/proto/secmod/rfc3826/priv/aes.py +pysnmp/smi/__init__.py +pysnmp/smi/builder.py +pysnmp/smi/error.py +pysnmp/smi/exval.py +pysnmp/smi/indices.py +pysnmp/smi/instrum.py +pysnmp/smi/view.py +pysnmp/smi/mibs/ASN1-ENUMERATION.py +pysnmp/smi/mibs/ASN1-REFINEMENT.py +pysnmp/smi/mibs/ASN1.py +pysnmp/smi/mibs/PYSNMP-MIB.py +pysnmp/smi/mibs/PYSNMP-USM-MIB.py +pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py +pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py +pysnmp/smi/mibs/SNMP-MPD-MIB.py +pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py +pysnmp/smi/mibs/SNMP-PROXY-MIB.py +pysnmp/smi/mibs/SNMP-TARGET-MIB.py +pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py +pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py +pysnmp/smi/mibs/SNMP-USM-AES-MIB.py +pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py +pysnmp/smi/mibs/SNMPv2-CONF.py +pysnmp/smi/mibs/SNMPv2-MIB.py +pysnmp/smi/mibs/SNMPv2-SMI.py +pysnmp/smi/mibs/SNMPv2-TC.py +pysnmp/smi/mibs/SNMPv2-TM.py +pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py +pysnmp/smi/mibs/__init__.py +pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py +pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py +pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py +pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py +pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py +pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py +pysnmp/smi/mibs/instances/__SNMPv2-MIB.py +pysnmp/smi/mibs/instances/__init__.py +tools/build-pysnmp-mib +tools/libsmi2pysnmp \ No newline at end of file diff -Nru python-pysnmp4-4.1.9a/pysnmp.egg-info/top_level.txt python-pysnmp4-4.2.2/pysnmp.egg-info/top_level.txt --- python-pysnmp4-4.1.9a/pysnmp.egg-info/top_level.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp.egg-info/top_level.txt 2012-04-21 09:48:06.000000000 +0000 @@ -0,0 +1 @@ +pysnmp diff -Nru python-pysnmp4-4.1.9a/pysnmp.egg-info/zip-safe python-pysnmp4-4.2.2/pysnmp.egg-info/zip-safe --- python-pysnmp4-4.1.9a/pysnmp.egg-info/zip-safe 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/pysnmp.egg-info/zip-safe 2010-12-13 16:29:34.000000000 +0000 @@ -0,0 +1 @@ + diff -Nru python-pysnmp4-4.1.9a/README python-pysnmp4-4.2.2/README --- python-pysnmp4-4.1.9a/README 2007-07-09 13:39:47.000000000 +0000 +++ python-pysnmp4-4.2.2/README 2012-04-13 19:36:18.000000000 +0000 @@ -2,8 +2,8 @@ PYTHON SNMP FRAMEWORK --------------------- -This is an alpha-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! @@ -14,10 +14,14 @@ * SMI framework for resolving MIB information and implementing SMI Managed Objects * Complete SNMP entity implementation +* USM Extended Security Options support (3DES, 192/256-bit AES encryption) * Extensible network transports framework (UDP and UNIX domain implemented) * Asynchronous socket-based IO API support -* 100% Python, works with Python 1.5 and later -* MT-safe +* Twisted (http://twistedmatrix.com) integration +* IPv6 transport support +* Python eggs and py2exe friendly +* 100% Python, works with Python 2.4 though 3.3 (alpha 2) +* MT-safe (only if run locally to a thread) Features, specific to SNMPv3 model include: @@ -35,21 +39,13 @@ * Much slower than C implementations. Some optimization still possible. * No pure-Python MIB compiler. But there's a workaround, read on. -PRECAUTIONS ------------ - -The 4.x revision of PySNMP brings an alpha-quality code, unstable APIs and -appears to run rather slow. Also, the 4.x APIs are quite incompatible -with their 2.x/3.x counterparts as of this early release. Chances are that, -at least, high-level compatibility interfaces would appear in future stable -releases. - 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 --------- @@ -72,18 +68,21 @@ targetAddr = cmdgen.UdpTransportTarget(('localhost', 161)) errorIndication, errorStatus, \ - errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( - userData, targetAddr, (('SNMPv2-MIB', 'sysDescr'), 0) + errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( + userData, targetAddr, (('SNMPv2-MIB', 'sysDescr'), 0) ) if errorIndication: # SNMP engine errors print errorIndication else: if errorStatus: # SNMP agent errors - print '%s at %s\n' % (errorStatus, varBinds[int(errorIndex)-1]) + print '%s at %s\n' % ( + errorStatus.prettyPrint(), + errorIndex and varBinds[int(errorIndex)-1] or '?') + ) else: - for varBind in varBinds: # SNMP agent values - print '%s = %s' % varBind + for oid, val in varBinds: # SNMP agent values + print '%s = %s' % (oid.prettyPrint(), val.prettyPrint()) 8X---------------- cut here -------------------- @@ -100,12 +99,11 @@ While MIB parser/codegenerator has not been implemented in PySNMP, the smidump tool of libsmi library [6] could be used for automatic convertion -of MIB text files into Python code. The code been generated relies upon -PySNMP SMI library. +of MIB text files into Python code. The produced code relies on PySNMP +SMI library. In order to convert MIB text files into pysnmp.smi-compliant Python source, -please, use build-pysnmp-mib utility as shipped along with PySNMP -distribution. +please, use build-pysnmp-mib utility as shipped with PySNMP distribution. A large set of pre-compiled MIB files is shipped along the pysnmp-mibs package.[2] @@ -150,6 +148,8 @@ [6] libsmi homepage http://www.ibr.cs.tu-bs.de/projects/libsmi/ + Use libsmi version > 0.4.5, possibly from libsmi SVN: + svn checkout http://www.ibr.cs.tu-bs.de/svn/libsmi [7] PySNMP mailing list archives: http://sourceforge.net/mail/?group_id=14735 @@ -157,8 +157,8 @@ [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 -Nru python-pysnmp4-4.1.9a/setup.cfg python-pysnmp4-4.2.2/setup.cfg --- python-pysnmp4-4.1.9a/setup.cfg 1970-01-01 00:00:00.000000000 +0000 +++ python-pysnmp4-4.2.2/setup.cfg 2012-04-21 09:48:08.000000000 +0000 @@ -0,0 +1,5 @@ +[egg_info] +tag_build = +tag_date = 0 +tag_svn_revision = 0 + diff -Nru python-pysnmp4-4.1.9a/setup.py python-pysnmp4-4.2.2/setup.py --- python-pysnmp4-4.1.9a/setup.py 2007-08-15 10:02:37.000000000 +0000 +++ python-pysnmp4-4.2.2/setup.py 2012-04-18 19:30:15.000000000 +0000 @@ -1,35 +1,95 @@ #!/usr/bin/env python -from distutils.core import setup +import sys -setup(name="pysnmp", - version="4.1.9a", - description="SNMP framework for Python", - author="Ilya Etingof", - author_email="ilya@glas.net ", - url="http://sourceforge.net/projects/pysnmp/", - packages = [ 'pysnmp', - 'pysnmp.v4', - 'pysnmp.v4.smi', - 'pysnmp.v4.smi.mibs', - 'pysnmp.v4.smi.mibs.instances', - 'pysnmp.v4.carrier', - 'pysnmp.v4.carrier.asynsock', - 'pysnmp.v4.carrier.asynsock.dgram', - 'pysnmp.v4.entity', - 'pysnmp.v4.entity.rfc3413', - 'pysnmp.v4.entity.rfc3413.oneliner', - 'pysnmp.v4.proto', - 'pysnmp.v4.proto.mpmod', - 'pysnmp.v4.proto.secmod', - 'pysnmp.v4.proto.secmod.rfc3414', - 'pysnmp.v4.proto.secmod.rfc3414.auth', - 'pysnmp.v4.proto.secmod.rfc3414.priv', - 'pysnmp.v4.proto.secmod.rfc3826', - 'pysnmp.v4.proto.secmod.rfc3826.priv', - 'pysnmp.v4.proto.acmod', - 'pysnmp.v4.proto.proxy', - 'pysnmp.v4.proto.api' ], - scripts = [ 'tools/libsmi2pysnmp', - 'tools/build-pysnmp-mib' ], - license="BSD" - ) +def howto_install_setuptools(): + 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.1.2' ], + 'zip_safe': True + } + if sys.platform.lower()[:3] != 'win': + params['install_requires'].append('pycrypto>=2.4.1') + +except ImportError: + for arg in sys.argv: + if arg.find('egg') != -1: + howto_install_setuptools() + sys.exit(1) + from distutils.core import setup + params = {} + if sys.version_info[:2] > (2, 4): + params['requires'] = [ 'pyasn1(>=0.1.2)' ] + if sys.platform.lower()[:3] != 'win': + params['requires'].append('pycrypto(>=2.4.1)') + +if sys.platform.lower()[:3] == 'win': + try: + import Crypto + except ImportError: + sys.stderr.write("""WARNING! WARNING! WARNING! +PyCrypto binaries are required for SNMPv3 encryption to work. +You may wish to grab them from http://www.voidspace.org.uk/python/modules.shtml +and install into your system. +""") + +params.update( { + 'name': 'pysnmp', + 'version': '4.2.2', + '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', + 'pysnmp.smi.mibs', + 'pysnmp.smi.mibs.instances', + 'pysnmp.carrier', + 'pysnmp.carrier.asynsock', + 'pysnmp.carrier.asynsock.dgram', + 'pysnmp.carrier.twisted', + 'pysnmp.carrier.twisted.dgram', + 'pysnmp.entity', + 'pysnmp.entity.rfc3413', + 'pysnmp.entity.rfc3413.oneliner', + 'pysnmp.entity.rfc3413.twisted', + 'pysnmp.proto', + 'pysnmp.proto.mpmod', + 'pysnmp.proto.secmod', + 'pysnmp.proto.secmod.rfc3414', + 'pysnmp.proto.secmod.rfc3414.auth', + 'pysnmp.proto.secmod.rfc3414.priv', + 'pysnmp.proto.secmod.rfc3826', + 'pysnmp.proto.secmod.rfc3826.priv', + 'pysnmp.proto.secmod.eso', + 'pysnmp.proto.secmod.eso.priv', + 'pysnmp.proto.acmod', + 'pysnmp.proto.proxy', + 'pysnmp.proto.api' ], + 'scripts': [ 'tools/libsmi2pysnmp', 'tools/build-pysnmp-mib' ] + } ) + +setup(**params) diff -Nru python-pysnmp4-4.1.9a/THANKS python-pysnmp4-4.2.2/THANKS --- python-pysnmp4-4.1.9a/THANKS 2007-09-03 07:08:50.000000000 +0000 +++ python-pysnmp4-4.2.2/THANKS 2010-11-12 23:23:02.000000000 +0000 @@ -22,6 +22,7 @@ Randy Couey Brian Kyckelhahn Mark M Evans +Filippo Giunchedi at Truelite Srl Thanks to Python Software Foundation for granting financial support for the project. diff -Nru python-pysnmp4-4.1.9a/TODO python-pysnmp4-4.2.2/TODO --- python-pysnmp4-4.1.9a/TODO 2007-08-14 12:37:27.000000000 +0000 +++ python-pysnmp4-4.2.2/TODO 2011-03-17 18:07:02.000000000 +0000 @@ -22,25 +22,16 @@ * Disallow SNMP access to USM objects -* Make sure objects shutdown methods work alright - * Maybe MibInstrumentationController should be async what implies callback function interface. * Re-work ACL to get rid of linear search there -* Implement SNMP proxy example & app - -* Check for memory leaks esp. on failed requests - * Implement partial context name match at isAccessAllowed() * Sort out whether pyasn1 objects should probably have either clone() or subtype() methods. -* Convert symbolic constants (keys, SNMP errors) into singular, hashable - objects for performance and typing reliablity - * Implement by-transportTag search at secmod/rfc2576 * Review PDU components coercion code at proxy/rfc2576 @@ -53,3 +44,8 @@ * re-design something to get rid of an ugly hack coercing MIB values into SNMP message header as it has incompatible constraints set + +* Implement OID prefix to MIB module mapping then dynamic MIB modules + loading on OID to MIB symbol resolution + +* Implement TCP transport support diff -Nru python-pysnmp4-4.1.9a/tools/build-pysnmp-mib python-pysnmp4-4.2.2/tools/build-pysnmp-mib --- python-pysnmp4-4.1.9a/tools/build-pysnmp-mib 2006-04-05 16:30:56.000000000 +0000 +++ python-pysnmp4-4.2.2/tools/build-pysnmp-mib 2010-11-29 09:49:18.000000000 +0000 @@ -1,15 +1,16 @@ -#!/bin/bash +#!/bin/sh # # Convert MIB text into PySNMP-compilant MIB/managed objects module. # See http://pysnmp.sf.net for more information. # -libsmi2pysnmp=libsmi2pysnmp # part of pysnmp distro +basedir=$(dirname "$0") +libsmi2pysnmp=$basedir/libsmi2pysnmp # part of pysnmp distro smidump=smidump # part of libsmi distro while getopts o: o do case "$o" in - o) exec 5>"$OPTARG" 1>&5 || { echo >&2 "Redirection failed"; exit 1; } ;; + o) outFile=$OPTARG ;; [?]) echo >&2 "\ Convert MIB text file into PySNMP-compliant module, see http://pysnmp.sf.net. Usage: $0 [-o pysnmp-mib-file ] [ mib-text-file ]\ @@ -18,16 +19,20 @@ esac done +[ -n "$outFile" ] && { + exec 5>"$outFile" 1>&5 || { echo >&2 "Redirection failed"; exit 1; } +} + shift $((OPTIND-1)) [ $# -gt 1 ] && { echo >&2 "Extra arguments given"; exit 1; } [ -z $1 ] && { mibFile="-"; } || { mibFile=$1; - export SMIPATH=":$SMIPATH:$(echo $mibFile | sed -e 's/\(.*\)\/.*/\1/g')"; + export SMIPATH="$SMIPATH:$(echo $mibFile | sed -e 's,[^/]*$,.,')"; } -egrep -q 'FROM *RFC' $mibFile 2> /dev/null && { oldMib='yes'; } || { +egrep -q 'FROM *RFC' $mibFile 2> /dev/null && ! egrep -q 'FROM *SNMPv2-' $mibFile 2> /dev/null && { oldMib='yes'; } || { [ $? -eq 1 ] && { oldMib='no'; } || { echo >&2 "cant open $mibFile"; exit 1; @@ -35,21 +40,26 @@ } [ $oldMib = 'yes' ] && { # pysnmp SMI is SMIv2 - tmpFile=/tmp/buildmibs.$$ - $smidump -f smiv2 $mibFile > $tmpFile 2> /dev/null || { + [ -x "$(which mktemp)" ] && tmpFile=$(mktemp -t buildmibs.XXXXXXX) || tmpFile=/tmp/buildmibs.$$ + $smidump -k -f smiv2 $mibFile > $tmpFile 2> /dev/null || { [ -f $tmpFile ] && rm -f $tmpFile; - echo >&2 "$smidump -f smiv2 $mibFile fails"; + echo >&2 "$smidump -k -f smiv2 $mibFile fails"; + echo >&2 "make sure you are using libsmi version > 0.4.5 (or svn)"; exit ; } - $smidump -f python $tmpFile 2> /dev/null | $libsmi2pysnmp || { + $smidump -k -f python $tmpFile 2> /dev/null | $libsmi2pysnmp || { [ -f $tmpFile ] && rm -f $tmpFile; - echo >&2 "$smidump -f python $mibFile | $libsmi2pysnmp fails"; + [ -n "$outFile" ] && rm -f $outFile; + echo >&2 "$smidump -k -f python $mibFile | $libsmi2pysnmp fails"; + echo >&2 "make sure you are using libsmi version > 0.4.5 (or svn)"; exit } rm -f $tmpFile } || { - $smidump -f python $mibFile 2> /dev/null | $libsmi2pysnmp || { - echo >&2 "$smidump -f python $mibFile | $libsmi2pysnmp fails"; + $smidump -k -f python $mibFile 2> /dev/null | $libsmi2pysnmp || { + [ -n "$outFile" ] && rm -f $outFile; + echo >&2 "$smidump -k -f python $mibFile | $libsmi2pysnmp fails"; + echo >&2 "make sure you are using libsmi version > 0.4.5 (or svn)"; exit } } diff -Nru python-pysnmp4-4.1.9a/tools/libsmi2pysnmp python-pysnmp4-4.2.2/tools/libsmi2pysnmp --- python-pysnmp4-4.1.9a/tools/libsmi2pysnmp 2007-02-07 13:01:32.000000000 +0000 +++ python-pysnmp4-4.2.2/tools/libsmi2pysnmp 2012-04-02 16:22:12.000000000 +0000 @@ -1,19 +1,26 @@ #!/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.7-alpha' +version = '0.1.3' +genTextLoader = 1 -class Error(StandardError): pass +class Error(Exception): pass if len(sys.argv) > 1: - sys.stderr.write('libsmi-to-pysnmp MIB converter, version %s.\n\ -smidump -f python | %s > \n' % (version, sys.argv[0])) - sys.exit(-1) + if sys.argv[1] == '--no-text': + genTextLoader = 0 + else: + sys.stderr.write('SNMP MIB to pysnmp objects converter, version %s.\n\ +Usage:\n\ + %s [--no-text]\n\ +Takes:\n\ + smidump -f python \n\ +program output on stdin, generates python code on stdout.\n\ +The smidump tool is available at http://www.ibr.cs.tu-bs.de/projects/libsmi/\n\ +The --no-text option disables code generation for MIB text comments.\n' % (version, sys.argv[0])) + sys.exit(-1) inputText = '' while 1: @@ -32,10 +39,8 @@ 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'] @@ -58,90 +63,70 @@ } 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 @@ -153,29 +138,29 @@ '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'): @@ -183,33 +168,48 @@ 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': if classMode: - r = r + 'subtypeSpec = %s.subtypeSpec+constraint.SingleValueConstraint(' % parentType + r = r + 'subtypeSpec = %s.subtypeSpec+' % parentType else: - r = r + '.subtype(subtypeSpec=constraint.SingleValueConstraint(' + r = r + '.subtype(subtypeSpec=' + # Python has certain limit on the number of func params + if len(typeDef) > 127: + r = r + 'ConstraintsUnion(' + r = r + '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 + '), SingleValueConstraint(' + cnt = cnt + 1 + if len(typeDef) > 127: + r = r + ')' if classMode: r = r + ')\n' r = r + identFiller*identValue else: r = r + '))' if classMode: - r = r + 'namedValues = namedval.NamedValues(' + r = r + 'namedValues = NamedValues(' else: - r = r + '.subtype(namedValues=namedval.NamedValues(' - typedesc = typeDef.items() - typedesc.sort(lambda x,y: cmp(x[1],y[1])) + r = r + '.subtype(namedValues=NamedValues(' + 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 + ') + NamedValues(' + cnt = cnt + 1 if classMode: r = r + ')\n' r = r + identFiller*identValue @@ -219,32 +219,33 @@ 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): - __subtypeSpec = 'constraint.ValueSizeConstraint' + if baseType in __kludgyStringTypes: + __subtypeSpec = 'ValueSizeConstraint' else: - __subtypeSpec = 'constraint.ValueRangeConstraint' + __subtypeSpec = '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". The patch - # for it is available from http://www.glas.net/~ilya/download/tools/pysnmp/libsmi-0.4.5-perl_python_range_union.patch - # Thanks to Randy Couey! - if typeDef.has_key('ranges'): + # 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 'ranges' in typeDef: # if more than one size/range is given, then we need to - # create a ContraintsUnion to hold all of them. + # create a ConstraintsUnion to hold all of them. if len(typeDef['ranges']) > 1: single_range = 0 if classMode: - r = r + 'subtypeSpec = %s.subtypeSpec+constraint.ConstraintsUnion(' % parentType + r = r + 'subtypeSpec = %s.subtypeSpec+ConstraintsUnion(' % parentType else: - r = r + '.subtype(subtypeSpec=constraint.ConstraintsUnion(' + r = r + '.subtype(subtypeSpec=ConstraintsUnion(' for range in typeDef['ranges']: r = r + '%s(%s,%s),' % (__subtypeSpec, __reprIntVal(range['min']), __reprIntVal(range['max'])) if classMode: @@ -252,32 +253,38 @@ r = r + identFiller*identValue else: r = r + '))' - # only one size/range contraint was given + # only one size/range constraint was given if single_range: 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'): - 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( @@ -288,27 +295,48 @@ ) out.write("# Python version %s\n\n" % str(sys.version_info)) -out.write('# Imported just in case new ASN.1 types would be created\n') -out.write('from pyasn1.type import constraint, namedval\n\n') - out.write('# Imports\n\n') +# smidump sometimes does not fully convert into SMIv2 +__replacementModules = { + ('RFC1213-MIB', 'mib-2'): ('SNMPv2-SMI', 'mib-2'), + ('RFC1213-MIB', 'transmission'): ('SNMPv2-SMI', 'transmission'), + ('RFC1213-MIB', 'ifIndex'): ('IF-MIB', 'ifIndex'), + ('RFC1213-MIB', 'ifAdminStatus'): ('IF-MIB', 'ifAdminStatus'), + ('RFC1213-MIB', 'ifOperStatus'): ('IF-MIB', 'ifOperStatus'), + ('RFC1213-MIB', 'PhysAddress'): ('SNMPv2-TC', 'PhysAddress'), + ('RFC1213-MIB', 'ipAdEntAddr'): ('IP-MIB', 'ipAdEntAddr') + } + imports = {} for imp in ( { 'module': 'ASN1', 'name': 'Integer' }, { 'module': 'ASN1', 'name': 'OctetString' }, { 'module': 'ASN1', 'name': 'ObjectIdentifier' }, + { 'module': 'ASN1-ENUMERATION', 'name': 'NamedValues' }, + { 'module': 'ASN1-REFINEMENT', 'name': 'ConstraintsUnion' }, + { 'module': 'ASN1-REFINEMENT', 'name': 'ConstraintsIntersection' }, + { 'module': 'ASN1-REFINEMENT', 'name': 'SingleValueConstraint' }, + { 'module': 'ASN1-REFINEMENT', 'name': 'ValueRangeConstraint' }, + { 'module': 'ASN1-REFINEMENT', 'name': 'ValueSizeConstraint' }, { 'module': 'SNMPv2-SMI', 'name': 'Bits' }, # XXX { 'module': 'SNMPv2-SMI', 'name': 'Integer32' }, # libsmi bug { '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'], imp['name']) in __replacementModules: + imp['module'], imp['name'] = __replacementModules[ + (imp['module'], imp['name']) + ] + 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]: @@ -320,27 +348,47 @@ out.write(', \"%s\"' % s) out.write(')\n') -if mib.has_key('typedefs'): - typedefs = mib['typedefs'].items(); typedefs.sort() +if 'typedefs' in mib: + typedefs = [ item for item in mib['typedefs'].items() if 'parent module' not in item[1] ] + typedefs.sort() + typedefs_left = [ item for item in mib['typedefs'].items() if 'parent module' in item[1] ] + typedefs_left.sort() + typedefs_seen = set([ item[0] for item in typedefs ]) + while len(typedefs_left): + delayed = [] + for t in typedefs_left: + if t[1]['parent module']['name'] in { \ + # implicitly imported MIBs + 'SNMPv2-TC', + 'SNMPv2-SMI' + } or t[1]['parent module']['type'] in typedefs_seen: + typedefs_seen.add(t[0]) + typedefs.append(t) + continue + delayed.append(t) + if len(delayed) == len(typedefs_left): + for t in typedefs_left: + sys.stderr.write('WARNING: unresolved type %s(%s::%s)\n' % (t[0], t[1]['parent module']['name'], t[1]['parent module']['type'])) + sys.stderr.write('WARNING: %d unresolvable types used\n' % len(delayed)) + typedefs.extend(typedefs_left) + break + typedefs_left = delayed 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 = () @@ -348,36 +396,51 @@ out.write('\n# Objects\n\n') row_create = {} for symName, symDef in nodes: - out.write('%s = ' % transOpers(symName)) if symDef['nodetype'] == 'node': + 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 '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 'description' in symDef: + out.write('ObjectIdentity(%s)' % __oidToTuple(symDef['oid'])) else: out.write('MibIdentifier(%s)' % __oidToTuple(symDef['oid'])) - if symDef['nodetype'] == 'scalar': + 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']) - if symDef['nodetype'] == 'table': + elif symDef['nodetype'] == 'table': + out.write('%s = ' % transOpers(symName)) out.write('MibTable(%s)' % __oidToTuple(symDef['oid'])) - if symDef['nodetype'] == 'row': + elif symDef['nodetype'] == 'row': + 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']: @@ -396,28 +459,48 @@ break else: modName = dstModName + if idx == symDef['linkage'][-1] and \ + 'implied' in symDef and \ + symDef['implied'] == 'true': + impliedFlag = 1 + else: + impliedFlag = 0 + out.write('(%d, \"%s\", \"%s\")' % ( - 0, modName, idx + impliedFlag, modName, idx )) out.write(')') - if symDef['nodetype'] == 'column': + 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: out.write('.setMaxAccess(\"%s\")' % symDef['access']) + elif symDef['nodetype'] == 'capabilities': + out.write('%s = ' % transOpers(symName)) + out.write('AgentCapabilities(%s)' % __oidToTuple(symDef['oid'])) + else: + sys.stderr.write('Warning: skipping unknown node type %s, oid %s\n' % (symDef['nodetype'], symName)) + continue - out.write('%s\n' % addLabelForSymbol(symName)) + out.write('%s' % addLabelForSymbol(symName)) + + if genTextLoader: + 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: @@ -430,17 +513,15 @@ '%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, '.')) - nodes.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 = () @@ -450,18 +531,23 @@ out.write('%s = ' % transOpers(symName)) if symDef['nodetype'] == 'notification': out.write('NotificationType(%s)' % __oidToTuple(symDef['oid'])) - out.write('.setObjects(') + out.write('.setObjects(*(') for objName, objDef in symDef['objects'].items(): + if (objDef['module'], objName) in __replacementModules: + objDef['module'], objName = __replacementModules[ + (objDef['module'], objName) + ] out.write('(\"%s\", \"%s\"), ' % (objDef['module'], objName)) - out.write(')') + out.write(') )') + out.write('%s' % addLabelForSymbol(symName)) + if genTextLoader: + 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, '.')) - nodes.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 = () @@ -470,11 +556,55 @@ for symName, symDef in groups: out.write('%s = ' % transOpers(symName)) if symDef['nodetype'] == 'group': - out.write('ObjectGroup(%s)' % __oidToTuple(symDef['oid'])) - out.write('.setObjects(') + if symName.find('otification') < 0: # hackerish + out.write('ObjectGroup(') + else: + out.write('NotificationGroup(') + out.write('%s)' % __oidToTuple(symDef['oid'])) + out.write('.setObjects(*(') for objName, objDef in symDef['members'].items(): + if (objDef['module'], objName) in __replacementModules: + objDef['module'], objName = __replacementModules[ + (objDef['module'], objName) + ] out.write('(\"%s\", \"%s\"), ' % (objDef['module'], objName)) - out.write(')') + out.write(') )') + out.write('%s' % addLabelForSymbol(symName)) + if genTextLoader: + if 'description' in symDef: + out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n'))) + out.write('\n') + +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 = () + +if compliances: + out.write('\n# Compliances\n\n') + for symName, symDef in compliances: + out.write('%s = ' % transOpers(symName)) + if symDef['nodetype'] == 'compliance': + out.write('ModuleCompliance(') + out.write('%s)' % __oidToTuple(symDef['oid'])) + if 'requires' in symDef: + out.write('.setObjects(*(') + for objName, objDef in symDef['requires'].items(): + if (objDef['module'], objName) in __replacementModules: + objDef['module'], objName = __replacementModules[ + (objDef['module'], objName) + ] + # XXX nodetype not stored + out.write('(\"%s\", \"%s\"), ' % (objDef['module'], objName)) + out.write(') )') + # XXX refinements not stored + out.write('%s' % addLabelForSymbol(symName)) + if genTextLoader: + 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') @@ -482,13 +612,13 @@ if moduleIdentityNode: out.write('# Module identity\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) - out.write(', PYSNMP_MODULE_ID=%s' % moduleIdentityNode) + out.write(', PYSNMP_MODULE_ID=%s' % transOpers(moduleIdentityNode)) out.write(')\n\n') 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') @@ -500,40 +630,50 @@ 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') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) - out.write(', %s=%s' % ( - transOpers(symTrans(symName)[0]), transOpers(symTrans(symName)[0]) - )) + out.write(', %s=%s' % ((transOpers(symTrans(symName)[0]),)*2)) idx = idx + 1 out.write(')\n\n') 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') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) - out.write(', %s=%s' % (symName, symName)) + out.write(', %s=%s' % ((transOpers(symName),)*2)) idx = idx + 1 out.write(')\n\n') 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') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) - out.write(', %s=%s' % (symName, symName)) + out.write(', %s=%s' % ((transOpers(symName),)*2)) idx = idx + 1 - out.write(')\n') + out.write(')\n\n') + +if compliances: + out.write('# Compliances\n') + out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) + idx = 1 + for symName, symObj in compliances: + if idx % 127 == 0: + out.write(')\n') + out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) + out.write(', %s=%s' % ((transOpers(symName),)*2)) + idx = idx + 1 + out.write(')\n') # XXX # implement API version checking