pax_global_header00006660000000000000000000000064135424410070014512gustar00rootroot0000000000000052 comment=1dcc0428eafbacd46e987cec0504b12308c810df pysnmp-4.4.12/000077500000000000000000000000001354244100700131305ustar00rootroot00000000000000pysnmp-4.4.12/.gitignore000066400000000000000000000004071354244100700151210ustar00rootroot00000000000000# Python stuff *.pyc __pycache__ # vim swapfiles *.sw? # python packaging MANIFEST dist/ build/ *.egg-info/ # PyCharm stuff .idea/ # Sphinx template docs/source/.templates/layout.html # Eclipse stuff .project .pydevproject # Virtual envs venv* # Tox .tox/ pysnmp-4.4.12/.travis.yml000066400000000000000000000013631354244100700152440ustar00rootroot00000000000000language: python cache: pip matrix: include: - os: linux dist: trusty python: '2.6' - os: linux dist: trusty python: '2.7' - os: linux dist: trusty python: '3.2' - os: linux dist: trusty python: '3.3' - os: linux dist: trusty python: '3.4' - os: linux dist: trusty python: '3.5' - os: linux dist: trusty python: '3.6' - os: linux dist: xenial sudo: true python: '3.7' - os: linux dist: trusty python: 'nightly' - os: linux dist: trusty python: 'pypy' - os: linux dist: trusty python: 'pypy3' install: - pip install -r requirements.txt -r devel-requirements.txt - pip install -e . - pip install pysnmp-mibs script: - sh runtests.sh pysnmp-4.4.12/CHANGES.txt000066400000000000000000002102601354244100700147420ustar00rootroot00000000000000 Revision 4.4.12, released 2019-09-24 ------------------------------------ - Fixed broken SNMPv3 `msgFlag` initialization on authoritative SNMP engine ID discovery. This bug causes secure communication with peer SNMP engines to stall at SNMP engine ID discovery procedure. Revision 4.4.11, released 2019-08-10 ------------------------------------ - Added SNMPv3 USM master and localized keys support to LCD configuration - Improved initial and runtime USM debugging - Fixed a bug in USM configuration which did not allow the same user names to be added under different security names Revision 4.4.10, released 2019-07-29 ------------------------------------ - Reworked VACM access control function. Most important changes include: * Added subtree match negation support (vacmViewTreeFamilyType) * Added subtree family mask support (vacmViewTreeFamilyMask) * Added prefix content name matching support (vacmAccessContextMatch) * Added key VACM tables caching for better `isAccessAllowed` lookup performance One potential incompatibility may be caused by the `addContext()` call which now needs to be made explicitly during low-level VACM configuration rather than be a side effect of `addVacmAccess()` call. - Rebased MIB importing code onto `importlib` because `imp` is long deprecated - Received MIB objects resolution made more forgiving to errors, added optional `ignoreErrors` parameter to `ObjectType.resolveWithMib()` to control that behaviour. - Fixed asyncore main loop to respect non-default timer resolution - Fixed `.setTimerResolution()` behaviour of abstract main loop dispatcher to update call intervals of the existing periodic dispatcher jobs - Fixed `var-bindings` initialization to prevent pyasn1 encoder failures with newer pyasn1 versions where `SequenceOf` type looses its default initializer. - Fixed crash on uninitialized component serialization left out in SNMP v1 TRAP PDU to SNMPv2/3 TRAP PDU proxy translation routine. Revision 4.4.9, released 2019-02-09 ----------------------------------- - Made MIB loader ignoring file and directory access errors - Added missing SNMP PDU error classes and their handling in Command Responder - Fixed crash on MIB load failure in case of directory access error - Fixed socket transparency option (IPV6_TRANSPARENT) to make IPv6 transparent operation functional Revision 4.4.8, released 2018-12-30 ----------------------------------- - Fixed Pythonized MIB load (in the source form) - made sure to turn it into a code object prior to its execution Revision 4.4.7, released 2018-12-29 ----------------------------------- - Copyright notice extended to the year 2019 - Exposed ASN.1 `Null` type through `rfc1902` module for convenience. - Use `compile()` before `exec`'ing MIB modules to attach filename to the stack frames (ultimately shown in traceback/debugger) - Fixed hlapi/v3arch transport target caching to ensure transport targets are different even if just timeout/retries options differ - Fixed hlapi LCD configurator to include `contextName`. Prior to this fix sending SNMPv3 TRAP with non-default `contextName` would fail. - Fixed possible duplicate key occurrence in the `OrderedDict` following a race condition - Fixed undefined name references in `inet_pton`/`inet_ntop` substitute routines for IPv6 in `TRANSPORT-ADDRESS-MIB.py` Revision 4.4.6, released 2018-09-13 ----------------------------------- - Improved package build and dependency tracking - Fixed missing LICENSE from the tarball distribution - Fixed `CommandGeneratorLcdConfigurator.unconfigure()` to fully clean up internal caches, otherwise repetitive attempts to configure the target would fail. - Fix to tolerate possible duplicate enumerations in `Bits` and `Integer` SMI types. - Fix to tolerate non-initialised entries in SNMP community table. Once a bad entry sneaked into the SNMP community table, all the subsequent SNMP v1/v2c operations failed. The fix ignores incomplete SNMP community table entries in the course of building indices. Revision 4.4.5, released 2018-08-05 ----------------------------------- - Added PySnmpError.cause attribute holding parent exception tuple - Fixed broken InetAddressType rendering caused by a pyasn1 regression - Fixed typo in RFC1158 module - Fixed possible infinite loop in GETBULK response PDU builder - Fixed memory leak in the `config.delContext()` VACM management harness - Fixed `Bits` class initialization when enumeration values are given - Fixed crash caused by incoming SNMPv3 message requesting SNMPv1/v2c security model - Fixed out-of-scope OIDs leaking at the end of SNMP table at hlapi `nextCmd` and `bulkCmd` calls when `lexicographicMode = False` Revision 4.4.4, released 2018-01-03 ----------------------------------- - Copyright notice extended to the year 2018 - Fixed short local key expansion at 3DES key localization implementation. Revision 4.4.3, released 2017-12-22 ----------------------------------- - Migrated references from SourceForge - Added missing SHA2 support for Blumenthal key localization - Fixed named bits handling at rfc1902.Bits - Fixed missing SmiError exception class at pysnmp.proto.rfc1155 - Fixed SNMP v1->v2c PDU proxy -- error-status & error-index fields from v1 PDU get copied over to v2c PDU in addition to the exception sentinels being set Revision 4.4.2, released 2017-11-11 ----------------------------------- - The pysnmp version being used gets exposed to the MIB modules via the `MibBuilder` instance - The .setObjects() method of the SMI types now accepts `append=False` parameter to let the caller adding more than 255 elements over the course of multiple calls - Added support for some more missing fields of SMIv2 MACRO types - Example scripts rearranged in a way that IPv6 requirement is clearly encoded in the script's name - Fixed SNMPv2-SMI.NotificationType to expose .set/getReference() instead of .set/getRevision() which should not be there in the first place - Fixed non-implied-OID encoding in SNMP table indices - Fixed inconsistent SNMPv3 discovery and retrying algorithm Revision 4.4.1, released 2017-10-23 ----------------------------------- - HMAC-SHA-2 Authentication Protocols support added (RFC-7860) - The pycryptodome dependency replaced with pycryptodomex as it is recommended by the upstream to avoid unwanted interference with PyCrypto package should it also be installed - Sphinx theme changed to Alabaster in the documentation - Minor adjustments towards pyasn1 0.4.x compatibility - Fixed ObjectIdentifier-into-ObjectIdentity casting at rfc1902.ObjectType MIB resolution harness - Fixed NetworkAddress object handling in SNMP table indices - Fixed MIB lookup by module:object.indices MIB object with InetAddressIPv{4,6} objects being in the index - Fixed non-translated PDU being retries at CommandGenerator what leads to wrong PDU version being sent and even a crash on incompatible PDU/SNMP message combination Revision 4.3.10, released 2017-10-06 ------------------------------------ - Refactored partial SNMP message decoding to make it less dependent on unpublished pyasn1 API features. - Fix to MibTableRow.setFromName() to keep the input parameter type when it propagates to the return value. Before this fix ObjectIdentity.prettyPrint() may crash when rendering malformed SNMP table indices. - Fixed NotificationReceiver to include SNMPv1 TRAP Message community string into SNMPv2c/v3 TRAP PDU - Fixed multiple bugs in SNMP table indices rendering, especially the InetAddressIPv6 type which was severely broken. - Fixed crashing Bits.prettyPrint() implementation - Fixed crashing Bits.clone()/subtype() implementation - Fixed leaking exceptions bubbling up from the asyncio and Twisted adapters Revision 4.3.9, released 2017-07-26 ----------------------------------- - Deprecated UsmUserData initializaton parameters removed - Adapted to pyasn1 API changes introduced by release 0.3.1 - Fix to a crash happening on inbound SNMP message having non-initialized fields - Fix to (persistent SNMP engine ID) file writing on Windows Revision 4.3.8, released 2017-06-15 ----------------------------------- - Security fix to the bug introduced in 4.3.6: msgAuthoritativeEngineTime stopped changing over time and was returning the same timestamp (process start time). This fix makes it growing as it should. Revision 4.3.7, released 2017-05-29 ----------------------------------- * Fixed import error in legacy NotificationOriginator implementation Revision 4.3.6, released 2017-05-28 ----------------------------------- - More instrumentation hooks added addressing security failures auditing needs. - SNMP table indices correlation implemented within SMI framework. The opaque InetAddress type implemented. INET-ADDRESS-MIB included into the distribution. - SNMP table indices resolution logic made more robust against malformed indices. - Fixes to *lexicographicMode* option documentation to make it unambiguous. - The `ErrorIndication` object is now derived from `Exception` so that it could be raised in exceptions. - The `errorIndication` values produced by various parts of SNMP engine unified to be `ErrorIndication` instances. This fixes an issue with Twisted. - Embedded MIB modules rebuilt with the latest pysmi adding previously missing attributes like `status`, `description` etc. - Fixed potential SNMP engine crash on handling incoming message at unsupported security level Revision 4.3.5, released 2017-03-24 ----------------------------------- - The getNext() and getBulk() calls of Twisted interface. now support ignoreNonIncreasingOid option. - TextualConvention is now a new-style class. - Fix to accidentally reset error-status when building confirmed class SNMPv1 PDU. - Fix to possible infinite recursion in TextualConvention.prettyIn(). - Fixed crash when attempting to report unsupported request/notification PDU back to sender. Revision 4.3.4, released 2017-03-01 ----------------------------------- - Fix to low-level SNMP API example to accommodate changed pyasn1 SEQUENCE supporting iterator protocol. - The pyasn1 version dependency bumped (0.2.3), SEQUENCE/SEQUENCE OF API calls adjusted to accommodate changed pyasn1 API (in part of .setComponentBy*() kw flags). - Fixed crash on SNMP engine's invalid message counter increment. Revision 4.3.3, released 2017-02-04 ----------------------------------- - Switched from now unmaintained PyCrypto to PyCryptodome. - Switched to new-style classes. - NotificationType now allows additional var-binds specified as MIB objects. A side effect of this change is that additional var-binds can only be added prior to .resolveMibObjects() is run. - Non-standard (but apparently used by many vendors) Reeder AES192/256 key localization algorithm implemented and set as default for usmAesCfb192Protocol and usmAesCfb256Protocol identifiers. Original and more standard implementation can still be used with the usmAesBlumenthalCfb192Protocol and usmAesBlumenthalCfb192Protocol IDs respectively. - TextualConvention.prettyOut() improved to produce prettier and more SMI-compliant output. - TextualConvention.prettyIn() implemented to handle DISPLAY-HINT based value parsing. - Fix to NotificationType to make additional var-binds overriding MIB objects implicitly included through NOTIFICATION-TYPE OBJECTS. - Fix to SNMP engine boots counter persistence on Python 3. - Fix to Pythonized MIBs loading when only .pyc files are present (e.g. py2exe/cx_freeze environments). - Fix broken 3DES key localization and encryption procedures. - Updated IP address for demo.snmplabs.com in examples. - Missing index added to bundled RFC1213::atEntry MIB table. - Twisted integration made Python3 compatible. - Accommodated ASN.1 SEQUENCE iteration rules change in upcoming pyasn1 version. - Author's email changed, copyright extended to 2017. Revision 4.3.2, released 2016-02-12 ----------------------------------- - Copyright notice added to non-trivial source code files. - SNMP table row consistency check added. This change may break valid SNMP SET operations on tables if RowStatus column is not passed at the very end of var-binds. - All SNMP counters now incremented via '+= 1' rather than 'x = x + 1' to simplify their tracking by third-party code. - Notification originator examples re-pointed to Notification Receiver at demo.snmplabs.com. - Two more execution observer points added: rfc2576.processIncomingMsg and rfc3414.processIncomingMsg to give an insignt on security modules internals. - TEXTUAL-CONVENTION's DISPLAY-HINT text formatting reworked for better performance and encoding accurancy of 'a' and 't' formats. - WARNING: security fix to USM - extra user entry clone removed on incoming message processing. It made USM accepting SNMPv3 TRAPs from unknown SNMP engine IDs. - Fix to snmpInvalidMsgs and snmpUnknownSecurityModels MIB symbols import at SNMPv3 MP model. - Fix to NotificationOriginator to cope with unspecified user callable. - Fix to OctetString.prettyOut() to pretty-print Python 3 bytes without 'b' qualifier. - Fix to better pysmi import errors handling. - Fix to missing next() in Python 2.5 at pysnmp.hlapi Revision 4.3.1, released 2015-11-12 ----------------------------------- - Added recursive resolution of ObjectIdentifier values at ObjectType by converting it to ObjectIdentity. - A bunch of convenience shortcuts to rfc1902.ObjectIdentity added from rfc1902.ObjectType and rfc1902.NotificationType (.addAsn1MibSource(), .addMibSource(), .loadMibs()) - When pretty printing indices at rfc1902.ObjectType, quote only strings. - SNMP overview and PySNMP hlapi tutorial added to documentation. - Fix to __doc__ use in setup.py to make -O0 installation mode working. - Fix to ObjectIdentity->ObjectIdentifier attributes handover - Fixed crash at oneliner compatibility code on EOM response. - Fixed crash in hlapi.transport module. - Fixed OID resolution issues that roots at node 0 and 2. - Fix to MIB builder to fail gracefully on corrupted MIB package encounter. - Fix to docs distribution -- now the are Sphinx-buildable out-of-the-box. - Source code re-linted Revision 4.3.0, released 2015-09-28 ----------------------------------- - Critical error fixed in key localization procedure for AES192/AES256/3DES cyphers. Previous versions might never worked properly in this respect. - Initial PySMI integration. Original ASN.1 MIBs could now be parsed, stored at a local pysnmp MIBs repository and loaded into SNMP Engine. Relevant example scripts added. Obsolete libsmi-based scripts removed. - Major rewrite of native SNMPv3 CommandGenerator and NotificationOriginator applications towards the following goals: * avoid binding to specific SNMP engine instance to promote single SNMP app instance using many SNMP engine instances * support two APIs for working with request data: one operates on the whole PDU object while the other on PDU contents * keep callback context data in stack rather than in stateful application cache * newly introduced sendVarBinds() method offers a more functional and logical signatures. * Promote the use of dedicated classes for dealing with OID-value pairs. Instances of those classes resemble OBJECT-IDENTITY, OBJECT-TYPE and NOTIFICATION-TYPE MIB structures. * Oneliner API reworked to become more generic: its LCD configuration shortcuts and and var-bindings processing code split off SNMP apps classes to stand-alone objects. The whole API also moved up in package naming hierarchy and becomes 'pysnmp.hlapi.asyncore' (hlapi is apparently an African fish). Old oneliner API remains fully operational at its original location. * Synchronous oneliner apps redesigned to offer Python generator-based API along with a more comprehensive set of accepted parameters. * Asyncore-based asynchronous apps reworked to become functions. * Twisted API moved entirely into high-level domain to be aligned with other high-level APIs. This WILL BREAK backward compatibility for those apps that use Twisted API. * Keep backward compatibility for all existing major/documented interfaces - Sphinx documentation added to source code and example scripts. Library documentation converted from .html into RsT markup. - Execution Observer facility implemented to give app an inside view of SNMP engine inner workings. This is thought to be a generic framework for viewing (and modifying) various internal states of pysnmp engine. Previously introduced non-standard APIs (like getting peer's transport endpoint which is not suggested in RFCs) will be gradually migrated to this new framework. - Initial support for the asyncio & Trollius frameworks and coroutines-based SNMP Applications interfaces added. Both IPv4 and IPv6 datagram transports are currently supported. - Original asynsock transport and AsyncsockDispatcher renamed into asyncore and AsyncoreDispatcher respectively to provide better hint to fellow devs on the underlying transport being used. Backward compatibility preserved. - The asyncore-based transport subsystem extended to support POSIX sendmsg()/recvmsg() based socket communication what could be used, among other things, in the context of a transparent SNMP proxy application. Technically, the following features were brought into pysnmp with this update: * Sending SNMP packets from a non-local IP address * Receiving IP packets for non-local IP addresses * Responding to SNMP requests from exactly the same IP address the query was sent to. This proves to be useful when listening on both primary and secondary IP interfaces. - Internal oneliner apps configuration cache moved from respective apps objects to [a singular] snmpEngine "user context" object. That would allow for better cache reuse and allow for a single app working with many snmpEngine instances. - Oneliner GETBULK Command Generator now strips possible excessive OIDs off the bottom of returned var-binds table. - Constraints assignment shortcut added to some base rfc1902 types (Integer, Integer32, OctetString, Bits). That formally constitutes ASN.1 sub-typing. - Built-in debugging is now based on Python logging module. - Examples on a single Transport Dispatcher use with multiple SnmpEngine instances applicatons added. - Example script on transport timeout & retries manipulation added. - Example script explaining incoming message's communityName re-mapping added. - Broadcast socket option can now be enabled with the .enableBroadcast() call for any datagram-based transport (namely, UDP and UDP6). - AbstractTransportDispatcher's jobStarted() and jobFinished() methods now accept optional 'count' parameter which is a way for an app to indicate how many responses are expected or have been processed in bulk. - Example script on SNMP Agents UDP broadcast-based discovery added. - Oneliner transport object now supports setLocalAddress() method to force socket binding to specified local interface. - New public DgramSocketTransport.getLocalAddress() returns local endpoint address underlying BSD socket is currently bound to. - Passing request details to access control callback at CommandResponder reworked towards more robust and simple design with the execution observer facility. - All MIBs rebuilt with pysmi. - MIB instrumentation example improved to cover table index building facility. - Handle the case of null writer at Debug printer. - Do not cache snmpEngineId & snmpAdminString at CommandGenerator to let it be reused with many different snmpEngines. - TRAP PDU agent address evaluation at proto.api made lazy to improve startup time. - Multiple fixes to verify pyasn1 decoder.decode() return to withstand broken SNMP messages or its components. - First attempt made to make some of SNMP Engine settings persistent across reboots. - Make config.delTransport() returning detached transport object. Asyncio examples now use this facility to explicitly shutdown transport object. - Parts of SMIv1 remnant MIBs (RFC1213-MIB, RFC1158-MIB) added to provide complete compatibility with SMIv1. Symbols defined in these MIBs only present in SMIv1 so they can't be substituted with their SMIv2 analogues. - MibBuilder.addMibSources() convenience method added. - The smi.MibBuilder() will now raise more specific exceptions (MibLoadError, MibNotFoundError) on MIB loading problems rather than more generic SmiError. - The oneliner's MibVariable MIB lookup subsystem redesigned for more generality to mimic OBJECT-TYPE macro capabilities related to SNMP PDU handling. The two new classed are ObjectIdentity and ObjectType. The ObjectIdentity class additionally supports just a MIB module name initializer in which case if resolves into either first or last symbol in given MIB. Another option is just a MIB symbol initializer without specifying MIB module. This new subsystem is moved from the scope of oneliner to more common pysnmp.smi.rfc1903 scope to more naturally invoke it from whatever part of pysnmp requires MIB services. - MibBuilder now prepends the contents of environment variables it recognizes (PYSNMP_MIB_DIR, PYSNMP_MIB_DIRS, PYSNMP_MIB_PKGS) rather than using them instead of its default core MIBs. - Removed RowStatus default value as it may collide with possible subclass constraints. - A few additional MIB tree management methods added to MibViewController to better address ordered nature of MIB tree nodes (namely, getFirst*, getLast* family of methods). - Wheel distribution format now supported. - Fix to authoritative engine side snmpEngineID discovery procedure: respond with notInTimeWindows rather then with unsupportedSecurityLevel at time synchronization phase. - Fix to rfc1902.Bits type to make it accepting hex and binary initializers, cope with missing bits identifieirs at prettyPrint(). - Memory leak fixed in CommandForwarder examples. - Fix to BULK CommandGenerator to use the same nonRepeaters OIDs across multiple GETBULK iterations so returned table for nonRepeaters columns would hold the same var-bind. - Fix to CommandGenerator to make sendRequestHandle persistent across multiple iterations of GETNEXT/GETBULK queries. - Fix to sendNotification() error handling at NotificationOriginator. - Fix to preserve possible 'fixed length' setting atrfc1902.OctetString on clone()'ing and subtype()'ing. - Fix to rfc1902.OctetString & Bits to base them on OctetString class to make the 'fixed length' property working. - Fix to .clone() method of rfc1902.Bits class to make its signature matching the rest of classes. This may broke code which used to pass namedValue parameter positionally rather than binding it by name. - Fix to PDU translation service (proto.proxy.rfc2576) to make it initializing errorIndex & errorStatus components of the resulting PDU. - Fix to MsgAndPduDispatcher.sendPdu() to clean up request queue on pysnmp-level processing failure. - Fix to SNMPv1/v2c message processing subsystem to make it serving unique PDU request-id's in both outgoing and incoming confirmed and response PDU types. Duplicate request-id's in unrelated PDUs may cause cache errors otherwise. - Fix to licensing terms of multiple twisted backend modules to make the whole pysnmp package licensed under BSD 2-Clause license. This change has been explicitly permitted by the original modules authors. - Fix to asyncore-based transport not to use asyncore's cheap inheritance from socket object what caused warnings. - Fix at NotificationOriginator to make is using MibInstrumentationController when expanding Notification OBJECTS into Managed Objects Instances. - Missing wrongLength and wrongEncoding SMI errors added. - Fix to file descriptor leak at MibBuilder. - Fix to rfc2576.v2ToV1() to ignore impossible errorStatus. - Fix to rfc2576.v1ToV2() to reset ErrorStatus==noSuchName on proxying. - Fix to smi.builder to explicitly fail on any MIB file access error (but ENOENT) and raise IOError uniformly on any directory/egg access failure. - Fix to infinite loop at config.delV3User(). Revision 4.2.5, released 2013-10-02 ----------------------------------- - License updated to vanilla BSD 2-Clause to ease package use (http://opensource.org/licenses/BSD-2-Clause). - A dozen of lightweight Twisted-based example scripts replaced more complex example implementations used previously. - SNMP Proxy example apps separated into a larger set of more specialized ones. - Most of Command Generator examples re-pointed to a live SNMP Agent at demo.snmplabs.com to ease experimentation and adoption. - Multithreaded oneliner CommandGenerator example added. - Packet-level SNMP API (pysnmp.proto.api) getErrorIndex() method can now be instructed to ignore portentially malformed errorIndex SNMP packet value what sometimes happens with buggy SNMP implementations. - Standard SNMP Apps and built-in proxy now ignores malformed errorIndex value. - Built-in logging now includes timestamps. - Multi-lingual capabilities of all CommandGenerator & NotificationOriginator apps re-worked and improved. For instance it is now it's possible to run getBulk() against a SNMPv1 Agent invoking built-in SNMP Proxy behind the scene. - The $PYSNMP_MIB_DIR & $PYSNMP_MIB_DIRS & $PYSNMP_MIB_PKGS path separator made platform-specific. - Change to rfc2576.v1tov2() logic: errorStatus = noSuchName is now translated into rfc1905.noSuchObject exception value for *all* var-bindings at once. Although RFC2576 does not suggest error-status -> v2c exception translation, historically pysnmp used to perform it for a long time so we can't easily stop doing that. - Exception re-raising improved at MibInstrumController.flipFlopFsm() and asynsock/twisted dispatchers so that original traceback is preserved. - A single instance of transport dispatcher can now serve multiple receivers (identified by IDs) chosen by a public data routing method. - SnmpEngine.[un]registerTransportDispatcher() methods now accept optional receiver ID token to be used by transport dispatcher's data router. This allows for multiple SNMP engines registration with a single transport dispatcher. - Distribute is gone, switched to setuptools completely. - The snmpCommunityTable row selection improved to follow RFC2576, clause 5.2.1. - Asyncore-based dispatcher attempts to use poll() whenever available on the platform. It would help handling a really large number (>1024) of file descriptors. - AsynCommandGenerator.makeReadVarBinds() generalized into a new makeVarBinds() method which replaces somewhat redundant code at setCmd() and AsynNotificationOriginator.sendNotification(). - AsynCommandGenerator.uncfgCmdGen() & AsynNotificationOriginator.uncfgCmdGen() methods now accept optional authData parameter to remove specific entries from LCD. This can be useful for modifying security parameters for specific securityName. - SNMP credentials management reworked to separate userName from securityName in snmpCommunityEntry and usmUserEntry tables. Changes made to addV1System(), addV3User() functions as well as to their oneliner's wrappers. - The contextEngineId parameter of config.addV3User() and auth.UsmUserData() renamed into securityEngineId as it's semantically correct - Oneliner UsmUserData() and CommunityData() classes now support clone()'ing to facilitate authentication data management in user applications. - Oneliner transport target classes now support the getTransportInfo() method that returns network addresses used on protocol level. - Oneliner CommandGenerator.getNext() & .getBulk() methods now support the maxCalls kwarg to limit the maximum number of iterations to perform. - The config.addSocketTransport() helper renamed into config.addTransport() and improved by automatically instantiating compatible TransportDispatcher making it dispatcher-agnostic. As an additional bonus, application may not call registerTransportDispatcher() as it would be called by addTransport(). - The SnmpV3MessageProcessingModel.getPeerEngineInfo() method is implemented to communicate discovered peer SNMP engine information to SNMP apps what can be used for fine usmUserTable configuration. - AsynNotificationOriginator.cfgCmdGen() does not take into account securityModel & securityLevel when reducing LCD access via addTrapUser(). This improves LCD consistency on sparse add/del operatons but also does not let you to configure different securityModels per securityname at VACM though the cfgCmdGen() wrapper. - MIB builder traceback formatting and reporting improved. - SNMP Engine object now has a snmpEngineID attribute exposed. - Fix to inet_ntop()/inet_pton() support on Windows at TRANSPORT-ADDRESS-MIB. - Fix to usmUserSecurityName table column implementation -- automatic value generation from index value removed. - Fix and significant logic rework of snmpCommunityTable to make it working in both Generator and Responder modes and better follow RFC2576 requirements on sequential entries lookup and selection. As a side effect, untagged snmpCommunityTable entries will *not* match tagged snmpTargetAddrTable entries and vice versa. - Fix to Twisted-based NotificationOriginator to make it serving INFORMs again. - Fix to rfc2576.v1tov2() logic: errorStatus = noSuchName is now translated into rfc1905.noSuchObject exception value for *all* var-bindings. Although this is not mentioned in RFC, it looks as a more consistent approach. - Fix of rounding error to base I/O dispatcher's next timer call calculation. - Explicit twisted dispatcher's timer resolution (of 1 sec) removed to make use of global default of 0.5 sec. - Fix to twisted/udp non-default local endpoint binding features. Common socket ('host', port) notation is now supported. - Fix to Twisted-based transport to make it closing UDP port / UNIX pipe on shutdown. - Fix to Twisted-based dispatcher not to close transport on unregistration at dispatcher as transports can potentially be reused elsewhere. - Fix to asyncore-based transport to work only with AsynsockDispatcher's socket map and not to touch default asyncore's one. The latter have caused dispatcher/transport restarting issues. - The delV3User() function improved to drop all rows from USM table that were cloned from the target one. - Fix to exceptions handling at MsgAndPduDispatcher.sendPdu() to avoid sendPduHandle miss (followed by system crash) on cache expiration run. - Break cyclic references at CommandResponder and NotificationReceiver apps through close() method. - Fix to octet string typing at 3DES codec (used to throw an exception). - Fix to SnmpAdminString, SnmpTagList, SnmpTagValue types to make them supporting UTF-8 initializers. - Fix to v1/v2c message processing module which used to refer to a bogus stateReference in some cases what causes SNMP engine crashes. - Fix to IPv6 transport to zero ZoneID, FlowID and ScopeID components sometimes coming along with incoming packet. - Fix to SNMPv1 MP module to pass stateReference to registered app on unconfirmed notifications reception (to let NotificationReceiver Apps browsing request details). (transport information at the moment) at SNMP engine. - Asyncsock sockets now configured with SO_REUSEADDR option to fix possible Windows error 10048. - Gracefully handle malformed SnmpEngineID at USM coming from SNMPv3 header. - Typos fixed in error-status constants at CommandResponder - Missing import added to oneliner auth module. - Cosmetic changes to v3arch example scripts. Revision 4.2.4, released 2013-01-30 ----------------------------------- - SNMPv3 high-level and native API examples reworked and extended to cover many use cases. - The missing functionality of NOTIFICATION-TYPE objects being looked up at local Management Instrumentation and attached to TRAP/INFORM message by Notification Originator is now fully implemented. - The missing functionality of passing Response PDU contents of INFORM request is now implemented at Notification Originator app. The return value of NotificationOriginator.sendNotification is now a composite object that includes errorStatus, errorIndex and varBinds. - The missing functionality of passing lookupNames & lookupValues params to Notification Originator is now implemented. It may make sense for INFORMs. - The missing functionality of passing contextName to oneliner version of NotificationOriginator.sendNotification is now implemented. - Oneliner example apps now include cases where non-default SNMP ContextEngineId/ContextName/SecurityEngineId is used. - The contextName parameter of SnmpContext.getMibInstrum made optional. - AbstractMibInstrumController class added as a base class for all possible kinds of Management Instrumentation controllers. - Report package version on debugging code initialization. - MibInstrumController.getMibBuilder() added. - I/O sockets buffer sizes made configurable, minimum default is now forced to be no less than 2**17 (to fit two huge datagrams). - Catch possible exceptions on pyasn1 encoder invocation. - VACM modules converted from a function into an object to let it keep state (caches) in the future. - Unnecessary MibSource explicit initialization calls removed at MibBuilder. - Example configuration for Net-SNMP's snmptrapd added. - Cast additionalVarBinds into ObjectIdentifier type at NotificationOriginator.sendNotification() - Standard SNMPv3 Apps hardened to catch protocol-related exceptions and report them as errorIndication's. - Catch and mute possible failure of getsockname(), that seems to happen on Windows only so far. - Memory leak fixed at oneliner cache of already configured targets. - Fixes to at AsynNotificationOriginator.sendNotification() to make a) the notificationType param mandatory b)t e varBinds param really optional - Fixes to ContextEngineId/ContextName support at the oneliner API: now both items should be passed to request PDU through Cmd() request initiation method, the items of authData object should be used only for LCD configuration. - Fix to MibVariable handling of the MIB, initializers. - Fix to outgoing queue processing order at socket transport. Now it's a FIFO discipline rather than LIFO. - Fix to NotificationOriginator's additionalVarBinds parameter - it is not mandatory anymore with the oneliner API. Also additionalVarBinds defaulted value changed from None to () meaning no var-binds. - Attempt to convert Windows style EOL into UNIX ones in MIB source modules appeared to be unnecessary and even destructive to modules data in some cases. So the conversion code removed altogether. - Fix to isAccessAllowed() error handling at NotificationOriginator. System used to crash on access denied condition. - Fix to NotificationOriginator to make it use system uptime and trap OID values from SNMP engine's instrumentation rather then from SNMP context. - Fix a couple of bugs at MibTable* logic involved for table instances creation. - Fix to Management Instrumentation code to handle cases of non-initialized or not-compliant-to-constraints Managed Objects Instances. - Fix to Management Instrumentation code to make table row removal through SNMP working again. Wrong method (instumClone) was probed at terminal MIB nodes values instead of the right one (setValue). Revision 4.2.3, released 2012-09-06 ----------------------------------- - SECURITY FIX: USM subsystem did not verify securityLevel of a request to an authoritative SNMP engine against auth/priv protocols configured for the user in question. That allowed unauthenticated/unciphered access to pysnmp-based Agent even if USM user is configured to provide one. - Oneliner [Asyn]CommandGenerator now supports optional keyword args lookupNames, lookupValues that enable response OID / value looked up at MIB and reported as a MibVariable container object carrying relevant MIB info. - Oneliner [Asyn]CommandGenerator now supports symbolic MIB object names to be passed within a MibVariable container object which would do a deferred MIB lookup for name resolution. This is a new and preferred API which obsoletes the tuple-based one (it is still suppored though). - Oneliner CommandGenerator's class attributes lexicographicMode, maxRows and ignoreNonIncreasingOid moved to optional keyword args of nextGen() and bulkGen() methods. - IPv6/UDP and Local Domain Socket transport interfaces added to the oneliner API. - Mib Instrumentation subsystem re-worked to replace excessive MibNode's smiCreate()/smiWrite()/smiDestroy() methods with MibScalarInstance's getValue()/setValue() - MibTree.readTest[Get]Next() reworked to be called uniformely so user could tap on these methods at any level of the MIB tree. - MibTableColumn.getNextNodeWithValue() unpublished API method obsoleted and removed for clarity. - Hex dumps of binary parts of the protocol added to ease system operations analysis. - SnmpEngineId autogeneration does not call DNS resolver but uses local hostname not to depend upon local IP availability and performance. - Example apps reworked, additional SNMPv3 auth/priv protocols and transports added. - Package version is now available as __init__.__version__ and it is in-sync with distutils. - Package meta-information updated. - The __init__.py's made non-empty (rumors are that they may be optimized out by package managers). - Multiple fixes to UNIX domain socket transport to make it fully operational again. - Use sysUpTime value whenever it is included in Notification PDU, otheriwese resort to SNMP engine uptime reading. - SNMPv2c Message is now defined in rfc1901.py what matches standard definition. - Types defined within SNMPv1/v2c data structures (rfc1157.py/rfc1905.py) moved to module scope to become accessible by wrapper routines (v1.py/v2c.py). This is used for setting strictly typed default values to corresponding SNMP data structures. - The obsolete and unpublished MibInstrumController.readVarsFast() method removed for API clarity. - MibBuilder now distinguishes case of MIB modules filenames even if underlying OS does not. - LCD configuration caching is implemented at pysnmp.entity.rfc3413.config that improves performance of repetitive calls by 10% and might hugely improve NotificationOriginator's performance when working on a large number of targets. - A caching maps implemented at rfc2576 subsystem to speed-up communityName to/from securityName resolution. The also makes transport tags processing better compliant to the standard. - Community and Transport tags processing changed at the oneliner interface to make the whole mechanism more compliant with the standard. Most importantly, it is now possible to tag authentication and transport information separately. - The NoSuchInstanceError exception class is no more inherits from NoSuchObjectError to make class hierarchy closer to SNMP specification which states that these errors are separate and independent. - The Next & BulkCommandGenerator's split onto single-run and iterative impementations. The former just process a single interaction and complete while the latter run as many interactions as user callback function indicates to. - The pysnmp.entity.rfc3413.mibvar module is now obsolete by pysnmp.entity.rfc3413.oneliner.mibvar featuring basically the same features but within a stateful, dedicated object. - Auth & target configuration container classes moved to their separate modules at oneliner API. - The notificationType parameter of AsynNotificationOriginator.sendNotification made defaulted to reflect its optional nature. - Oneliner UsmUserData, UdpTransportTarget, Udp6TransportTarget instances are not hashable anymore as they are intended to act more like a data structure than object. - Built-in debugger now supports negating debugging categories. - An async/getgen.py example script added. - Fix to MIB data reading routine to make it working with possible Windows end-of-line's. - Fix to CommandGenerator's SNMPv3 engine autodiscovery algorithm when retryCount is administratively set to 0. - Fix to Notification Originator to make it communicating a single sendPduHandle to an application even when multiple INFORMs are triggered and processed by a single call by way of transport tagging feature. - Fix to rfc2576:processIncomingMessage() to take SecurityModel into account when lookup up SecurityName by CommunityName. This allows mixed SNMPv1/v2c communication with the same target. - Fix to internal MessageProcessing and SecurityModel timers so they become dependant on system timer resolution. - Fix to v1.PDUAPI.setDefaults() method that used to set wrongly typed time-stamp component. - Fix to IPv6 address handling to prevent system from crashing whilst running Python3. - Fix to SNMPv2 exception objects translation into SNMPv1 PDU and NEXT OIDs calculation. - Fix to MibTree class to properly report noSuchObject & noSuchInstance SNMP special values. - Fix to libsmi2pysnmp tool to make it working again in Python < 2.7 - Fix to exception handling at decodeMessageVersion() caller to prevent ASN.1 parsing errors crashing the whole app. - Fix to GenericTrap type processing at rfc2576:v1Tov2c() which used to crash the whole SNMP engine. - Fix to [possibly uninizilaized] pyasn1 objects printouts at MibInstrumController.__indexMib() - Fix to maxSizeResponseScopedPDU calculation at rfc3414/service.py. - Dedicated 'withmib' example set is obsolete and removed. - Another SNMP proxy example app added (1to3.py). - Fix to MIB modules loading code to make it using __import__() properly. This also makes pysnmp working again with Python 3.3rc0. - Typo fix to snmpInASNParseErrs MIB instance object. - Typo fix to errind.EngineIdMismatch class and its instance. Revision 4.2.2, released 2012-04-21 ----------------------------------- - 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. - SMIv1 MIB modules (including RFC1155 and RFC1213) were moved to pysnmp-mibs as pysnmp is SMIv2-based. - 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, released 2011-11-07 ----------------------------------- - 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 var-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, released 2011-09-22 ------------------------------------- - Fix to SNMPv1 Trap PDU agentAddress setter shortcut method. Revision 4.1.16c, released 2011-08-14 ------------------------------------- - Missing module import fixed in privacy subsystem Revision 4.1.16b, released 2011-08-13 ------------------------------------- - 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, released 2011-03-17 ------------------------------------- - 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 conversion 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, released 2010-12-13 ------------------------------------- - 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, released 2010-07-15 ------------------------------------- - 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, released 2010-02-09 ------------------------------------- - 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, released 2009-12-03 ------------------------------------- - 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, released 2009-08-21 ------------------------------------- - 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, released 2008-05-25 ------------------------------------- - 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, released 2007-11-28 ------------------------------------ - UNSTABLE ALPHA RELEASE. - At onliner CommandGenerator, close transport on destruction to prevent socket leak. Implicit async transports registration at default asyncore's socket map has been disabled to avoid side effects. - Fix to rfc2576.v1ToV2c() PDU converter to perform noSuchName error code translation. - Fixes to Notification PDU conversion code at rfc2576 in part of snmpTrapOID handling. - Fix to nonRepeaters object use as sequence slicer (must be int) at cmdrsp.CommandResponderApplication - Make AsynsockDispatcher using its own socket map by default for threading safety. This will break asyncore apps that rely on pysnmp sharing the same socket map with them. A solution would be to either set asyncore map to pysnmp (AsynsockDispatcher.setSocketMap()) or pass pysnmp map (AsynsockDispatcher.getSocketMap()) to asyncore. - Fix to response timeout roundup bug at CommandGenerator and NotificationOriginator code. - Oneline configuration classes made hashable to prevent memory leaks when committing them into CommandGenerator/NotificationOriginator internal repository. - Security information is now released properly in all MP modules. This might fix a significant memory leak. - Typo fix to rfc3411 confirmed class PDU members. Revision 4.1.8a, released 2007-08-14 ------------------------------------ - UNSTABLE ALPHA RELEASE. - SMI/dispatcher timeout conversion multiplier is actually 100 (1/100 sec) rather than 1/1000. This fix affects timeouts specified through SMI. - __repr__() implemented for UdpTransportTarget, CommunityData, UsmUserData in oneliner module. - Automatically initialize table index values on table management operations (SF bug ID #1671989). - Fix to carrier code: ignore BADFD socket error as it may happen upon FD closure on n-1 select() event. - Fix to MibBuilder.setMibPath() to preserve previously loaded modules intact. Otherwise loadModules() called after setMibPath() might fail with 'MIB file not found in search path' exception. - Fix to oneliner classes that now invoke unconfiguration methods on destruction. This might have caused memory leaks. - Automatically initialize SNMP-USER-BASED-SM-MIB::UsmUserSecurityName columnar object instance on creation, as stated in DESCRIPTION (SF tracker ID #1620392). - Fix to USM timeframe arithmetics (SF bug #1649032). - VACM shortcuts merged into universal add/delVacmUser() to let notifications and requests to co-exist for the same user. - At oneliners, build LCD tables keys from a hashed mix of input parameters 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 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 NotificationOriginator applications respectively. - Multi-target oneliner API-based example script added. - Ignore more socket errors in datagram-type async socket code. - AES cipher now supported (rfc3826). - Fix to messed up tagIDs of noSuchInstance and noSuchObject types. - SET Command Responder fixed to obscure access to non-existing variables by returning notWritable error (SF bug #1764839). - AsynsockDispatcher.setSocketMap() method added to facilitate pysnmp transport integration into third-party asyncore-based applications. - Fix to errorIndex generation at CommandResponder application, the value should be a one-based. Revision 4.1.7a, released 2007-02-19 ------------------------------------ - UNSTABLE ALPHA RELEASE. - Low-level debugging facility implemented. - Support UdpTransportTarget timeout and retries parameters in oneliner API. - Fix to snmpTrapOID construction at ...proxy.rfc2576.v1ToV2() function. - Fix to MibViewController.getNodeName() to take MIB module name into account (SF bug #1505847). - Do explicit check for Counter32,Unsigned32,TimeTicks,Counter64 value types in MibTableRow index conversion and in TextualConvention.prettyPrint() methods (SF bug #1506341). Handle Bits in indices as RFC2578 suggests. - Apply read-create column status to libsmi2pysnmp-generated code whenever MIB text specifies that (SF bug #1508955). - Honor and apply DISPLAY-HINT specification when building TextualConvention class at libsmi2pysnmp. - Managed Objects Instances files (smi/mibs/instances/) are now double-underscore prefixed to make them imported explicitly by these prefixed names. They used to be imported as a side-effect of Managed Objects files import what is way too hackerish. - The libsmi2pysnmp now supports future libsmi bugfix that would generate "ranges" subtree along with the legacy and ambiguous "range" one. - SMI support for fixed-length string indices implemented (SF bug #1584799, #1653908). - Managed Object Instances may now have smiRead, smiWrite, smiCreate methods to support specific value mangling. These methods, if present, would be invoked from SNMP [Agent] core instead of conventional clone() method. The reason is to separate trivial value duplication from specific Instance value mangling that may have Agent-specific side effects (such as RowStatus). - MIB table row destruction now works (SF bug #1555010). - LCD unconfiguration functions for oneliners implemented (SF bug #1635270). - unloadModules() and unexportSymbols() implemented at MibBuilder - Notification type PDU proxy code fixed to produce symmetrical conversion. - Various SNMP engine-internal caches expiration implemented. - SMI-level access control now takes effect only if AC object is passed to MIB instrumentation API. - LCD management code now uses generic MIB instrumentation features. - Fix to oneliner manager code to have individual UdpSocketTransport instance per each SnmpEngine. Multithreaded apps might fail otherwise. (SF bug ID #1586420). - Exclude the PYSNMP_MODULE_ID symbol from MIB view index, as it may get resolved into OID label instead of actual MIB object name. - Memory leak fixed in indices.OidOrderedDict implementation. - Fix to VACM shortcuts to let notifications and requests to co-exist for the same user otherwise. - Fix to ...oneliner.cmdgen.UsmUserData to support non-default ciphers. - USM now uses local notion of snmpEngineBoots/Time when authoritative and cached estimate otherwise. Also, a security fix applied to to USM time-window verification (SF bug #1649032). - Fix to notification objects resolution code at NotificationOriginator.sendNotification() - Do not raise securityLevel for USM error reports that lacks user information, as these reports could never be ciphered (SF bug #1624720). - Non-default BULK PDU params now actually applied. - SnmpEngineID default value generation algorithmic function changed to allow multiple SNMP engines running on the same host. - Documentation updated. - A handful of minor fixes applied (SourceForge tracker IDs #1537592, #1537600, #1537659, #1548208, #1560939, #1563715, #1575697, #1599220, #1615077, #1615365, #1616579). Revision 4.1.6a, released 2006-05-25 ------------------------------------ - UNSTABLE ALPHA RELEASE. - pysnmpUsmSecretAuthKey and pysnmpUsmSecretPrivKey length increased up to 256 octets. There seems no limit on this in RFC, though. - A workaround for probably broken Agents: SNMPv3 Manager code defaults ContextEngineId to SecurityEngineId whenever ContextEngineId is not reported by authoritative SNMP engine on discovery. - Use empty PDU in engine-discovery report at mpmod/rfc3412.py. - MibBuilder.loadModules() now fails on missing MIB files. - MibBuilder.exportSymbols() now accepts unnamed objects (likely Managed Objects Instances) - SNMPv2-SMI.MibScalarInstance objects now support create*/destroy* Management Instrumentation methods to pass Columnar Object creation and removal events. MibTableColumn class invoke these methods accordingly. - Fix to AsynNotificationOriginator.asyncSendNotification() callback formal parameters - Initial VACM configuration implemented according to rfc3415 Appendix 1 - tools/buildmibs.sh split-up and re-implemented as tools/build-pysnmp-mib and pysnmp-mibs/tools/rebuild-pysnmp-mibs for better usability. These and libsmi2pysnmp scripts made installable. - Types/Notifications/Groups exportSymbols() call chunking implemented in tools/libsmi2pysnmp - Initial values specified to pyasn1 types to comply with latest pyasn1 API. - Documentation improved - Minor fixes towards Python 1.5 compatibility Revision 4.1.5a, released 2005-11-04 ------------------------------------ - UNSTABLE ALPHA RELEASE. - Multi-lingual SNMP Trap/Inform Applications completed; examples added - SMI model re-designed to make a clear separation between Managed Objects and their specification (AKA Agent and Manager side) - SNMP SET Application support completed - Minor, though backward incompatible, changes to one-liner API - Many bugfixes Revision 4.1.4a, released 2005-08-16 ------------------------------------ - UNSTABLE ALPHA RELEASE. - SHA-based authentication fixed and privacy implemented - ...oneliner.cmdgen.UsmUserData constructor now takes authProtocol and privProtocol parameters in a backward incompatible manner. Revision 4.1.3a, released 2005-07-28 ------------------------------------ - UNSTABLE ALPHA RELEASE. - rfc3413 applications API changes (related to callback function behaviour). - TransportDispatcher now provides "jobs" interface to clients for better control of dispatcher's execution. - Many minor fixes. Revision 4.1.2a, released 2005-07-12 ------------------------------------ - UNSTABLE ALPHA RELEASE. - Top-level application classes renamed into longer, self descripting names for clarity. - CommandResponder & NotificationOriginator applications now uses stand-alone SnmpContext for application registration. - Many minor fixes (inspired by testing on WinXP) Revision 4.1.1a, released 2005-06-29 ------------------------------------ - UNSTABLE ALPHA RELEASE. - SNMPv3 code first published - SNMP engine and applications implemented on library level - Major re-design towards SNMPv3-style API. Revision 4.0.2a, released 2005-03-01 ------------------------------------ - Adopted to slightly changed asyncore API (as shipped with python 2,4) Revision 4.0.1a, released 2004-11-18 ------------------------------------ - Minor bug/typo fixes, mostly in example/ scripts. Revision 4.0.0a, released 2004-11-15 ------------------------------------ - UNSTABLE EARLY ALPHA RELEASE. - Major re-design and re-implementation. - Rudimental API versioning implemented to let incompatible package branches to co-exist within the same Python installation. - SMI framework designed and implemented. This framework provides 1) various access to MIB data 2) a way to implement custom MIB instrumentation objects. There's also a tool for building SMI classes from libsmi(3) output (smidump -f python). - ASN.1 subtyping machinery implemented. Now dynamic ASN.1 instances subtyping and quering becomes available. Previously, this has been done through Python classes inheritance what proved to be a wrong concept. - ASN.1 codecs framework re-designed and re-implemented aimed at a more consistent design and better performance. Highlights include abstract codec interface and serialized data caching (at encoder). - Asn1Item constraints machinery re-implemented based on Mike C. Fletcher's design and code. Now various constrains are implemented as stand-alone objects serving interested Asn1Object derivatives through some abstract protocol (that's probably the Decorator design pattern). - ASN.1 tagging facility re-implemented along the client-server design pattern. Besides this seems to be a more appropriate design, it allows an easier way for dynamic subtyping. pysnmp-4.4.12/LICENSE.rst000066400000000000000000000024611354244100700147470ustar00rootroot00000000000000Copyright (c) 2005-2019, Ilya Etingof All rights reserved. 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. 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 COPYRIGHT HOLDER 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. pysnmp-4.4.12/MANIFEST.in000066400000000000000000000003071354244100700146660ustar00rootroot00000000000000include *.rst *.txt *.md *.sh recursive-include examples *.py recursive-include docs/source *.rst *.svg *.py recursive-include docs/mibs *.txt recursive-include docs *.conf Makefile prune docs/build pysnmp-4.4.12/README.md000066400000000000000000000136021354244100700144110ustar00rootroot00000000000000 SNMP library for Python ----------------------- [![PyPI](https://img.shields.io/pypi/v/pysnmp.svg?maxAge=2592000)](https://pypi.python.org/pypi/pysnmp) [![Python Versions](https://img.shields.io/pypi/pyversions/pysnmp.svg)](https://pypi.python.org/pypi/pysnmp/) [![Build status](https://travis-ci.org/etingof/pysnmp.svg?branch=master)](https://travis-ci.org/etingof/pysnmp) [![GitHub license](https://img.shields.io/badge/license-BSD-blue.svg)](https://raw.githubusercontent.com/etingof/pysnmp/master/LICENSE.rst) This is a pure-Python, open source and free implementation of v1/v2c/v3 SNMP engine distributed under 2-clause [BSD license](http://snmplabs.com/pysnmp/license.html). The PySNMP project was initially sponsored by a [PSF](http://www.python.org/psf/) grant. Thank you! Features -------- * Complete SNMPv1/v2c and SNMPv3 support * 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/IPv4, UDP/IPv6) * Asynchronous socket-based IO API support * [Twisted](http://twistedmatrix.com), [Asyncio](https://docs.python.org/3/library/asyncio.html) and [Trollius](http://trollius.readthedocs.org/index.html) integration * [PySMI](http://snmplabs.com/pysmi/) integration for dynamic MIB compilation * Built-in instrumentation exposing protocol engine operations * Python eggs and py2exe friendly * 100% Python, works with Python 2.4 though 3.7 * MT-safe (if SnmpEngine is thread-local) Features, specific to SNMPv3 model include: * USM authentication (MD5/SHA-1/SHA-2) and privacy (DES/AES) protocols (RFC3414, RFC7860) * View-based access control to use with any SNMP model (RFC3415) * Built-in SNMP proxy PDU converter for building multi-lingual SNMP entities (RFC2576) * Remote SNMP engine configuration * Optional SNMP engine discovery * Shipped with standard SNMP applications (RC3413) Download & Install ------------------ The PySNMP software is freely available for download from [PyPI](https://pypi.python.org/pypi/pysnmp) and [GitHub](https://github.com/etingof/pysnmp.git). Just run: ```bash $ pip install pysnmp ``` to download and install PySNMP along with its dependencies: * [PyASN1](http://snmplabs.com/pyasn1/) * [PyCryptodomex](https://pycryptodome.readthedocs.io) (required only if SNMPv3 encryption is in use) * [PySMI](http://snmplabs.com/pysmi/) (required for MIB services only) Besides the library, command-line [SNMP utilities](https://github.com/etingof/snmpclitools) written in pure-Python could be installed via: ```bash $ pip install snmpclitools ``` and used in the very similar manner as conventional Net-SNMP tools: ```bash $ snmpget.py -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 demo.snmplabs.com sysDescr.0 SNMPv2-MIB::sysDescr.0 = STRING: Linux zeus 4.8.6.5-smp #2 SMP Sun Nov 13 14:58:11 CDT 2016 i686 ``` Examples -------- PySNMP is designed in a layered fashion. Top-level and easiest to use API is known as *hlapi*. Here's a quick example on how to SNMP GET: ```python from pysnmp.hlapi import * iterator = getCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) errorIndication, errorStatus, errorIndex, varBinds = next(iterator) if errorIndication: # SNMP engine errors print(errorIndication) else: if errorStatus: # SNMP agent errors print('%s at %s' % (errorStatus.prettyPrint(), varBinds[int(errorIndex)-1] if errorIndex else '?')) else: for varBind in varBinds: # SNMP response contents print(' = '.join([x.prettyPrint() for x in varBind])) ``` This is how to send SNMP TRAP: ```python from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(OctetString(hexValue='8000000001020304')), UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType(ObjectIdentity('SNMPv2-MIB', 'authenticationFailure')) ) ) if errorIndication: print(errorIndication) ``` We maintain publicly available SNMP Agent and TRAP sink at [demo.snmplabs.com](http://snmplabs.com/snmpsim/public-snmp-agent-simulator.html). You are welcome to use it while experimenting with whatever SNMP software you deal with. ```bash $ python3 examples/hlapi/asyncore/sync/manager/cmdgen/usm-sha-aes128.py SNMPv2-MIB::sysDescr.0 = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m $ $ python3 examples//hlapi/asyncore/sync/agent/ntforg/v3-inform.py SNMPv2-MIB::sysUpTime.0 = 0 SNMPv2-MIB::snmpTrapOID.0 = SNMPv2-MIB::warmStart SNMPv2-MIB::sysName.0 = system name ``` Other than that, PySNMP is capable to automatically fetch and use required MIBs from HTTP, FTP sites or local directories. You could configure any MIB source available to you (including [this one](http://mibs.snmplabs.com/asn1/)) for that purpose. For more example scripts please refer to [examples section](http://snmplabs.com/pysnmp/examples/contents.html#high-level-snmp) at pysnmp web site. Documentation ------------- Library documentation and examples can be found at the [pysnmp project site](http://snmplabs.com/pysnmp/). If something does not work as expected, please [open an issue](https://github.com/etingof/pysnmp/issues) at GitHub or post your question [on Stack Overflow](http://stackoverflow.com/questions/ask) or try browsing pysnmp [mailing list archives](https://sourceforge.net/p/pysnmp/mailman/pysnmp-users/). Bug reports and PRs are appreciated! ;-) Copyright (c) 2005-2019, [Ilya Etingof](mailto:etingof@gmail.com). All rights reserved. pysnmp-4.4.12/THANKS.txt000066400000000000000000000013001354244100700146530ustar00rootroot00000000000000Many people contributed to pysnmp by reporting problems, suggesting various improvements or submitting actual code. The list goes in a more-or-less chronological order: Cameron Laird Case Vanhorsen Jarkko Torppa Tim Kwiatkowski Carlos Ribeiro Chris Green Doobee R. Tzeck Jim Crumpler Roy Smith Mark Kilmartin Matthew W. Samsonoff John P Speno Mike C. Fletcher Wichert Akkerman Hernan Perez Masci Martin Jackson Ivan Zderadicka Randy Couey Brian Kyckelhahn Mark M Evans Filippo Giunchedi at Truelite Srl Matt Hooks Zachary Lorusso Floris Bruynooghe Laurelin of Middle Earth Robert Reese Olivier Verriest Eugene M. Kim Thanks to Python Software Foundation for granting financial support for the project. pysnmp-4.4.12/TODO.txt000066400000000000000000000046451354244100700144470ustar00rootroot00000000000000Sparse notes on major existing problems/plans * SMI issues remained include: 1) multiple OID registration should be posible for customizing Managed Objects classes 2) in MIBVIEW object model: MIB module name, MIB object name and object instance should be clearly separated. Dedicated, simple API for table cells mangling should be provided. * Walking over VACM shadowed OIDs is painfully slow * Notification filtering (RFC3413) not implemented. * MsgAndPduDispatcher should use TransportDispatcher jobs interface to handle SNMPv3 handshake * Implement prettyIn value format parser at TC * Disallow SNMP access to USM objects * Maybe MibInstrumentationController should be async what implies callback function interface. * Re-work ACL to get rid of linear search there * Implement partial context name match at isAccessAllowed() * Sort out whether pyasn1 objects should probably have either clone() or subtype() methods. * Review PDU components coercion code at proxy/rfc2576 * TextualConvention subclassing order now depends upon DisplayHint clause presense in MIB definition (for useful prettyIn/Out()). Maybe this should be re-worked. * exclude SNMP-COMMUNITY-MIB from view for better security * 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 * Rework UNIX sockets transport to make it STREAM-type. * The get-first/get-last operations of pysnmp.smi.rfc1902.ObjectIdentity() may need a means to deal only with specific node types. * redesign proto.errind.ErrorIndication * redesign PYSNMP MIB tables to better handle optional values (keys) * add RowStatus checks when reading MIB tables (LCD) * Disallow empty SET value reaching scalar MIB object * Figure out why .getUnitis() are not propagated from SNMPv2-SMI::ObjectType to response object * Extent pysmi/mibdump tool to produce MIB instances from ASN.1 MIBs * Write a tool that parses iana-private-enterprise numbers into a pysnmp MIB instance * Make mibdump producing OID->MIB indices in form of pysnmp MIB instance and JSON * Write a helper function/module based on pysnmp that reports device details based on SNMP data. In particular: description, vendor ID/name (sysObjectID), implemented MIBs (sysORTable) pysnmp-4.4.12/devel-requirements.txt000066400000000000000000000012641354244100700175140ustar00rootroot00000000000000Sphinx <= 1.6; python_version < '2.7' Sphinx > 1.6; python_version >= '2.7' trollius; python_version < '3.0' # NOTE: Twisted < 19.2.1 has a security problem in URL handling. # However, newer Twisted does not work on older Pythons. That's why # we have to pin to older Twisted here. # On the other hand, pysnmp does not use anything HTTP, however other # dependencies can rely on that. twisted < 15.4; python_version < '2.7' twisted; python_version == '2.7' twisted < 17.9; python_version == '3.0' twisted < 17.9; python_version == '3.1' twisted < 17.9; python_version == '3.2' twisted <= 17.9; python_version == '3.3' twisted <= 17.9; python_version == '3.4' twisted; python_version >= '3.5' pysnmp-4.4.12/docs/000077500000000000000000000000001354244100700140605ustar00rootroot00000000000000pysnmp-4.4.12/docs/Makefile000066400000000000000000000163721354244100700155310ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PySNMP.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PySNMP.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/PySNMP" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PySNMP" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." pysnmp-4.4.12/docs/README.txt000066400000000000000000000003421354244100700155550ustar00rootroot00000000000000You need Sphinx to build this documentation. Or you can read it in ASCII. ;) Better run: # pip install sphinx and once Sphinx is installed on your system, run: $ make html To build a copy of HTML'ed PySNMP documentation. pysnmp-4.4.12/docs/mibs/000077500000000000000000000000001354244100700150125ustar00rootroot00000000000000pysnmp-4.4.12/docs/mibs/PYSNMP-MIB.txt000066400000000000000000000031041354244100700172040ustar00rootroot00000000000000PYSNMP-MIB DEFINITIONS ::= BEGIN -- -- Top-level infrastructure of the PySNMP project enterprise MIB tree -- IMPORTS MODULE-IDENTITY, enterprises FROM SNMPv2-SMI; pysnmp MODULE-IDENTITY LAST-UPDATED "201704140000Z" ORGANIZATION "The PySNMP Project" CONTACT-INFO "E-mail: Ilya Etingof GitHub: https://github.com/etingof/pysnmp" DESCRIPTION "PySNMP top-level MIB tree infrastructure" REVISION "201704140000Z" DESCRIPTION "Updated addresses" REVISION "200505140000Z" DESCRIPTION "Initial revision" ::= { enterprises 20408 } -- -- PySNMP enterprise-specific management objects -- pysnmpObjects OBJECT IDENTIFIER ::= {pysnmp 1} pysnmpExamples OBJECT IDENTIFIER ::= {pysnmp 2} pysnmpEnumerations OBJECT IDENTIFIER ::= {pysnmp 3} pysnmpModuleIDs OBJECT IDENTIFIER ::= {pysnmpEnumerations 1} pysnmpAgentOIDs OBJECT IDENTIFIER ::= {pysnmpEnumerations 2} pysnmpDomains OBJECT IDENTIFIER ::= {pysnmpEnumerations 3} pysnmpExperimental OBJECT IDENTIFIER ::= {pysnmp 9999} -- -- Notifications -- pysnmpNotificationPrefix OBJECT IDENTIFIER ::= {pysnmp 4} pysnmpNotifications OBJECT IDENTIFIER ::= {pysnmpNotificationPrefix 0} pysnmpNotificationObjects OBJECT IDENTIFIER ::= {pysnmpNotificationPrefix 1} -- -- Conformance -- pysnmpConformance OBJECT IDENTIFIER ::= {pysnmp 5} pysnmpCompliances OBJECT IDENTIFIER ::= {pysnmpConformance 1} pysnmpGroups OBJECT IDENTIFIER ::= {pysnmpConformance 2} END pysnmp-4.4.12/docs/mibs/PYSNMP-SOURCE-MIB.txt000066400000000000000000000052261354244100700202110ustar00rootroot00000000000000PYSNMP-SOURCE-MIB DEFINITIONS ::= BEGIN IMPORTS MODULE-IDENTITY, OBJECT-TYPE FROM SNMPv2-SMI TAddress FROM SNMPv2-TC snmpTargetAddrEntry FROM SNMP-TARGET-MIB pysnmpModuleIDs FROM PYSNMP-MIB; pysnmpSourceMIB MODULE-IDENTITY LAST-UPDATED "201704140000Z" ORGANIZATION "The PySNMP Project" CONTACT-INFO "E-mail: Ilya Etingof GitHub: https://github.com/etingof/pysnmp" DESCRIPTION "This MIB module defines implementation specific objects that provide variable source transport endpoints feature to SNMP Engine and Standard SNMP Applications." REVISION "201704140000Z" DESCRIPTION "Updated addresses" REVISION "201501160000Z" -- 16 January 2015, midnight DESCRIPTION "Initial Revision" ::= { pysnmpModuleIDs 8 } -- Administrative assignments **************************************** pysnmpSourceMIBObjects OBJECT IDENTIFIER ::= { pysnmpSourceMIB 1 } pysnmpSourceMIBConformance OBJECT IDENTIFIER ::= { pysnmpSourceMIB 2 } -- -- -- The snmpSourceObjects group -- -- -- Augments SNMP-TRANSPORT-ADDRESS::snmpSourceAddressTable snmpSourceAddrTable OBJECT-TYPE SYNTAX SEQUENCE OF SnmpSourceAddrEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "A table of transport addresses to be used as a source in the generation of SNMP messages. This table contains additional objects for the SNMP-TRANSPORT-ADDRESS::snmpSourceAddressTable." ::= { pysnmpSourceMIBObjects 1 } snmpSourceAddrEntry OBJECT-TYPE SYNTAX SnmpSourceAddrEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "A transport address to be used as a source in the generation of SNMP operations. An entry containing additional management information applicable to a particular target." AUGMENTS { snmpTargetAddrEntry } ::= { snmpSourceAddrTable 1 } SnmpSourceAddrEntry ::= SEQUENCE { snmpSourceAddrTAddress TAddress } snmpSourceAddrTAddress OBJECT-TYPE SYNTAX TAddress MAX-ACCESS read-create STATUS current DESCRIPTION "This object contains a transport address. The format of this address depends on the value of the snmpSourceAddrTDomain object." ::= { snmpSourceAddrEntry 1 } -- Conformance Information ******************************************* pysnmpSourceMIBCompliances OBJECT IDENTIFIER ::= { pysnmpSourceMIBConformance 1 } pysnmpSourceMIBGroups OBJECT IDENTIFIER ::= { pysnmpSourceMIBConformance 2 } END pysnmp-4.4.12/docs/mibs/PYSNMP-USM-MIB.txt000066400000000000000000000155531354244100700176610ustar00rootroot00000000000000PYSNMP-USM-MIB DEFINITIONS ::= BEGIN IMPORTS MODULE-IDENTITY, OBJECT-TYPE FROM SNMPv2-SMI SnmpAdminString FROM SNMP-FRAMEWORK-MIB usmUserEntry FROM SNMP-USER-BASED-SM-MIB RowStatus FROM SNMPv2-TC pysnmpModuleIDs FROM PYSNMP-MIB; pysnmpUsmMIB MODULE-IDENTITY LAST-UPDATED "201704140000Z" ORGANIZATION "The PySNMP Project" CONTACT-INFO "E-mail: Ilya Etingof GitHub: https://github.com/etingof/pysnmp" DESCRIPTION "This MIB module defines objects specific to User Security Model (USM) implementation at PySNMP." REVISION "201908300000Z" DESCRIPTION "Added USM key types" REVISION "201707300000Z" DESCRIPTION "Extended authentication key size" REVISION "201704140000Z" DESCRIPTION "Updated addresses" REVISION "200505140000Z" -- 14 May 2005, midnight DESCRIPTION "The Initial Revision" ::= { pysnmpModuleIDs 1 } -- Administrative assignments **************************************** pysnmpUsmMIBObjects OBJECT IDENTIFIER ::= { pysnmpUsmMIB 1 } pysnmpUsmMIBConformance OBJECT IDENTIFIER ::= { pysnmpUsmMIB 2 } -- Implementation-specific SNMP engine configuration pysnmpUsmCfg OBJECT IDENTIFIER ::= { pysnmpUsmMIBObjects 1 } pysnmpUsmDiscoverable OBJECT-TYPE SYNTAX INTEGER { notDiscoverable(0), discoverable(1) } MAX-ACCESS read-write STATUS current DESCRIPTION "Whether SNMP engine would support its discovery by responding to unknown clients." DEFVAL { discoverable } ::= { pysnmpUsmCfg 1 } pysnmpUsmDiscovery OBJECT-TYPE SYNTAX INTEGER { doNotDiscover(0), doDiscover(1) } MAX-ACCESS read-write STATUS current DESCRIPTION "Whether SNMP engine would try to figure out the EngineIDs of its peers by sending discover requests." DEFVAL { doDiscover } ::= { pysnmpUsmCfg 2 } pysnmpUsmKeyType OBJECT-TYPE SYNTAX INTEGER { passphrase (0), master(1), localized(2) } MAX-ACCESS not-accessible STATUS current DESCRIPTION "When configuring USM user, the value of this enumeration determines how the keys should be treated. The default value "passphrase" means that given keys are plain-text pass-phrases, "master" indicates that the keys are pre-hashed pass-phrases, while "localized" stands for pre-hashed pass-phrases mixed with SNMP Security Engine ID value." DEFVAL { passphrase } ::= { pysnmpUsmCfg 3 } -- The usmUser Group ************************************************ pysnmpUsmUser OBJECT IDENTIFIER ::= { pysnmpUsmMIBObjects 3 } -- -- The pysnmpUsmSecretTable contains a database of USM users passphrases -- used for key localization. This table may be consulted during SNMP engine-ID -- autodiscovery procedure. -- pysnmpUsmSecretTable OBJECT-TYPE SYNTAX SEQUENCE OF PysnmpUsmSecretEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "The table of USM users passphrases configured in the SNMP engine's Local Configuration Datastore (LCD)." ::= { pysnmpUsmMIBObjects 2 } pysnmpUsmSecretEntry OBJECT-TYPE SYNTAX PysnmpUsmSecretEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Information about a particular USM user credentials." INDEX { IMPLIED pysnmpUsmSecretUserName } ::= { pysnmpUsmSecretTable 1 } PysnmpUsmSecretEntry ::= SEQUENCE { pysnmpUsmSecretUserName SnmpAdminString, pysnmpUsmSecretAuthKey OCTET STRING, pysnmpUsmSecretPrivKey OCTET STRING, pysnmpUsmSecretStatus RowStatus } pysnmpUsmSecretUserName OBJECT-TYPE SYNTAX SnmpAdminString (SIZE(1..32)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "The username string for which a row in this table represents a configuration." ::= { pysnmpUsmSecretEntry 1 } pysnmpUsmSecretAuthKey OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..65535)) -- no upper limit in RFC MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's authentication passphrase used for localized key generation." ::= { pysnmpUsmSecretEntry 2 } pysnmpUsmSecretPrivKey OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..65535)) -- no upper limit in RFC MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's encryption passphrase used for localized key generation." ::= { pysnmpUsmSecretEntry 3 } pysnmpUsmSecretStatus OBJECT-TYPE SYNTAX RowStatus MAX-ACCESS read-create STATUS current DESCRIPTION "Table status" ::= { pysnmpUsmSecretEntry 4 } -- -- The pysnmpUsmKeysTable contains a database of USM users' localized -- keys. -- pysnmpUsmKeyTable OBJECT-TYPE SYNTAX SEQUENCE OF PysnmpUsmKeyEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "The table of USM users localized keys configured in the SNMP engine's Local Configuration Datastore (LCD)." ::= { pysnmpUsmMIBObjects 3 } pysnmpUsmKeyEntry OBJECT-TYPE SYNTAX PysnmpUsmKeyEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Information about a particular USM user credentials." AUGMENTS { usmUserEntry } ::= { pysnmpUsmKeyTable 1 } PysnmpUsmKeyEntry ::= SEQUENCE { pysnmpUsmKeyAuthLocalized OCTET STRING, pysnmpUsmKeyPrivLocalized OCTET STRING, pysnmpUsmKeyAuth OCTET STRING, pysnmpUsmKeyPriv OCTET STRING } pysnmpUsmKeyAuthLocalized OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..64)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's localized key used for authentication." ::= { pysnmpUsmKeyEntry 1 } pysnmpUsmKeyPrivLocalized OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..64)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's localized key used for encryption." ::= { pysnmpUsmKeyEntry 2 } pysnmpUsmKeyAuth OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..64)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's non-localized key used for authentication." ::= { pysnmpUsmKeyEntry 3 } pysnmpUsmKeyPriv OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..64)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's non-localized key used for encryption." ::= { pysnmpUsmKeyEntry 4 } -- Conformance Information ******************************************* pysnmpUsmMIBCompliances OBJECT IDENTIFIER ::= { pysnmpUsmMIBConformance 1 } pysnmpUsmMIBGroups OBJECT IDENTIFIER ::= { pysnmpUsmMIBConformance 2 } END pysnmp-4.4.12/docs/net-snmpd.conf000066400000000000000000000033121354244100700166330ustar00rootroot00000000000000# To run Command Generator examples shipped with this distribution with # a Net-SNMP Agent (snmpd) listening at your localhost, the following # configuration tokens should be put into: # ... /var/lib/net-snmp/snmpd.conf (while snmpd is down) createUser usr-md5-des MD5 authkey1 DES privkey1 createUser usr-md5-none MD5 authkey1 createUser usr-none-none createUser usr-sha-des SHA authkey1 DES privkey1 createUser usr-sha-none SHA authkey1 createUser usr-sha-aes SHA authkey1 AES privkey1 createUser usr-sha-aes128 SHA authkey1 AES privkey1 createUser usr-md5-aes MD5 authkey1 AES privkey1 createUser usr-md5-aes128 MD5 authkey1 AES privkey1 # ... and the following options into /etc/snmpd/snmpd.conf com2sec local default public com2sec6 local6 default public com2secunix localunix /var/run/snmp-agent public group PySNMPGroup v1 local group PySNMPGroup v1 local6 group PySNMPGroup v1 localunix group PySNMPGroup v2c local group PySNMPGroup v2c local6 group PySNMPGroup v2c localunix group PySNMPGroup usm usr-md5-des group PySNMPGroup usm usr-md5-none group PySNMPGroup usm usr-none-none group PySNMPGroup usm usr-sha-aes group PySNMPGroup usm usr-sha-aes128 group PySNMPGroup usm usr-sha-none group PySNMPGroup usm usr-md5-aes group PySNMPGroup usm usr-md5-aes128 group PySNMPGroup usm usr-sha-des view pysnmpview included .1 access PySNMPGroup "" any noauth exact pysnmpview pysnmpview pysnmpview access PySNMPGroup "" any auth exact pysnmpview pysnmpview pysnmpview access PySNMPGroup "" any priv exact pysnmpview pysnmpview pysnmpview pysnmp-4.4.12/docs/net-snmptrapd.conf000066400000000000000000000041351354244100700175260ustar00rootroot00000000000000# To run the Notification Originator examples shipped with this distribution # against Net-SNMP's snmptrapd daemon (which actually acts the Manager role) # listening at your localhost, the following configuration # tokens should be put into: # # ... /var/lib/net-snmp/snmptrapd.conf (while snmptrapd is down) # # this is to make SNMPv3 INFORMs working createUser usr-md5-des MD5 authkey1 DES privkey1 createUser usr-md5-none MD5 authkey1 createUser usr-none-none createUser usr-sha-des SHA authkey1 DES privkey1 createUser usr-sha-none SHA authkey1 createUser usr-sha-aes SHA authkey1 AES privkey1 createUser usr-sha-aes128 SHA authkey1 AES privkey1 createUser usr-md5-aes MD5 authkey1 AES privkey1 createUser usr-md5-aes128 MS5 authkey1 AES privkey1 # this is to make SNMPv3 TRAPs working with Notification Originator having # snmpEngineId = 8000000001020304 createUser -e 0x8000000001020304 usr-md5-des MD5 authkey1 DES privkey1 createUser -e 0x8000000001020304 usr-md5-none MD5 authkey1 createUser -e 0x8000000001020304 usr-none-none createUser -e 0x8000000001020304 usr-sha-des SHA authkey1 DES privkey1 createUser -e 0x8000000001020304 usr-sha-none SHA authkey1 createUser -e 0x8000000001020304 usr-sha-aes SHA authkey1 AES privkey1 createUser -e 0x8000000001020304 usr-sha-aes128 SHA authkey1 AES privkey1 createUser -e 0x8000000001020304 usr-md5-aes MD5 authkey1 AES privkey1 createUser -e 0x8000000001020304 usr-md5-aes128 MS5 authkey1 AES privkey1 # # ... and the following options into /etc/snmpd/snmptrapd.conf # # the snmptrapd will listen on all local IPv4 & IPv6 interfaces snmpTrapdAddr udp:0.0.0.0:162,udp6:[::]:162 # this is to make SNMPv1 TRAPs and SNMPv2c TRAPs/INFORMs working authCommunity log,execute,net public # this is to make SNMPv3 TRAPs/INFORMs working authUser log usr-md5-des priv authUser log usr-md5-none authUser log usr-none-none noauth authUser log usr-sha-des priv authUser log usr-sha-none authUser log usr-sha-aes priv authUser log usr-sha-aes128 priv authUser log usr-md5-aes priv authUser log usr-md5-aes128 priv # other settings doNotRetainNotificationLogs yes doNotLogTraps no doNotFork no pysnmp-4.4.12/docs/source/000077500000000000000000000000001354244100700153605ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/.static/000077500000000000000000000000001354244100700167255ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/.static/css/000077500000000000000000000000001354244100700175155ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/.static/css/rtdimproved.css000066400000000000000000000003501354244100700225640ustar00rootroot00000000000000@import url("../pygments.css"); @import url("theme.css"); /* fix horizontal padding to accomodate adsense banners */ .wy-nav-content { padding: 1.618em 2.236em; height: 100%; /* max-width: 800px; */ margin: auto; } pysnmp-4.4.12/docs/source/.static/favicon.ico000066400000000000000000000076761354244100700210660ustar00rootroot00000000000000  ¨(@ ÃÃÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿýýýÿùùùÿôôôÿðððÿëëëÿéééÿèèèÿéééÿíííÿñññÿöööÿûûûÿþþþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿûûûÿïïïÿÜÜÜÿÆÆÆÿ¯¯¯ÿ››œÿ‹ŒŒÿ€‚ÿz{|ÿyyzÿ||}ÿ„„…ÿ‘ÿ¡¡¡ÿ¶¶¶ÿÍÍÍÿãããÿôôôÿýýýÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿüüüÿèèèÿ½½½ÿ‹‹‹ÿ__`ÿ>?@ÿ,,,ÿ'% ÿ($ÿ+%ÿ+%ÿ*#ÿ&!ÿ"ÿ ÿ$#"ÿ/01ÿFGHÿjklÿšššÿÌÌÌÿñññÿþþþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿüüüÿÛÛÛÿ‰‰‰ÿ>?@ÿÿ"ÿC3ÿmRÿl%ÿ§~.ÿ´ˆ3ÿ¹Ž7ÿ¸Ž8ÿ³‹8ÿ§‚4ÿ•t.ÿ}a%ÿ^Iÿ>0ÿ' ÿ'%"ÿQQRÿ¤¤¥ÿëëëÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿðððÿ˜™™ÿ))(ÿ& ÿeMÿ¢z'ÿ˘4ÿà¨=ÿé¯Cÿì´Gÿî¶Jÿî¸MÿïºPÿî»Rÿî¼Tÿë»Uÿç¹TÿݱNÿË¡Cÿ¨‚-ÿuWÿ>/ÿHFAÿ½½½ÿüüüÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿíííÿ‹Š‡ÿO@ÿ–r"ÿÁ‘.ÿÙ 4ÿã§9ÿä©<ÿä«?ÿä¬Aÿä®Dÿä¯Fÿä±Iÿä²Lÿå´NÿäµQÿä·Tÿä¸Vÿã¸WÿÚ¯LÿÅ–1ÿ¥zÿnUÿ¥£žÿûûûÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿùúúÿ¹±™ÿ•r$ÿ³†&ÿÇ‘*ÿ×›/ÿØ1ÿØž4ÿØ 7ÿØ¡9ÿØ£<ÿÚ¥>ÿß§@ÿبDÿØ©GÿØ«IÿجLÿØ®OÿذRÿÔ¬NÿÅ—3ÿ¸‰$ÿšt ÿ¹³¢ÿþþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÎÄ¥ÿlÿ¦{ÿ¾ˆ#ÿÌ‘'ÿÌ’*ÿÌ”-ÿÌ•/ÿÌ—2ÿ̘5ÿÓœ7ÿâ¢9ÿÌ<ÿÍŸ?ÿÌ BÿÌ¢EÿÍ£GÿÌ¥JÿÇ Dÿ·‹)ÿ¬ÿœz/ÿÔÑÆÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿéåÓÿ‹q2ÿ‹gÿ®|ÿĉ"ÿÉ"ÿ‹&ÿÂ)ÿÂŽ+ÿÁ.ÿË•1ÿÝž6ÿ”6ÿ•8ÿÁ—;ÿÁ˜=ÿš@ÿÂEÿº“;ÿ¥zÿ˜nÿ¤ŽYÿïïìÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþþùÿ´¤yÿxZÿšnÿÒ-ÿÚ¢JÿÏ”2ÿÉ‘.ÿÆ/ÿÄ‘1ÿÌ•3ÿÜž6ÿÕ9ÿØ>ÿÅœDÿÈ¢MÿÍ«[ÿгhÿ³’Dÿ”lÿ’nÿÇ¿¦ÿþþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿìçÖÿŽv=ÿƒ`ÿÈŒ5ÿùß½ÿôÄ‚ÿì¨EÿèªKÿä«Pÿä«NÿèªFÿá´bÿâºlÿäÁwÿçÉ„ÿêÑ’ÿÙ‚ÿ£3ÿgÿ¬–^ÿññëÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþÿÑǨÿd#ÿ r#ÿíЧÿþëÑÿö³Wÿõ³Uÿô¸_ÿñ¶[ÿî°NÿñÄwÿðÉ€ÿïΈÿïÒ‘ÿêÓ”ÿÁ¥`ÿ”nÿp&ÿ¶±œÿÑÒÔÿÑÒÓÿרÙÿääåÿóóóÿýýýÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿüüõÿµ¥yÿ…aÿÇ›VÿûéÑÿ÷¼kÿô²Tÿô¸_ÿð¶[ÿí°MÿñÄwÿðÉ€ÿï͈ÿîÒ‘ÿÜ€ÿ¦„7ÿˆcÿZI!ÿVN;ÿYO:ÿVM9ÿSL=ÿVRJÿiheÿ–—˜ÿØØÙÿüüüÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿòðâÿ†Oÿ›p"ÿã­_ÿö´Xÿô³Uÿô¸_ÿð¶[ÿì¯MÿðÄwÿðÉ€ÿïΈÿêÍ‹ÿÀ¡Zÿ“nÿ¢w ÿµˆ0ÿË™:ÿÓ¢AÿÒ£DÿÉžDÿµ>ÿ’s0ÿdO!ÿgaSÿÑÑÑÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿáÚÂÿ“u3ÿ½…/ÿð«Kÿõ³Vÿô¸_ÿðµZÿë®LÿðÄwÿðÉ€ÿï͈ÿÙºuÿ¡~1ÿžsÿÔš0ÿá¦:ÿá©>ÿà«Cÿá®Hÿá±Mÿá´Rÿß´SÿÇ›8ÿ™v+ÿËÆ»ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿüÿÌÀœÿœu+ÿÚBÿô³Uÿô·]ÿïµZÿê®LÿðÄwÿðÉ€ÿ鯀ÿ¹—MÿŽiÿª{ÿÊ&ÿÊ’+ÿÊ•0ÿÉ—5ÿÊš9ÿÊ>ÿÊŸCÿÉ¢Gÿ¸.ÿ±>ÿðìâÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿûûóÿ¼©yÿ´„1ÿì±Zÿ÷È‚ÿï·]ÿé®KÿñÄwÿïÈÿÑ®eÿ¢€3ÿ¤ŒJÿ”lÿÑ™AÿÔ@ÿÍ•4ÿÊ—9ÿÉ›@ÿÊ IÿΪXÿÊ«^ÿŸy$ÿŰ‚ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿôòäÿ¸œ`ÿРSÿûêÐÿòÆÿè­IÿñÄwÿä½rÿ°Œ?ÿƳuÿñîÛÿ¢‰WÿÅž`ÿùЙÿñ°Rÿî¶_ÿì¾mÿìÆ}ÿìÐŽÿŨbÿ¥…AÿðëàÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿíçÒÿÀžZÿëÓ­ÿõÕ¢ÿè¬IÿíÁsÿÆŸSÿ¾¦dÿ÷õàÿÿÿÿÿâÜÎÿ§†Hÿè¸tÿöµYÿó»eÿòÃtÿñÌ„ÿãÅÿª‰?ÿØÊ­ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿçݾÿÒ¬hÿí½qÿç­JÿÞ²dÿ½žYÿñìÑÿÿÿÿÿÿÿÿÿÿÿÿÿϦÿÁ:ÿò±Tÿó»dÿñÃtÿïÊ‚ÿâYÿï‚ÿýüûÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿù÷ìÿΪfÿæ­Qÿç­JÿÔ¨Yÿǰtÿþþöÿÿÿÿÿÿÿÿÿÿÿÿÿüûúÿʲ†ÿÞ«^ÿõÇ~ÿòÃtÿݶkÿ¿¦oÿöóíÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿøöêÿâaÿÏšEÿÑ™<ÿ¾“Hÿʶ~ÿÿÿ÷ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿöóíÿؾ‘ÿòКÿí¾oÿ̬nÿîèÛÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿùùðÿÈ»œÿ¿iÿ¾ŽEÿ«’iÿËžÿÿÿøÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿîãÏÿâ³gÿß±`ÿÞέÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿùùðÿÓÓÆÿÙÌ­ÿ׳oÿ··§ÿÌ˰ÿÿÿøÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿðëâÿ˪yÿÁ mÿáÙÉÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿùùðÿÒÒÄÿØË¬ÿ׳nÿ·¶¦ÿÍ˰ÿÿÿùÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿôôôÿÝÜÝÿÍËÍÿââãÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿôõíÿÕÖËÿ×ζÿÔ¹ƒÿÃùÿÓÓ½ÿþþùÿÿÿÿÿÿÿÿÿþýûÿÿÿþÿÿÿÿÿéêêÿÐÎÊÿÌÉÃÿáâãÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿûûûÿר×ÿ§¨«ÿ¤šŠÿ¾¢mÿ²³µÿÏÐÎÿîïîÿþýúÿîÙ²ÿçÇŒÿéÍ™ÿùòæÿçéìÿ̼ŸÿÓ½•ÿéêìÿþþþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿþþþÿìíìÿÕרÿÑǵÿ׺ƒÿÚÚÚÿãääÿö÷øÿôæÌÿéÍ—ÿùòäÿðÞ»ÿëÑ ÿÿÿÿÿóäÇÿîØ¯ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿöíÜÿêПÿýýüÿÿÿÿÿÿÿÿÿïܶÿôæÍÿÿÿÿÿüùóÿëПÿýûøÿôçÍÿðݹÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿùòåÿîØ­ÿÿþýÿÿÿÿÿÿÿÿÿòãÅÿõêÔÿÿÿÿÿüúõÿïÛ´ÿýüúÿõéÒÿôçÎÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿýüùÿõêÓÿûøñÿþþýÿÿÿÿÿúõëÿöîÛÿýüùÿùôèÿöîÜÿüû÷ÿ÷îÜÿûøñÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿûøñÿöíÙÿöíÚÿöîÛÿõíÙÿôèÎÿõëÓÿõêÒÿõëÖÿöíÚÿùôèÿÿþþÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿpysnmp-4.4.12/docs/source/.static/logo.svg000066400000000000000000000327631354244100700204210ustar00rootroot00000000000000 pysnmp-4.4.12/docs/source/changelog.rst000066400000000000000000000000661354244100700200430ustar00rootroot00000000000000 Changelog ========= .. include:: ../../CHANGES.txt pysnmp-4.4.12/docs/source/conf.py000066400000000000000000000246161354244100700166700ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # PySNMP documentation build configuration file, created by # sphinx-quickstart on Sat Jun 27 23:15:54 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'contents' # General information about the project. project = u'SNMP library for Python' copyright = u'2005-2019, Ilya Etingof ' author = u'Ilya Etingof ' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '4.4' # The full version, including alpha/beta/rc tags. release = '4.4' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. #todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' #html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'logo': 'logo.svg', 'description': '

Brewing free software for the greater good

', 'show_powered_by': False, 'github_user': 'etingof', 'github_repo': 'pysnmp', 'fixed_sidebar': True, } html_sidebars = { '**': [ 'about.html', 'navigation.html', 'relations.html', 'searchbox.html', 'donate.html', ] } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None #html_title = "PySNMP" # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = "pysnmplogo.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = '.static/favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'PySNMPdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'PySNMP.tex', u'PySNMP Documentation', u'Ilya Etingof \\textless{}etingof@gmail.com\\textgreater{}', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pysnmp', u'PySNMP Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'PySNMP', u'PySNMP Documentation', author, 'PySNMP', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Configuration for Intersphinx intersphinx_mapping = { 'python': ('https://docs.python.org/3.4/', None), 'pyasn1': ('http://snmplabs.com/pyasn1/', None), 'pysmi': ('http://snmplabs.com/pysmi/', None), 'twisted': ('https://twistedmatrix.com/documents/15.4.0/api/', None) } # this merges constructor docstring with class docstring autoclass_content = 'both' # Sort members by type autodoc_member_order = 'bysource' # Napoleon settings napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = False napoleon_use_rtype = False pysnmp-4.4.12/docs/source/contents.rst000066400000000000000000000062121354244100700177500ustar00rootroot00000000000000 SNMP library for Python ======================= .. toctree:: :maxdepth: 2 PySNMP is a cross-platform, pure-`Python `_ `SNMP `_ engine implementation. It features fully-functional SNMP engine capable to act in Agent/Manager/Proxy roles, talking SNMP v1/v2c/v3 protocol versions over IPv4/IPv6 and other network transports. Despite its name, SNMP is not really a simple protocol. For instance its third version introduces complex and open-ended security framework, multilingual capabilities, remote configuration and other features. PySNMP implementation closely follows intricate system details and features bringing most possible power and flexibility to its users. Current PySNMP stable version is 4.4. It runs with Python 2.4 through 3.7 and is recommended for new applications as well as for migration from older, now obsolete, PySNMP releases. All site documentation and examples are written for the 4.4 and later versions in mind. Older materials are still available under the obsolete section. Besides the libraries, a set of pure-Python `command-line tools `_ are shipped along with the system. Those tools mimic the interface and behaviour of popular Net-SNMP snmpget/snmpset/snmpwalk utilities. They may be useful in a cross-platform situations as well as a testing and prototyping instrument for pysnmp users. PySNMP software is free and open-source. Source code is hosted in a `Github repo `_. The library is being distributed under 2-clause BSD-style license. PySNMP library development has been initially sponsored by a `PSF `_ grant. Quick start ----------- You already know something about SNMP and have no courage to dive into this implementation? Try out quick start page! .. toctree:: :maxdepth: 2 /quick-start Documentation ------------- .. toctree:: :maxdepth: 2 /docs/tutorial /docs/api-reference Examples -------- .. toctree:: :maxdepth: 2 /examples/contents Download -------- Best way is usually to .. code-block:: bash # pip install pysnmp If that does not work for you for some reason, you might need to read the following page. .. toctree:: :maxdepth: 2 /download License ------- .. toctree:: :maxdepth: 2 /license FAQ --- .. toctree:: :maxdepth: 2 /faq Further development ------------------- We fanatically document all fixes, changes and new features in changelog. There you could also download the latest unreleased pysnmp tarball containing the latest fixes and improvements. .. toctree:: :maxdepth: 1 /changelog Our development plans and new features we consider for eventual implementation are collected in the following section. .. toctree:: :maxdepth: 2 /development Contact ------- In case of questions or troubles using PySNMP, please open up an `issue `_ at GitHub or ask at `Stack Overflow `_ . Old site archive ---------------- .. toctree:: :maxdepth: 2 /oldsite pysnmp-4.4.12/docs/source/development.rst000066400000000000000000000120411354244100700204320ustar00rootroot00000000000000 Further development ------------------- Although PySNMP is already a mature software and it is being used at many places, the ultimate goal of the project is to implement most of the useful features that SNMP standards can offer. What follows is a list of most prominent missing features that PySNMP developers are planning to put their hands on in the future. PySNMP library ++++++++++++++ #. Built-in MIB parser. PySNMP uses a data model of its own to work with information contained in MIB files. To convert ASN.1-based MIB texts into Python modules, an off-line, third-party tool is employed. As it turns out, this approach has two major drawback: one is that PySNMP users may need to pre-process MIB texts to use them with their PySNMP-based applications. Another is that LibSMI's Python driver seems to miss some information carried by MIBs. Thus the solution would be to write another MIB parser and code generator which would produce PySNMP compliant Python code right from MIB text files all by itself. **Done:** see `PySMI project `_ in conjuction with the latest PySNMP codebase. #. Reverse MIB index. The variable-bindings received by the system whilst in Manager role could be post-processed using the information kept in MIB files to include human-friendly OIDs names, tables indices and values representation. However, there is currently no provisioning in the PySNMP system for locating and loading up MIB files containing additional information on arbitrary OIDs. So the idea is to maintain an OID-to-MIB index to let PySNMP load relevant MIB automatically on demand. #. Stream sockets support. Currently, PySNMP transport subsystem only supports datagram-type network sockets. That covers UDP-over-IPv4 and UDP-over-IPv6. However, SNMP engine can potentially run over stream-oriented protocols what would let it support TCP-over-IPv4, TCP-over-IPv6 and SSL/TSL transports. Neither of these is currently implemented with PySNMP. #. AgentX implementation. We anticipate many uses of this. For instance, having AgentX protocol support in pure-Python would let us write AgentX modules in pure-Python and attach them to high-performance Net-SNMP Agent. Or we could build and maintain a fully-featured, stand-alone PySNMP-based Agent so that users would write their own AgentX extensions what would comprise a complete SNMP Agent solution at lesser effort. #. A DBMS-based SMI. Currently implemented SMI takes shape of live Python objects that let user hook up his own handler on any existing Managed Object Instance. That's flexible and working approach in many cases, however sometimes, for instance when Management Instrumentation is inherently DBMS-based, it may be more efficient to move the entire SMI/MIB subsystem into a database. PySNMP engine would talk to it through its simple and well defined SMI API. Stand-alone PySNMP-based tools ++++++++++++++++++++++++++++++ #. SNMP Proxy Forwarder. That would be a stand-alone, application-level proxy service supporting all SNMP versions, multiple network transports, Command and Notification SNMP message types. Its anticipated features include extensive configuration facilities, fine-graned access control and logging. **Done:** see `SNMP Proxy Forwarder `_. #. SNMP Trap Receiver. We see this application as a simple yet flexible SNMP TRAP collector. It would listen on network sockets of different types receiving SNMP TRAP/INFORM notifications over any SNMP version and putting all the details into a database and possibly triggering external events. #. Database backend for SNMP Simulator. We have already built a tool for simulating SNMP Agents based on a snapshot of their Management Instrumentation state. Current implementation uses a plain-text file for keeping and possibly managing the snapshot. Many users of the Simulator software requested a value variation feature to be supported so that simulated Agents would look live, not static. We consider this variation and also dependencies features would be best implemented as a relational database application. So we are planning to put some more efforts into the Simulator project as time permits. **Done:** since `snmpsim-0.2.4 `_ If you need some particular feature - please, `open a feature request `_ . Once we see a greater demand in particular area, we would re-arrange our development resources to meet it sooner. You could greater speed up the development of particular feature by sponsoring it. Please get back to us to discuss details. Contributions to the PySNMP source code is greatly appreciated as well. We require contributed code to run with Python 2.4 through the latest Python version (which is 3.7 at the time of this writing). Contributed code will be redistributed under the terms of the same `license `_ as PySNMP is. pysnmp-4.4.12/docs/source/docs/000077500000000000000000000000001354244100700163105ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/api-reference.rst000066400000000000000000000264661354244100700215650ustar00rootroot00000000000000 Library reference ================= .. toctree:: :maxdepth: 2 Dealing with many SNMP features may quickly overwhelm developers who aim at a quick and trivial task, PySNMP employs a layered architecture approach where the topmost programming API tries to be as simple as possible to allow immediate solutions for most common use cases. It will let you perform SNMP GET/SET/WALK and TRAP/INFORM operations by pasting code snippets from PySNMP documentation and example scripts right into your Python interactive session. Most of SNMP operations involve packet exchange over network. PySNMP is shipped with a set of bindings to popular asynchronous Python I/O frameworks that let you run PySNMP in parallel with other tasks your application may perform. Synchronous SNMP ---------------- Most simple and strightforward way to use PySNMP is by employing its Synchronous, blocking API. It's also the default API offered by users on *pysnmp.hlapi* sub-package import. Command Generator .. toctree:: :maxdepth: 2 /docs/hlapi/asyncore/sync/manager/cmdgen/getcmd /docs/hlapi/asyncore/sync/manager/cmdgen/setcmd /docs/hlapi/asyncore/sync/manager/cmdgen/nextcmd /docs/hlapi/asyncore/sync/manager/cmdgen/bulkcmd Notification Originator .. toctree:: :maxdepth: 2 /docs/hlapi/asyncore/sync/agent/ntforg/notification Transport configuration +++++++++++++++++++++++ The following shortcut classes convey configuration information to SNMP engine's Local Configuration Datastore (:RFC:`2271#section-3.4.2`) as well as to underlying socket API. Once committed to LCD, SNMP engine saves its configuration for the lifetime of SNMP engine object. .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.UdpTransportTarget :members: setLocalAddress .. autoclass:: pysnmp.hlapi.Udp6TransportTarget :members: setLocalAddress Asynchronous: asyncore ---------------------- The :mod:`asyncore` module is in Python standard library since ancient times. Main loop is built around :mod:`select` dispatcher, user code is invoked through callback callables. Command Generator .. toctree:: :maxdepth: 2 /docs/hlapi/asyncore/manager/cmdgen/getcmd /docs/hlapi/asyncore/manager/cmdgen/setcmd /docs/hlapi/asyncore/manager/cmdgen/nextcmd /docs/hlapi/asyncore/manager/cmdgen/bulkcmd Notification Originator .. toctree:: :maxdepth: 2 /docs/hlapi/asyncore/agent/ntforg/notification Transport configuration +++++++++++++++++++++++ .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.asyncore.UdpTransportTarget :members: setLocalAddress .. autoclass:: pysnmp.hlapi.asyncore.Udp6TransportTarget :members: setLocalAddress Asynchronous: asyncio --------------------- The :mod:`asyncio` module first appeared in standard library since Python 3.3 (in provisional basis). Its main design feature is that it makes asynchronous code looking like synchronous one. That greately simplifies development and maintanence. Command Generator .. toctree:: :maxdepth: 2 /docs/hlapi/asyncio/manager/cmdgen/getcmd /docs/hlapi/asyncio/manager/cmdgen/setcmd /docs/hlapi/asyncio/manager/cmdgen/nextcmd /docs/hlapi/asyncio/manager/cmdgen/bulkcmd Notification Originator .. toctree:: :maxdepth: 2 /docs/hlapi/asyncio/agent/ntforg/notification Transport configuration +++++++++++++++++++++++ .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.asyncio.UdpTransportTarget :members: setLocalAddress .. autoclass:: pysnmp.hlapi.asyncio.Udp6TransportTarget :members: setLocalAddress Asynchronous: trollius ---------------------- An almost compatible alternative to *asyncio* for pre-3.3 Python is `Trollius `_ module. PySNMP's `asyncio` bindings automatically work with Trolleus. Please refer to :doc:`Trollius examples ` for more information. Asynchronous: Twisted --------------------- `Twisted `_ is one of the earliest and hugely popular asynchronous I/O framework. It introduced a concept of :class:`~twisted.internet.defer.Deferred` for representing work-in-progress that is not blocking the rest of I/O operations. PySNMP provides Twisted bindings. Command Generator .. toctree:: :maxdepth: 2 /docs/hlapi/twisted/manager/cmdgen/getcmd /docs/hlapi/twisted/manager/cmdgen/setcmd /docs/hlapi/twisted/manager/cmdgen/nextcmd /docs/hlapi/twisted/manager/cmdgen/bulkcmd Notification Originator .. toctree:: :maxdepth: 2 /docs/hlapi/twisted/agent/ntforg/notification Transport configuration +++++++++++++++++++++++ .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.twisted.UdpTransportTarget :members: setLocalAddress SNMP Engine ----------- SNMP Engine is a central, stateful object used by all SNMP v3 substsems. Calls to high-level Applications API also consume SNMP Engine object on input. .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.SnmpEngine(snmpEngineID=None) Security Parameters ------------------- Calls to high-level Applications API consume Security Parameters configuration object on input. The shortcut classes described in this section convey configuration information to SNMP engine's Local Configuration Datastore (:RFC:`2271#section-3.4.2`). Once committed to LCD, SNMP engine saves its configuration for the lifetime of SNMP engine object. Community-based +++++++++++++++ Security Parameters object is Security Model specific. The :py:class:`~pysnmp.hlapi.CommunityData` class is used for configuring Community-Based Security Model of SNMPv1/SNMPv2c. .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.CommunityData(communityIndex, communityName=None, mpModel=1, contextEngineId=None, contextName='', tag='') User-based ++++++++++ The :py:class:`~pysnmp.hlapi.UsmUserData` class provides SNMPv3 User-Based Security Model configuration for SNMP v3 systems. .. autoclass:: pysnmp.hlapi.UsmUserData(userName, authKey=None, privKey=None, authProtocol=usmNoAuthProtocol, privProtocol=usmNoPrivProtocol, securityEngineId=None, authKeyType=usmKeyTypePassphrase, privKeyType=usmKeyTypePassphrase) **Authentication protocol identifiers** .. autodata:: pysnmp.hlapi.usmNoAuthProtocol .. autodata:: pysnmp.hlapi.usmHMACMD5AuthProtocol .. autodata:: pysnmp.hlapi.usmHMACSHAAuthProtocol .. autodata:: pysnmp.hlapi.usmHMAC128SHA224AuthProtocol .. autodata:: pysnmp.hlapi.usmHMAC192SHA256AuthProtocol .. autodata:: pysnmp.hlapi.usmHMAC256SHA384AuthProtocol .. autodata:: pysnmp.hlapi.usmHMAC384SHA512AuthProtocol **Privacy (encryption) protocol identifiers** .. autodata:: pysnmp.hlapi.usmNoPrivProtocol .. autodata:: pysnmp.hlapi.usmDESPrivProtocol .. autodata:: pysnmp.hlapi.usm3DESEDEPrivProtocol .. autodata:: pysnmp.hlapi.usmAesCfb128Protocol .. autodata:: pysnmp.hlapi.usmAesCfb192Protocol .. autodata:: pysnmp.hlapi.usmAesCfb256Protocol .. autodata:: pysnmp.hlapi.usmAesBlumenthalCfb192Protocol .. autodata:: pysnmp.hlapi.usmAesBlumenthalCfb256Protocol **Key material types** .. autodata:: pysnmp.hlapi.usmKeyTypePassphrase .. autodata:: pysnmp.hlapi.usmKeyTypeMaster .. autodata:: pysnmp.hlapi.usmKeyTypeLocalized .. note:: SNMP authentication and encryption keys must be at least *8* and at most *32* octets long. Transport configuration is I/O framework specific and is described in respective sections. SNMP Context ------------ SNMP engine may serve several instances of the same MIB within possibly multiple SNMP entities. SNMP context is a tool for unambiguously identifying a collection of MIB variables behind the SNMP engine. See :RFC:`3411#section-3.3.1` for details. .. note:: The SNMP context information is not tied to SNMPv3/USM user, but it is transferred in SNMPv3 message header. Legacy SNMPv1/v2c protocols do not accommodate the SNMP context information at all. To fit legacy SNMPv1/SNMPv2c systems into unified SNMPv3 architecture, the mapping procedure is introduced by :RFC:`2576#section-5.1` which essentially lets you first configure and then supply the missing items (e.g. *contextName*, *contextEngineId* and other) to the upper layers of SNMP stack based on SNMPv1/v2c *communityName* and transport endpoint. The SNMP context information necessary for this mapping procedure to operate is supplied through the :py:class:`~pysnmp.hlapi.CommunityData` object. .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.hlapi.ContextData .. _mib-services: MIB services ------------ .. _mib-variables: MIB Variables +++++++++++++ SNMP MIB variable is identified by an OBJECT IDENTIFIER (OID) and is accompanied by a value belonging to one of SNMP types (:RFC:`1902#section-2`). This pair is collectively called a variable-binding in SNMP parlance. The :py:mod:`~pysnmp.smi.rfc1902` module implements :RFC:`1902#section-2` MACRO definiitons. .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.smi.rfc1902.ObjectIdentity :members: .. autoclass:: pysnmp.smi.rfc1902.ObjectType :members: .. _notification-types: MIB notification types ++++++++++++++++++++++ SNMP Notifications are enumerated and imply including certain set of MIB variables. Notification Originator applications refer to MIBs for MIB notifications through *NOTIFICATION-TYPE* ASN.1 macro. It conveys a set of MIB variables to be gathered and reported in SNMP Notification. The :py:mod:`~pysnmp.smi.rfc1902` module implements :RFC:`1902#section-2` macro definiitons. .. toctree:: :maxdepth: 2 .. autoclass:: pysnmp.smi.rfc1902.NotificationType :members: .. _snmp-types: SNMP base types --------------- SNMP represents real-world objects it serves along with their states in form of values. Those values each belong to one of SNMP types (:RFC:`1902#section-2`) which, in turn, are based on `ASN.1 `_ data description language. PySNMP types are derived from `Python ASN.1 types `_ implementation. .. toctree:: :maxdepth: 2 .. _null: Null type +++++++++ .. autoclass:: pysnmp.proto.rfc1902.Null(initializer) :members: .. note:: The `NULL` type actually belongs to the base ASN.1 types. It is not defined in :RFC:`1902#section-2` as an SNMP type. The `Null` type is exposed through `rfc1902` module just for convenience. .. _integer32: Integer32 type ++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Integer32(initializer) :members: .. _integer: Integer type ++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Integer(initializer) :members: .. _octetstring: OctetString type ++++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.OctetString(strValue=None, hexValue=None) :members: .. _ipaddress: IpAddress type ++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.IpAddress(strValue=None, hexValue=None) ObjectIdentifier type +++++++++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.ObjectIdentifier(initializer) Counter32 type ++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Counter32(initializer) Gauge32 type ++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Gauge32(initializer) Unsigned32 type +++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Unsigned32(initializer) TimeTicks type ++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.TimeTicks(initializer) Opaque type +++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Opaque(initializer) Counter64 type ++++++++++++++ .. autoclass:: pysnmp.proto.rfc1902.Counter64(initializer) Bits type +++++++++ .. autoclass:: pysnmp.proto.rfc1902.Bits(initializer) :members: pysnmp-4.4.12/docs/source/docs/hlapi/000077500000000000000000000000001354244100700174055ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/000077500000000000000000000000001354244100700210525ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/agent/000077500000000000000000000000001354244100700221505ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/agent/ntforg/000077500000000000000000000000001354244100700234475ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/agent/ntforg/notification.rst000066400000000000000000000002121354244100700266620ustar00rootroot00000000000000 TRAP/INFORM notification ======================== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncio.sendNotification pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/manager/000077500000000000000000000000001354244100700224645ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/manager/cmdgen/000077500000000000000000000000001354244100700237215ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/manager/cmdgen/bulkcmd.rst000066400000000000000000000001571354244100700260770ustar00rootroot00000000000000 GETBULK command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncio.bulkCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/manager/cmdgen/getcmd.rst000066400000000000000000000001461354244100700257170ustar00rootroot00000000000000 GET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncio.getCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/manager/cmdgen/nextcmd.rst000066400000000000000000000001571354244100700261200ustar00rootroot00000000000000 GETNEXT command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncio.nextCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncio/manager/cmdgen/setcmd.rst000066400000000000000000000001461354244100700257330ustar00rootroot00000000000000 SET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncio.setCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/000077500000000000000000000000001354244100700212305ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/agent/000077500000000000000000000000001354244100700223265ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/agent/ntforg/000077500000000000000000000000001354244100700236255ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/agent/ntforg/notification.rst000066400000000000000000000002131354244100700270410ustar00rootroot00000000000000 TRAP/INFORM notification ======================== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncore.sendNotification pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/manager/000077500000000000000000000000001354244100700226425ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700240775ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/manager/cmdgen/bulkcmd.rst000066400000000000000000000001601354244100700262470ustar00rootroot00000000000000 GETBULK command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncore.bulkCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/manager/cmdgen/getcmd.rst000066400000000000000000000001471354244100700260760ustar00rootroot00000000000000 GET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncore.getCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/manager/cmdgen/nextcmd.rst000066400000000000000000000001601354244100700262700ustar00rootroot00000000000000 GETNEXT command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncore.nextCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/manager/cmdgen/setcmd.rst000066400000000000000000000001471354244100700261120ustar00rootroot00000000000000 SET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.asyncore.setCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/000077500000000000000000000000001354244100700222045ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/agent/000077500000000000000000000000001354244100700233025ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/agent/ntforg/000077500000000000000000000000001354244100700246015ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/agent/ntforg/notification.rst000066400000000000000000000002021354244100700300130ustar00rootroot00000000000000 TRAP/INFORM notification ======================== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.sendNotification pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/manager/000077500000000000000000000000001354244100700236165ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/manager/cmdgen/000077500000000000000000000000001354244100700250535ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/manager/cmdgen/bulkcmd.rst000066400000000000000000000001471354244100700272300ustar00rootroot00000000000000 GETBULK command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.bulkCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/manager/cmdgen/getcmd.rst000066400000000000000000000001361354244100700270500ustar00rootroot00000000000000 GET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.getCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/manager/cmdgen/nextcmd.rst000066400000000000000000000001471354244100700272510ustar00rootroot00000000000000 GETNEXT command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.nextCmd pysnmp-4.4.12/docs/source/docs/hlapi/asyncore/sync/manager/cmdgen/setcmd.rst000066400000000000000000000001361354244100700270640ustar00rootroot00000000000000 SET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.setCmd pysnmp-4.4.12/docs/source/docs/hlapi/twisted/000077500000000000000000000000001354244100700210705ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/twisted/agent/000077500000000000000000000000001354244100700221665ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/twisted/agent/ntforg/000077500000000000000000000000001354244100700234655ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/twisted/agent/ntforg/notification.rst000066400000000000000000000002121354244100700267000ustar00rootroot00000000000000 TRAP/INFORM notification ======================== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.twisted.sendNotification pysnmp-4.4.12/docs/source/docs/hlapi/twisted/manager/000077500000000000000000000000001354244100700225025ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/twisted/manager/cmdgen/000077500000000000000000000000001354244100700237375ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/docs/hlapi/twisted/manager/cmdgen/bulkcmd.rst000066400000000000000000000001571354244100700261150ustar00rootroot00000000000000 GETBULK command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.twisted.bulkCmd pysnmp-4.4.12/docs/source/docs/hlapi/twisted/manager/cmdgen/getcmd.rst000066400000000000000000000001461354244100700257350ustar00rootroot00000000000000 GET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.twisted.getCmd pysnmp-4.4.12/docs/source/docs/hlapi/twisted/manager/cmdgen/nextcmd.rst000066400000000000000000000001571354244100700261360ustar00rootroot00000000000000 GETNEXT command =============== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.twisted.nextCmd pysnmp-4.4.12/docs/source/docs/hlapi/twisted/manager/cmdgen/setcmd.rst000066400000000000000000000001461354244100700257510ustar00rootroot00000000000000 SET command =========== .. toctree:: :maxdepth: 2 .. autofunction:: pysnmp.hlapi.twisted.setCmd pysnmp-4.4.12/docs/source/docs/mib-object-instances.svg000066400000000000000000000667641354244100700230540ustar00rootroot00000000000000 image/svg+xml ifInOctets.1 ifInOctets.7 ifInOctets.2 pysnmp-4.4.12/docs/source/docs/nms-components.svg000066400000000000000000004064111354244100700220170ustar00rootroot00000000000000 image/svg+xml managed entity agent data manager data managed entity managing entity protocol protocol protocol agent data managed entity agent data pysnmp-4.4.12/docs/source/docs/oid-tree-mibs.svg000066400000000000000000000623601354244100700215000ustar00rootroot00000000000000 image/svg+xml ITU-T(0) ISO(1) Joint ITU+ISO(2) standard(0) ISO member(1) ISO Org (3) NATO (57) ... Open SoftwareFoundation(22) ... ... DoD (6) Internet (1) directory(1) management(2) experimental(3) private(4) security(5) snmpv2(6) MIB-2 system(1) interface(2) addresstranslation(3) ip(4) icmp(5) tcp(6) udp(7) egp(8) cmot(9) ..... pysnmp-4.4.12/docs/source/docs/oid-tree.svg000066400000000000000000000411771354244100700205530ustar00rootroot00000000000000 image/svg+xml ITU-T(0) ISO(1) Joint ITU+ISO(2) standard(0) ISO member(1) ISO Org (3) NATO (57) ... Open SoftwareFoundation(22) ... ... DoD (6) Internet (1) directory(1) management(2) experimental(3) private(4) security(5) snmpv2(6) pysnmp-4.4.12/docs/source/docs/pysnmp-architecture.rst000066400000000000000000000112151354244100700230500ustar00rootroot00000000000000 .. toctree:: :maxdepth: 2 PySNMP architecture =================== We can look at PySNMP's internal structure from the view point of SNMP protocol evolution. SNMP was evolving for many years from a relatively simple way to structure and retrieve data (SNMPv1/v2c) all the way to extensible and modularized framework that supports strong crypto out-of-the-box (SNMPv3). In the order from most ancient SNMP services to the most current ones, what follows are different layers of PySNMP APIs: * The most basic and low-level is SNMPv1/v2c protocol scope. Here programmer is supposed to build/parse SNMP messages and their payload -- Protocol Data Unit (PDU), handle protocol-level errors, transport issues and so on. Although considered rather complex to deal with, this API probably gives best performance, memory footprint and flexibility, unless MIB access and/or SNMPv3 support is needed. * SNMPv3 standards come with abstract service interfaces to SNMP engines and its components. PySNMP implementation adopts this abstract API to a great extent, so it can be used directly. As additional benefit, SNMP RFCs could be referred to API semantics when programming PySNMP at this level. User could implements his own SNMP application using this API. * SNMPv3 (:RFC:`3413`) introduced a concept of core "SNMP Applications". PySNMP implements them all (in *pysnmp.entity.rfc3413*), so user can base his application right on top of one (or multiple) of those SNMP core applications. * Finally, to make SNMP more simple for, at least, most frequent tasks, PySNMP comes with a high-level API to core SNMP applications and some of SNMP engine services. This API is known under the name *pysnmp.hlapi* and should be used whenever possible. Another view to PySNMP internals could be from the code standpoint: PySNMP consists of a handful of large, self-contained components with well-defined interfaces. The following figure explains PySNMP functional structure. .. image:: pysnmp-design.svg PySNMP inner components: * SNMP Engine is a central, umbrella object that controls the other components of the SNMP system. Typical user application has a single instance of SNMP Engine class possibly shared by many SNMP Applications of all kinds. As the other linked-in components tend to buildup various configuration and housekeeping information in runtime, SNMP Engine object appears to be expensive to configure to a usable state. * Transport subsystem is used for sending SNMP messages to and accepting them 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 but others are also possible. Transport Dispatcher interfaces are mostly used by Message And PDU Dispatcher. However, when using the SNMPv1/v2c-native API (the lowest-level one), these interfaces would be invoked directly. * Message and PDU Dispatcher is the locus of SNMP message processing activities. Its main responsibilities include dispatching PDUs from SNMP Applications through various subsystems all the way down to Transport Dispatcher, and passing SNMP messages coming from network up to SNMP Applications. It maintains logical connection with Management Instrumentation Controller which carries out operations on Managed Objects, here for the purpose of LCD access. * Message Processing Modules handle message-level protocol operations for present and possibly future versions of SNMP protocol. Most importantly, these include message parsing/building and possibly invoking security services whenever required. * Message Security Modules perform message authentication and/or encryption. As of this writing, User-Based (for v3) and Community (for v1/2c) modules are implemented in PySNMP. All Security Modules share standard API used by Message Processing subsystem. * Access Control subsystem uses LCD information to authorize remote access to Managed Objects. This is used when running in agent role. * A collection of MIB modules and objects that are used by SNMP engine for keeping its configuration and operational statistics. They are collectively called Local Configuration Datastore (LCD). In most cases user is expected to only deal with the high-level API to all these PySNMP components. However implementing SNMP Agents, Proxies and some non-trivial features of managers require using the Standard Applications API. In those cases general understanding of SNMP operations and SNMP Engine components would be helpful. pysnmp-4.4.12/docs/source/docs/pysnmp-design.svg000066400000000000000000001047171354244100700216400ustar00rootroot00000000000000 image/svg+xml Network MessageProcessing:v1/v2c/v3 Security:Community andUser-based Asynchronous I/O:asyncore, twisted, asyncio IPv4/v6 View-basedAccess ControlSubstsrem MIBInstrumentationController MIBBuilder MIB ViewController SNMP Engine MIBs pysnmp-4.4.12/docs/source/docs/pysnmp-hlapi-tutorial.rst000066400000000000000000000547121354244100700233350ustar00rootroot00000000000000 .. toctree:: :maxdepth: 2 Common operations ================= In this tutorial we will gradually build and run a few different SNMP command requests and notifications. We will be using PySNMP synchronous :doc:`high-level API ` which is the simplest to use. Creating SNMP Engine -------------------- SNMP engine is a central, umbrella object in PySNMP. All PySNMP operations involve :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. PySNMP app can run multiple independent SNMP engines each guided by its own *SnmpEngine* object. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> SnmpEngine() SnmpEngine(snmpEngineID=OctetString(hexValue='80004fb80567')) SNMP engine has unique identifier that can be assigned automatically or administratively. This identifier is used in SNMP protocol operations. Making SNMP query ----------------- We will send SNMP GET command to read a MIB object from SNMP agent. For that purpose we will call synchronous, high-level :py:func:`~pysnmp.hlapi.getCmd` function. Other SNMP commands can be used in a vary similar way by calling corresponding functions. .. code-block:: python >>> from pysnmp.hlapi import * >>> [ x for x in dir() if 'Cmd' in x] ['bulkCmd', 'getCmd', 'nextCmd', 'setCmd'] >>> getCmd Choosing SNMP protocol and credentials -------------------------------------- We have a choice of three SNMP protocol versions. To employ SNMP versions 1 or 2c, we pass properly initialized instance of :py:class:`~pysnmp.hlapi.CommunityData` class. For the third SNMP version we pass :py:class:`~pysnmp.hlapi.UsmUserData` class instance. SNMP community name, as well as the choice between SNMP v1 and v2c, is conveyed to SNMP LCD via :py:class:`~pysnmp.hlapi.CommunityData` object. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> CommunityData('public', mpModel=0) # SNMPv1 CommunityData('public') >>> CommunityData('public', mpModel=1) # SNMPv2c CommunityData('public') Use of :py:class:`~pysnmp.hlapi.UsmUserData` object for LCD configuration implies using SNMPv3. Besides setting up USM user name, *UsmUserData* object can also carry crypto keys and crypto protocols to SNMP engine LCD. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> UsmUserData('testuser', authKey='myauthkey') UsmUserData(userName='testuser', authKey=) >>> UsmUserData('testuser', authKey='myauthkey', privKey='myenckey') UsmUserData(userName='testuser', authKey=, privKey=) PySNMP supports MD5 and SHA message authentication algorithms, DES, AES128/192/256 and 3DES encryption algoritms. For sake of simplicity, let's use SNMPv2. Although completely insecure, it's still the most popular SNMP version in use. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), CommunityData('public'), ... Setting transport and target ---------------------------- PySNMP supports UDP-over-IPv4 and UDP-over-IPv6 network transports. In this example we will query `public SNMP Simulator `_ available over IPv4 on the Internet at *demo.snmplabs.com*. Transport configuration is passed to SNMP LCD in form of properly initialized :py:class:`~pysnmp.hlapi.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.Udp6TransportTarget` objects respectively. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... Addressing SNMP context ----------------------- SNMP context is a parameter in SNMP (v3) message header that addresses specific collection of MIBs served by SNMP engine at managed entity. SNMP engine could serve many identical MIB objects representing completely different instances of hardware or software being managed. This is where SNMP context could be used. To indicate SNMP context at high-level API a properly initialized :py:class:`~pysnmp.hlapi.ContextData` object should be used. For this example we will use the 'empty' context (default). .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... Specifying MIB object --------------------- Finally, we have to specify the MIB object we want to read. On protocol level, MIB objects are identified by OIDs, but humans tend to address them by name: .. code-block:: bash $ snmpget -v2c -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 SNMPv2-MIB::sysDescr.0 = STRING: SunOS zeus.snmplabs.com $ $ snmpget -v2c -c public demo.snmplabs.com 1.3.6.1.2.1.1.1.0 SNMPv2-MIB::sysDescr.0 = STRING: SunOS zeus.snmplabs.com Both object name and OID come from MIB. Name and OID linking is done by high-level SMI construct called *OBJECT-TYPE*. Here is an example MIB object definition for *sysUpTime* with OID ...mgmt.mib-2.system.3 and value type *TimeTicks*. .. code-block:: bash sysUpTime OBJECT-TYPE SYNTAX TimeTicks MAX-ACCESS read-only STATUS current DESCRIPTION "The time (in hundredths of a second) since the network management portion of the system was last re-initialized." ::= { system 3 } In PySNMP we use the :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` class that is responsible for MIB objects identification. *ObjectIdentity* represents ways to address MIB object from human perspective. It needs to consult MIB to enter a fully "resolved" state. ObjectIdentity could be initialized with MIB object name, after a MIB look up it starts behaving like an OID. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> x = ObjectIdentity('SNMPv2-MIB', 'system') >>> # ... calling MIB lookup ... >>> tuple(x) (1, 3, 6, 1, 2, 1, 1, 1) >>> x = ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr') >>> # ... calling MIB lookup ... >>> str(x) '1.3.6.1.2.1.1.1' MIB resolution means the service of MIB object name into OID transformation or vice versa. The :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instance represents *OBJECT-TYPE* SMI constuct in PySNMP. ObjectType is a container object that references ObjectIdentity and SNMP type instances. As a Python object it looks like a tuple of (OID, value). .. code-block:: python >>> from pysnmp.hlapi import * >>> x = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386 box')) >>> # ... calling MIB lookup ... >>> x[0].prettyPrint() 'SNMPv2-MIB::sysDescr.0' >>> x[1].prettyPrint() 'Linux i386 box' The trailing zero is an indication of MIB object *instance*. Objects described in MIBs are just declarations, they never contain any data. Data is stored in MIB object instances addressed by appending extra information (known as *index*) to MIB object identifiers. For scalar MIB objects index is '0' by convention. The *ObjectIdentity* class takes indices as its initializers. .. code-block:: python >>> x = ObjectIdentity('SNMPv2-MIB', 'system', 0) >>> # ... calling MIB lookup ... >>> tuple(x) (1, 3, 6, 1, 2, 1, 1, 1, 0) We will be reading *sysDescr* scalar MIB object instance as defined in `SNMPv2-MIB `_ module. .. code-block:: python >>> from pysnmp.hlapi import * >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) By default PySNMP will search your local filesystem for ASN.1 MIB files you refer to. It can also be configured to automatically download them from remote hosts, as :doc:`shown ` in the examples. We maintain a `collection `_ of ASN.1 MIB modules that you can use in your SNMP projects. .. note:: An "ASN.1 MIB" is a plain-text description of identifiers and types. It is the common format that is distributed by manufacturers to describe their SNMP services, and is the same format used by Perl's Net::SNMP and almost all SNMP tools. Reading scalar value -------------------- We are finally in a position to send SNMP query and hopefully receive something meaningful in response. The distinctive feature of synchronous API is that it is built around the idea of Python generator. Any function invocation ends up with a generator object. Iteration over the generator object performs actual SNMP communication. On each iteration SNMP message gets built and sent out, response is awaited, received and parsed. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysUpTime', 0))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0'), TimeTicks(44430646))]) Working with SNMP tables ------------------------ SNMP defines a concept of table. Tables are used when a single given MIB object may apply to many instances of a property. For example, properties of network interfaces are put into SNMP table. Each instance of a property is addressed by a suffix appended to base MIB object. Tables are specified in MIBs, their index (or indices) are declared via the *INDEX* clause. Table index is non-zero integer, or string or any base SNMP type. At the protocol level all indices take shape of OID parts. For humans to work with indices comfortably, SNMP management applications rely on DISPLAY-HINT clause for automatic indices conversion between their OID and SNMP type-specific, human-friendly representation. .. code-block:: bash ifEntry OBJECT-TYPE SYNTAX IfEntry INDEX { ifIndex } ::= { ifTable 1 } ifIndex OBJECT-TYPE SYNTAX InterfaceIndex ::= { ifEntry 1 } ifDescr OBJECT-TYPE SYNTAX DisplayString (SIZE (0..255)) ::= { ifEntry 2 } InterfaceIndex ::= TEXTUAL-CONVENTION DISPLAY-HINT "d" SYNTAX Integer32 (1..2147483647) In PySNMP parlance: .. code-block:: python >>> x = ObjectIdentity('IF-MIB', 'ifDescr', 123) >>> # ... calling MIB lookup ... >>> str(x) '1.3.6.1.2.1.2.2.1.2.123' Some SNMP tables are indexed by many indices. Each of these indices become parts of OID concatinated to each other and ultimately to MIB object OID. From semantic standpoint, each index reflects an important and distinct property of a MIB object. .. code-block:: bash tcpConnectionEntry OBJECT-TYPE SYNTAX TcpConnectionEntry INDEX { tcpConnectionLocalAddressType, tcpConnectionLocalAddress, tcpConnectionLocalPort, tcpConnectionRemAddressType, tcpConnectionRemAddress, tcpConnectionRemPort } ::= { tcpConnectionTable 1 } tcpConnectionLocalPort OBJECT-TYPE SYNTAX InetPortNumber ::= { tcpConnectionEntry 3 } PySNMP's :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` class takes any number of indices in human-friendly representation and converts them into full OID: .. code-block:: python >>> x = ObjectIdentity('TCP-MIB', 'tcpConnectionState', ... 'ipv4', '195.218.254.105', 41511, ... 'ipv4', '194.67.1.250', 993) >>> # ... calling MIB lookup ... >>> str(x) '1.3.6.1.2.1.6.19.1.7.1.4.195.218.254.105.41511.1.4.194.67.1.250.993' Let's read TCP-MIB::tcpConnectionState object for a TCP connection: .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('TCP-MIB', 'tcpConnectionState', ... 'ipv4', '195.218.254.105', 41511, ... 'ipv4', '194.67.1.250', 993) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.6.19.1.7.1.4.195.218.254.105.41511.1.4.194.67.1.250.993')), Integer(5))]) SNMP command operations ----------------------- SNMP allows you to request a MIB object that is "next" to the given one. That way you can read MIB objects you are not aware about in advance. MIB objects are conceptually sorted by their OIDs. This feature is implemented by the :py:func:`~pysnmp.hlapi.nextCmd` function. .. code-block:: python >>> from pysnmp.hlapi import * >>> g = nextCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), DisplayString('SunOS zeus.snmplabs.com'))]) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.2.0'), ObjectIdentity(ObjectIdentifier('1.3.6.1.4.1.8072.3.2.10')))]) Iteration over the generator object "walk" over SNMP agent's MIB objects. SNMPv2c introduced significant optimization to the *GETNEXT* command - the revised version is called *GETBULK* and is capable to gather and respond a bunch of "next" MIB objects at once. Additional non-repeaters and max-repetitions parameters can be used to influence MIB objects batching. PySNMP hides this *GETBULK* optimization at the protocol level, the :py:func:`~pysnmp.hlapi.bulkCmd` function exposes the same generator API as *getNext()* for convenience. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> N, R = 0, 25 >>> g = bulkCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... N, R, ... ObjectType(ObjectIdentity('1.3.6'))) >>> >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), DisplayString('SunOS zeus.snmplabs.com'))]) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.2.0'), ObjectIdentifier('1.3.6.1.4.1.20408'))]) Python generators can not only produce data, but it is also possible to send data into running generator object. That feature is used by the high-level API to repeat the same SNMP operation for a new set of MIB objects. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = nextCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('IF-MIB', 'ifTable'))) >>> >>> g.send([ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets'))]) (None, 0, 0, [(ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) You could operate on many unrelated MIB object just by listing them in a single PDU. Response PDU will carry a list of MIB objects and their values in exactly the same order as they were in request message. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysUpTime', 0)) ... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), DisplayString('SunOS zeus.snmplabs.com')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0'), TimeTicks(44430646))]) Configuration management part of SNMP relies on SNMP *SET* command. Although its implementation on managed entity's side proved to be somewhat demanding (due to locking and transactional behavior requirements). So vendors tend to leave it out thus rendering managed entity being read-only. PySNMP supports *SET* uniformly through :py:func:`~pysnmp.hlapi.setCmd` function. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = setCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386') ... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), DisplayString('Linux i386'))]) Sending SNMP notifications -------------------------- Managed entity could send unsolicited messages to the managing entity. That is called notification in SNMP. Notifications help reduce polling, what may become a problem for large networks. SNMP notifications are enumerated and each has definite semantics. This is done through a special, high-level SMI construct called *NOTIFICATION-TYPE*. Like *OBJECT-TYPE*, that defines a MIB object, *NOTIFICATION-TYPE* has a unique OID, but instead of SNMP value references a sequence of other MIB objects. These MIB objects are specified with the *OBJECTS* clause and when notification is being sent, their current values are included into the notification message. .. code-block:: bash linkUp NOTIFICATION-TYPE OBJECTS { ifIndex, ifAdminStatus, ifOperStatus } STATUS current DESCRIPTION "..." ::= { snmpTraps 4 } To model *NOTIFICATION-TYPE* construct in PySNMP, we have the :py:class:`~pysnmp.smi.rfc1902.NotificationType` class that is a container object. It is identified by the :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` class and reference a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances. From behavior standpoint, *NotificationType* looks like a sequence of *ObjectType* class instances. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> x = NotificationType(ObjectIdentity('IF-MIB', 'linkUp')) >>> # ... calling MIB lookup ... >>> >>> [ str(y) for x in n ] ['SNMPv2-MIB::snmpTrapOID.0 = 1.3.6.1.6.3.1.1.5.3', 'IF-MIB::ifIndex = ', 'IF-MIB::ifAdminStatus = ', 'IF-MIB::ifOperStatus = '] Sending notification with PySNMP is not much different than sending SNMP command. The difference is in how PDU var-binds are built. There are two different kinds of notifications in SNMP: *trap* and *inform*. With *trap*, agent-to-manager communication is one-way - no response or acknowledgement is sent. .. code-block:: python >>> from pysnmp.hlapi import * >>> >>> g = sendNotification(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'trap', ... NotificationType(ObjectIdentity('IF-MIB', 'linkUp'), instanceIndex=(123,)) ... ) >>> next(g) (None, 0, 0, []) The *inform* notification is much like a command. The difference is in PDU format. Informs are used for manager-to-manager communication as well as for agent-to-manager. >>> from pysnmp.hlapi import * >>> >>> g = sendNotification(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'inform', ... NotificationType(ObjectIdentity('IF-MIB', 'linkUp'), instanceIndex=(123,)) ... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0'), TimeTicks(0)), ObjectType(ObjectIdentity('1.3.6.1.6.3.1.1.4.1.0'), ObjectIdentity('1.3.6.1.6.3.1.1.5.4')), ObjectType(ObjectName('1.3.6.1.2.1.2.2.1.1.123'), Null('')), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.7.123'), Null('')), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.8.123'), Null(''))]) In the latter example you can see MIB objects (ifIndex, ifAdminStatus, ifOperStatus) being automatically expanded from IF-MIB::linkUp notification. To address specific row of SNMP table objects by index, the index part of MIB objects could be passed to *NotificationType* via *instanceIndex* parameter. As you can see, the actual values for expanded MIB objects are NULLs. That's because in these examples our simple scripts do not have access to those MIB objects. We can supply that missing information by passing *NotificationType* a dictionary-like object that maps MIB object OIDs to current values. >>> from pysnmp.hlapi import * >>> >>> mib = {ObjectIdentifier('1.3.6.1.2.1.2.2.1.1.123'): 123, ... ObjectIdentifier('1.3.6.1.2.1.2.2.1.7.123'): 'testing', ... ObjectIdentifier('1.3.6.1.2.1.2.2.1.8.123'): 'up'} >>> >>> g = sendNotification(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'inform', ... NotificationType(ObjectIdentity('IF-MIB', 'linkUp'), instanceIndex=(123,), objects=mib) ... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0'), TimeTicks(0)), ObjectType(ObjectIdentity('1.3.6.1.6.3.1.1.4.1.0'), ObjectIdentity('1.3.6.1.6.3.1.1.5.4')), ObjectType(ObjectName('1.3.6.1.2.1.2.2.1.1.123'), InterfaceIndex(123)), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.7.123'), Integer(3)), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.8.123'), Integer(1))]) High-volume messaging --------------------- When in comes to managing large network, reading MIB objects sequentially introduces latency. By some point the latency becomes intolerable. Solutions to parallelize queries are well known - you could do that by offloading individual operations into multiple processes, or multiple threads of execution or build your application around the asynchronous I/O model. Compared to other solutions, asynchronous model is most lightweight and scalable. The idea is simple: never wait for I/O - do something else whenever possible. The back side of this is that execution flow becomes non-linear what hurts program analysis by human reader. PySNMP high-level API is adapted to work with three popular asynchronous I/O frameworks - :mod:`asyncore`, :mod:`twisted` and :mod:`asyncio`. Please, refer to PySNMP :doc:`library reference ` and :doc:`examples ` for more information on asynchronous API. pysnmp-4.4.12/docs/source/docs/snmp-apps.svg000066400000000000000000000254171354244100700207600ustar00rootroot00000000000000 image/svg+xml CommandGenerator NotificationReceiver ProxyForwarder CommandResponder NotificationOriginator SNMP Engine Network pysnmp-4.4.12/docs/source/docs/snmp-design.rst000066400000000000000000000244741354244100700213010ustar00rootroot00000000000000 .. toctree:: :maxdepth: 2 SNMP design =========== Contrary to what the name might suggest, SNMP is much more than just a protocol for moving management data. Over time it has grown to be more complex than its initial designers probably planned it. Terminology and entities ------------------------ The network management field has its own specific terminology for various components of a network management architecture, and so we adopt that terminology here. The peculiarity of this terminology is that the word "management" is greatly overused. So bare with it. There are three principle components of a network management architecture: a managing entity, the managed entity, and a network management protocol. .. image:: nms-components.svg * The managing entity is an application running in a centralized network management station (NMS). It is the managing entity that controls the collection, processing, analysis, and/or display of network management information. It is here that actions are initiated to control network behavior and here that the human network administrator interacts with the network devices. * A managed entity is typically hardware or software application that resides on a managed network. It enumerates and formalizes some of its properties and states, important for healthy operation, thus making them available to the managing entity. For example, a managed entity could be a host, router, switch, printer, or any other device. * The third piece of a network management system is the network management protocol. The protocol runs between the managing entity and the managed entity, allowing the managing entity to query the status of managed entity and make the latter carrying out actions via its agents. Structure and components ------------------------ SNMP consists of four parts: * Definitions of network management objects known as MIB objects. Management information is represented as a collection of managed objects that together form a virtual information store, known as the Management Information Base (MIB). A MIB object might be a counter, descriptive information such as software version; status information such as whether or not a device is healthy, or protocol-specific information such as a routing path to a destination. MIB objects thus define the management information maintained by a managed node. Related MIB objects are gathered into so-called MIB modules. * Data definition language, called SMI (Structure of Management Information) that introduces base data types, allows for creating their subtypes and more complex data structures. MIB objects are expressed in this data definition language. * Protocol (SNMP) for conveying information and commands between a managing and managed entities. SNMP is designed around a client-server model. What's interesting that both managing and managed entities contain client and server components. * Extensible security framework and system administration capabilities. The latter features were completely absent in SNMP versions prior to SNMPv3. Data types ---------- SMI introduces eleven base data types used for representing managed objects states. They are either pure ASN.1 types or their specializations. Pure ASN.1 types: * INTEGER * OCTET STRING * OBJECT IDENTIFIER ASN.1 is a really aged and quite complex set of standards that deals with structuring and serializing data in a portable way. SNMP-specific subtypes of those base ASN.1 types are: * Integer32/Unsigned32 - 32-bit integer * Counter32/Counter64 - ever increasing number * Gauge32 - positive, non-wrapping 31-bit integer * TimeTicks - time since some event * IPaddress - IPv4 address * Opaque - uninterpreted ASN.1 string In addition to these scalar types, SNMP defines a way to collect them into ordered arrays. From these arrays 2-d tables could be built. PySNMP relies on the `PyASN1 `_ package for modeling all SNMP types. With PyASN1, instances of ASN.1 types are represented by Python objects that look like either a string or an integer. We can convert PyASN1 objects into Python types and back. PyASN1 objects can participate in basic arithmetic operations (numbers) or in operations with strings (concatenation, subscription etc). All SNMP base types are immutable like their Python counterparts. .. code-block:: python >>> from pyasn1.type.univ import * >>> Integer(21) * 2 Integer(42) >>> Integer(-1) + Integer(1) Integer(0) >>> int(Integer(42)) 42 >>> OctetString('Hello') + ', ' + >>> OctetString(hexValue='5079534e4d5021') OctetString('Hello, PySNMP!') Users of PySNMP library may encounter PyASN1 classes and objects when passing data to or receiving data from PySNMP. The one data type we will discuss in more detail shortly is the OBJECT IDENTIFIER data type, which is used to name an object. With this system, objects are identified in a hierarchical manner. Object Identifier +++++++++++++++++ OIDs are widly used in computing for identifying objects. This system can be depicted as a tree whose nodes are assigned by different organizations, knowledge domains, types of concepts or objects, concrete instances of objects. From human perspective, an OID is a long sequence of numbers, coding the nodes, separated by dots. .. image:: oid-tree.svg Each 'branch' of this tree has a number and a name, and the complete path from the top of the tree down to the point of interest forms the name of that point. This complete path is the OID, the "identifier of an object" respectively. Nodes near the top of the tree are of an extremely general nature. Top level MIB object IDs (OIDs) belong to different standard organizations. Vendors define private branches including managed objects for their own products. At the top of the hierarchy are the International Organization for Standardization (ISO) and the Telecommunication Standardization Sector of the International Telecommunication Union (ITU-T), the two main standards organizations dealing with ASN.1, as well as a brach for joint efforts by these two organizations. In PyASN1 model, OID looks like an immutable sequence of numbers. Like it is with Python tuples, PyASN1 OID objects can be concatinated or split apart. Subscription operation returns a numeric sub-OID. .. code-block:: python >>> from pyasn1.type.univ import * >>> internetId = ObjectIdentifier((1, 3, 6, 1)) >>> internetId ObjectIdentifier('1.3.6.1') >>> internetId[2] 6 >>> [ x for x in internetId ] [1, 3, 6, 1] >>> internetId + (2,) ObjectIdentifier('1.3.6.1.2') >>> internetId[1:3] ObjectIdentifier('3.6') >>> internetId[1] >>> = 2 ... TypeError: object does not support item assignment Collections of objects ---------------------- Management Information Base (MIB) can be thought of as a formal description of a collection of relevant managed objects whose values collectively reflect the current "state" of some subsystem at a managed entity. These values may be queried, modified by or reported to a managing entity by sending SNMP messages to the agent that is executing in a managed node. For example, the typical objects to monitor on a printer are the different cartridge states and maybe the number of printed files, and on a switch the typical objects of interest are the incoming and outgoing traffic as well as the rate of package loss or the number of packets addressed to a broadcast address. Every managed device keeps a database of values for each of the definitions written in the MIB. So, the available data is actually not dependent on the database, but on the implementation. It is important to realize that MIB files never contain data, they are functionally similar to database schemas rather than data stores. To organize MIB modules and objects properly, all the manageable features of all products (from each vendor) are arranged in this MIB tree structure. Each MIB module and object is uniquely identified by an Object Identifier. Both SNMP managed and managing entities could consume MIB information. * Managing entity + Looks up OID by MIB object name + Casts value to proper type of MIB object + Humans read comments left by other humans * Managed entity + Implements MIB objects in code From human perspective, MIB is a text file written in a subset of ASN.1 language. We maintain `a collection `_ of 9000+ MIB modules that you can use for your projects. PySNMP converts ASN.1 MIB files into Python modules, then SNMP engine loads those modules at runtime on demand. PySNMP MIB modules are universal -- the same module can be consumed by both managed and managing entities. MIB conversion is performed automatically by PySNMP, but technically, it is handled by PySNMP sister project called `PySMI `_. However you can also perform said conversion by hand with PySMI's *mibdump.py* tool. Protocol operations ------------------- SNMP is designed around a client-server model. Both managing and managed entities contain client and server components. Clients and servers exchange data in a name-value form. Values are strongly typed. Central to protocol entity is *SNMP engine* that coordinates workings of all SNMP components. .. image:: snmp-engine.svg Two modes of protocol operation are defined: * Request-response messages * Unsolicited messages Protocol carries SNMP messages. Besides header information used for protocol operations, management information is transferred in so-called Protocol Data Units (PDU). Seven PDU types are defined in SNMP addressing conceptually different operations to be performed by either managing or managed entities (Manager or Agent repectively). * Manager-to-agent + GetRequest, SetRequest, GetNextRequest, GetBulkRequest, InformRequest * Manager-to-manager + InformRequest, Response * Agent-to-manager + SNMPv2-Trap, Response Core applications ----------------- The standard (:RFC:`3413`) identifies a few "standard" SNMP applications that are associated with either managing or managed entities. .. image:: snmp-apps.svg PySNMP implements all these standard applications (via *Native SNMP API*) carefully following RFCs and their abstract service interfaces. The backside of this approach is that it's way too detailed and verbose for most SNMP tasks. To make SNMP easy to use, PySNMP introduces *High-level SNMP API*. pysnmp-4.4.12/docs/source/docs/snmp-engine.svg000066400000000000000000000467431354244100700212670ustar00rootroot00000000000000 image/svg+xml Network Dispatcher MessageProcessing TimelinessAuthenticationEncryption Transport subsystem AccessControl PDU pysnmp-4.4.12/docs/source/docs/snmp-history.rst000066400000000000000000000112141354244100700215150ustar00rootroot00000000000000 .. toctree:: :maxdepth: 2 SNMP history ============ In the early days of networking, when computer networks were research artifacts rather than a critical infrastructure used by almost every second human on Earth, "network management" was practically unknown. Whenever one encountered a network problem, he might run a few pings to locate the source of the problem and then modify system settings, reboot hardware or software, or call a remote colleague to check console at the machine room. An interesting discussion of the first major "crash" of the ARPAnet in 1980, long before network management tools were available, and the efforts taken to recover from and understand the crash can be read in :RFC:`789`. The astonishment of the engineers taking part in post-mortem investigation could be read between the lines. As the public Internet and private intranets have grown from small networks into a large global infrastructure, the need to more systematically manage the huge number of hardware and software components within these networks has grown more important as well. SNMP was quickly designed and deployed by a group of university network researchers and users at a time when the need for network management was becoming painfully clear. SNMP milestones: * Research project, successor of SGMP * SNMPv1 in 1988: initial revision * SNMPv2 in 1993: improvements * SNMPv3 in 1999: full redesign * SNMPv3: backward compatible * SNMPv3: full Internet standard (STD0062) SNMP was initially thought as an interim solution to fill the need for network management tool while a more theoretically sound system was being developed by the ISO. Anticipating the transition to the new network management system, SNMP designers made SNMP modular. Although that transition never occurred, the modularity of SNMP help it evolving through three major versions and found widespread use and acceptance. The IETF recognizes SNMP version 3 as defined by :RFC:`3411` .. :RFC:`3418` as the current standard version of SNMP. The IETF has designated SNMPv3 a full Internet standard, the highest maturity level for an RFC. In practice, SNMP implementations often support multiple versions: typically SNMPv1, SNMPv2c, and SNMPv3 Is it still relevant? --------------------- Considering how old SNMP is you might be wondering why it is still in use and is there a more modern alternative? Apparently, SNMP is still the primary way to do performance and fault management. SNMP is universally supported by all networking hardware manufactures and network management applications. Perhaps one reason for SNMP being so tenacious is that, considering SNNP's wide deployment, it takes too much effort to migrate to anything else. But the other reason is that no significant drawbacks have been found in SNMP at least in the areas of fault and performance management. Additionally, SNMP is free and not controlled by any particular vendor. No copyright or licensing fees are required, so anyone can use it or build SNMP products on it. Despite significant efforts made by technology companies and standards bodies over all these years, no other network monitoring standard was adopted so far. The most prominent open alternative is probably NETCONF (:RFC:`6241`). However it mostly targets configuration management tasks rather than fault or performance monitoring. Additionally, NETCONF is significantly more resource intensive than SNMP is. It is obviously possible to for everybody to come up with its own ad-hoc management system. That can be done very easily on top of HTTPS/JSON, for example. However that would only work with your application. Also, SSL engine might be heavier on resources. Current and future uses ----------------------- As for current SNMP deployment, its virtually impossible to estimate how many SNMP-enabled devices run on the modern Internet today. For example, every home router and most of the desktop printers have embedded SNMP agent inside. Expanding on that, you may found SNMP useful for your home network monitoring. For instance you could easily setup an open source network monitoring application to watch, collect and graph bandwidth utilization of your home Wi-Fi router. A significant innovation might be coming in the following years. And that is Internet of Things. All those small and low-power gadgets need to be monitored and managed. And that may bring new life to the SNMP technology. Almost three decades ago SNMP was designed for heavily resource-constrained computers of that time. Later on the computers grew in power and resources. But now we are back to building a massive amount of low-power computers for "things" where original lightweight and well-understood SNMP can serve us again! pysnmp-4.4.12/docs/source/docs/tutorial.rst000066400000000000000000000002441354244100700207050ustar00rootroot00000000000000 Documentation ============= .. toctree:: :maxdepth: 2 /docs/snmp-history /docs/snmp-design /docs/pysnmp-architecture /docs/pysnmp-hlapi-tutorial pysnmp-4.4.12/docs/source/download.rst000066400000000000000000000043041354244100700177220ustar00rootroot00000000000000Download PySNMP =============== .. toctree:: :maxdepth: 2 The PySNMP software is provided under terms and conditions of BSD-style license, and can be freely downloaded from `PyPI `_ or GitHub (`master branch `_). Besides official releases, it's advisable to try the cutting-edge development code that could be taken from PySNMP `source code repository `_. It may be less stable in regards to general operation and changes to public interfaces, but it's first to contain fixes to recently discovered bugs. The best way to obtain PySNMP and dependencies is to run: .. code-block:: bash $ pip install pysnmp or .. code-block:: bash $ easy_install pysnmp In case you do not have the easy_install command on your system but still would like to use the on-line package installation method, please install `setuptools `_ package by downloading and running `ez_setup.pz `_ bootstrap: .. code-block:: bash # wget https://bootstrap.pypa.io/ez_setup.py # python ez_setup.py In case you are installing PySNMP on an off-line system, the following packages need to be downloaded and installed for PySNMP to become operational: * `PyASN1 `_, used for handling ASN.1 objects * `PySNMP `_, SNMP engine implementation Optional, but recommended: * `PyCryptodomex `_, used by SNMPv3 crypto features * `PySMI `_ for automatic MIB download and compilation. That helps visualizing more SNMP objects * `Ply `_, parser generator required by PySMI The installation procedure for all the above packages is as follows (on UNIX-based systems): .. code-block:: bash $ tar zxf package-X.X.X.tar.gz $ cd package-X.X.X # python setup.py install # cd .. # rm -rf package-X.X.X In case of any issues, please open a `GitHub issue `_ so we could try to help out. pysnmp-4.4.12/docs/source/examples/000077500000000000000000000000001354244100700171765ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/contents.rst000066400000000000000000000117251354244100700215730ustar00rootroot00000000000000 Example scripts =============== .. toctree:: :maxdepth: 2 SNMP is not simple (PySNMP implementation takes over 15K lines of Python code), but PySNMP tries to hide the complexities and let you carry out typical SNMP operations in a quick and intuitive way. PySNMP offers three groups of programming interfaces to deal with SNMP protocol. In the order from most concise to most detailed those APIs follow. High-level SNMP --------------- The so called high-level API (hlapi) is designed to be simple, concise and suitable for the most frequent operations. For that matter only Command Generator and Notification Originator Applications are currently wrapped into a nearly one-line Python expression. It comes in several flavours: one synchronous and a bunch of bindings to popular asynchronous I/O frameworks. Those varieties of APIs bring subtile differences, mostly to better match particular I/O framework customs. Unless you have a very specific task, the high-level API might solve your SNMP needs. .. toctree:: :maxdepth: 2 /examples/hlapi/asyncore/sync/contents .. toctree:: :maxdepth: 2 /examples/hlapi/asyncore/contents .. toctree:: :maxdepth: 2 /examples/hlapi/asyncio/contents .. toctree:: :maxdepth: 2 /examples/hlapi/trollius/contents .. toctree:: :maxdepth: 2 /examples/hlapi/twisted/contents Native SNMP API --------------- Complete implementation of all official Standard SNMP Applications. It should let you implement any SNMP operation defined in the standard at the cost of working at a somewhat low level. This API also comes in several transport varieties depending on I/O framework being used. .. toctree:: :maxdepth: 2 /examples/v3arch/asyncore/contents /examples/v3arch/asyncio/contents /examples/v3arch/trollius/contents /examples/v3arch/twisted/contents Packet-level SNMP ----------------- In cases where performance is your top priority and you only need to work with SNMP v1 and v2c systems and you do not mind writing much more code, then there is a low-level API to SNMP v1/v2c PDU and PySNMP I/O engine. There's practically no SNMP engine or SMI infrastructure involved in the operations of these almost wire-level interfaces. Although MIB services can still be used separately. A packet-level API-based application typically manages both SNMP message building/parsing and network communication via one or more transports. It's fully up to the application to handle failures on message and transport levels. Command Generator +++++++++++++++++ .. toctree:: /examples/v1arch/asyncore/manager/cmdgen/fetching-variables /examples/v1arch/asyncore/manager/cmdgen/modifying-variables /examples/v1arch/asyncore/manager/cmdgen/walking-operations /examples/v1arch/asyncore/manager/cmdgen/transport-tweaks Command Responder +++++++++++++++++ .. toctree:: /examples/v1arch/asyncore/agent/cmdrsp/agent-side-mib-implementations Notification Originator +++++++++++++++++++++++ .. toctree:: /examples/v1arch/asyncore/agent/ntforg/transport-tweaks Notification Receiver +++++++++++++++++++++ .. toctree:: /examples/v1arch/asyncore/manager/ntfrcv/transport-tweaks Low-level MIB access -------------------- .. toctree:: /examples/smi/manager/browsing-mib-tree /examples/smi/agent/implementing-mib-objects Using these examples -------------------- Before doing cut&paste of the code below into your Python interpreter, make sure to install pysnmp and its dependencies by running pip or easy_install: :: # pip pysnmp There's a public, multilingual SNMP Command Responder and Notification Receiver configured at `demo.snmplabs.com `_ to let you run PySNMP examples scripts in a cut&paste fashion. If you wish to use your own SNMP Agent with these scripts, make sure to either configure your local snmpd and/or snmptrapd or use a valid address and SNMP credentials of your SNMP Agent in the examples to let them work. Should you want to use a MIB to make SNMP operations more human-friendly, you are welcome to search for it and possibly download one from our `public MIB repository `_. Alternatively, you can configure PySNMP to fetch and cache required MIBs from there automatically. If you find your PySNMP application behaving unexpectedly, try to enable a /more or less verbose/ built-in PySNMP debugging by adding the following snippet of code at the beginning of your application: .. code-block:: python from pysnmp import debug # use specific flags or 'all' for full debugging debug.setLogger(debug.Debug('dsp', 'msgproc', 'secmod')) Then run your app and watch stderr. The Debug initializer enables debugging for a particular PySNMP subsystem, 'all' enables full debugging. More specific flags are: * io * dsp * msgproc * secmod * mibbuild * mibview * mibinstrum * acl * proxy * app For more details on PySNMP programming model and interfaces, please refer to :doc:`library documentation`. pysnmp-4.4.12/docs/source/examples/hlapi/000077500000000000000000000000001354244100700202735ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/000077500000000000000000000000001354244100700217405ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/agent/000077500000000000000000000000001354244100700230365ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/agent/ntforg/000077500000000000000000000000001354244100700243355ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/agent/ntforg/advanced-topics.rst000066400000000000000000000010311354244100700301260ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Notification Originator -------------------------------- .. include:: /../../examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/agent/ntforg/common-notifications.rst000066400000000000000000000007241354244100700312310ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Common notifications -------------------- .. include:: /../../examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/contents.rst000066400000000000000000000045671354244100700243430ustar00rootroot00000000000000 Asynchronous: asyncio ===================== The :mod:`asyncio` module first appeared in standard library since Python 3.3 (in provisional basis). Its main design feature is that it makes asynchronous code looking like synchronous one thus eliminating "callback hell". With `asyncio` built-in facilities, you could run many SNMP queries in parallel and/or sequentially, interleave SNMP queries with I/O operations with other systems. See `asyncio resources `_ repository for other `asyncio`-compatible modules. In most examples approximate analogues of well known Net-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net-SNMP tools, better understanding what example code doe Here's a quick example on a simple SNMP GET by high-level API: .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/v1-get.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/v1-get.py :start-after: """# :language: python To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python More examples on Command Generator API usage follow. .. toctree:: /examples/hlapi/asyncio/manager/cmdgen/snmp-versions /examples/hlapi/asyncio/manager/cmdgen/walking-operations /examples/hlapi/asyncio/manager/cmdgen/advanced-topics Sending SNMP TRAP's and INFORM's is as easy with PySNMP library. The following code sends SNMP TRAP: .. include:: /../../examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py :start-after: """# :language: python More examples on Notification Originator API usage follow. .. toctree:: /examples/hlapi/asyncio/agent/ntforg/common-notifications /examples/hlapi/asyncio/agent/ntforg/advanced-topics More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/manager/000077500000000000000000000000001354244100700233525ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/manager/cmdgen/000077500000000000000000000000001354244100700246075ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/manager/cmdgen/advanced-topics.rst000066400000000000000000000017001354244100700304030ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Command Generator -------------------------- .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/manager/cmdgen/snmp-versions.rst000066400000000000000000000014301354244100700301620ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/v1-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/v1-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncio/manager/cmdgen/walking-operations.rst000066400000000000000000000007231354244100700311600ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Walking operations ------------------ .. include:: /../../examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/000077500000000000000000000000001354244100700221165ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/agent/000077500000000000000000000000001354244100700232145ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/agent/ntforg/000077500000000000000000000000001354244100700245135ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/agent/ntforg/advanced-topics.rst000066400000000000000000000024141354244100700303120ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Notification Originator -------------------------------- .. include:: /../../examples/hlapi/asyncore/agent/ntforg/multiple-traps-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/agent/ntforg/multiple-traps-at-once.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/agent/ntforg/multiple-informs-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/agent/ntforg/multiple-informs-at-once.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/agent/ntforg/running-multiple-snmp-engines-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/agent/ntforg/running-multiple-snmp-engines-at-once.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/agent/ntforg/common-notifications.rst000066400000000000000000000007271354244100700314120ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Common notifications -------------------- .. include:: /../../examples/hlapi/asyncore/agent/ntforg/default-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/contents.rst000066400000000000000000000041401354244100700245040ustar00rootroot00000000000000 Asynchronous: asyncore ====================== With :mod:`asyncore` API your scripts get CPU time on :mod:`socket` events being watched for by :mod:`select` dispatcher. Your code live mostly in isolated functions (or any callable objects). In most examples approximate analogues of well known Net-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net-SNMP tools, better understanding what example code doe Here's a quick example on a simple SNMP GET by high-level API: .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/v2c-get.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/v2c-get.py :start-after: """# :language: python To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py :start-after: """# :language: python More examples on Command Generator API usage follow. .. toctree:: /examples/hlapi/asyncore/manager/cmdgen/snmp-versions /examples/hlapi/asyncore/manager/cmdgen/walking-operations /examples/hlapi/asyncore/manager/cmdgen/advanced-topics Sending SNMP TRAP's and INFORM's is as easy with PySNMP library. The following code sends SNMP TRAP: .. include:: /../../examples/hlapi/asyncore/agent/ntforg/default-v1-trap.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncore/agent/ntforg/default-v1-trap.py :start-after: """# :language: python More examples on Notification Originator API usage follow. .. toctree:: /examples/hlapi/asyncore/agent/ntforg/common-notifications /examples/hlapi/asyncore/agent/ntforg/advanced-topics More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/manager/000077500000000000000000000000001354244100700235305ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700247655ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/manager/cmdgen/advanced-topics.rst000066400000000000000000000027301354244100700305650ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Command Generator -------------------------- .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/query-multiple-snmp-engines-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/query-multiple-snmp-engines-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/multiple-concurrent-queries-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/manager/cmdgen/snmp-versions.rst000066400000000000000000000014411354244100700303420ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/v2c-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/v2c-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/manager/cmdgen/walking-operations.rst000066400000000000000000000007271354244100700313420ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Walking operations ------------------ .. include:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/000077500000000000000000000000001354244100700230725ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/agent/000077500000000000000000000000001354244100700241705ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/agent/ntforg/000077500000000000000000000000001354244100700254675ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/agent/ntforg/advanced-topics.rst000066400000000000000000000016001354244100700312620ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Notification Originator -------------------------------- .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/custom-contextname.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/custom-contextname.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/custom-contextengineid.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/custom-contextengineid.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/agent/ntforg/common-notifications.rst000066400000000000000000000030401354244100700323550ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Common notifications -------------------- .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v2c-trap-with-notification-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v2c-trap-with-notification-objects.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v3-inform.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v3-inform.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v3-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v3-trap.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/agent/ntforg/evaluating-notification-type.rst000066400000000000000000000017451354244100700340320ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Evaluating NOTIFICATION-TYPE ---------------------------- .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v2c-trap-with-notification-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/v2c-trap-with-notification-objects.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/send-notification-with-additional-varbinds.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/send-notification-with-additional-varbinds.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/agent/ntforg/snmp-v1-trap-variants.rst000066400000000000000000000015101354244100700323100ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 SNMPv1 TRAP variants -------------------- .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/custom-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/custom-v1-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/contents.rst000066400000000000000000000052371354244100700254700ustar00rootroot00000000000000 Synchronous SNMP ================ This chapter illustrates various uses of the synchronous high-level programming interface to some of Standard SNMP Applications, as defined in `RFC3413 `_. .. note:: The following examples involve creating Python iterator, the next() call is used to invoke iterator just once. In most examples approximate analogues of well known Net-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net-SNMP tools, better understanding what example code doe Here's a quick example on a simple SNMP GET by high-level API: .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v1-get.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v1-get.py :start-after: """# :language: python To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-mib.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-mib.py :start-after: """# :language: python More examples on Command Generator API usage follow. .. toctree:: /examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions /examples/hlapi/asyncore/sync/manager/cmdgen/modifying-variables /examples/hlapi/asyncore/sync/manager/cmdgen/walking-operations /examples/hlapi/asyncore/sync/manager/cmdgen/table-operations /examples/hlapi/asyncore/sync/manager/cmdgen/mib-tweaks /examples/hlapi/asyncore/sync/manager/cmdgen/transport-tweaks /examples/hlapi/asyncore/sync/manager/cmdgen/advanced-topics Sending SNMP TRAP's and INFORM's is as easy with PySNMP library. The following code sends SNMP TRAP: .. include:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: """# :language: python More examples on Notification Originator API usage follow. .. toctree:: /examples/hlapi/asyncore/sync/agent/ntforg/common-notifications /examples/hlapi/asyncore/sync/agent/ntforg/snmp-v1-trap-variants /examples/hlapi/asyncore/sync/agent/ntforg/evaluating-notification-type /examples/hlapi/asyncore/sync/agent/ntforg/advanced-topics More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/000077500000000000000000000000001354244100700245045ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/000077500000000000000000000000001354244100700257415ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/advanced-topics.rst000066400000000000000000000072011354244100700315370ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Command Generator -------------------------- .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/getbulk-limit-number-of-packets.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/getbulk-limit-number-of-packets.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/multiple-get-calls.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/multiple-get-calls.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-contextengineid.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-contextengineid.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-contextengineid-and-contextname.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-contextengineid-and-contextname.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-v3-security-name.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-v3-security-name.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/specific-v3-engine-id.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/specific-v3-engine-id.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-master-keys.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-master-keys.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-localized-keys.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-localized-keys.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/query-agents-from-multuple-threads-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/query-agents-from-multuple-threads-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/mib-tweaks.rst000066400000000000000000000031641354244100700305420ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 MIB tweaks ---------- .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/waive-mib-lookup.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/waive-mib-lookup.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/preload-pysnmp-mibs.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/preload-pysnmp-mibs.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-asn1-mib-search-path.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-asn1-mib-search-path.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-pysnmp-mibs-search-path.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-pysnmp-mibs-search-path.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/modifying-variables.rst000066400000000000000000000016361354244100700324340ustar00rootroot00000000000000 .. toctree:: :maxdepth: 2 Modifying variables ------------------- .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/coerce-set-value-to-mib-spec.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/coerce-set-value-to-mib-spec.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/set-multiple-scalar-values.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/set-multiple-scalar-values.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library-reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/snmp-versions.rst000066400000000000000000000042371354244100700313240ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 SNMP versions ------------- .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v1-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v1-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v2c-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v2c-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-md5-des.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-md5-des.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-md5-none.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-md5-none.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-none-none.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-none-none.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-sha-aes128.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/usm-sha-aes128.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/table-operations.rst000066400000000000000000000033721354244100700317500ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Table operations ---------------- .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/get-table-object-by-index.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/get-table-object-by-index.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/get-table-object-by-multiple-indices.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/get-table-object-by-multiple-indices.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/getbulk-fetch-scalar-and-table-variables-over-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/getbulk-fetch-scalar-and-table-variables-over-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-snmp-table.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-snmp-table.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/transport-tweaks.rst000066400000000000000000000016161354244100700320270ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-timeout-and-retries.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-timeout-and-retries.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/fetch-variables-over-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/fetch-variables-over-ipv6.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/asyncore/sync/manager/cmdgen/walking-operations.rst000066400000000000000000000007461354244100700323170ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Walking operations ------------------ .. include:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-mib.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/trollius/000077500000000000000000000000001354244100700221505ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/trollius/agent/000077500000000000000000000000001354244100700232465ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/trollius/agent/ntforg/000077500000000000000000000000001354244100700245455ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/trollius/agent/ntforg/common-notifications.rst000066400000000000000000000007271354244100700314440ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Common notifications -------------------- .. include:: /../../examples/hlapi/trollius/agent/ntforg/default-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/trollius/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/trollius/contents.rst000066400000000000000000000037761354244100700245540ustar00rootroot00000000000000 Asynchronous: trollius ====================== In order to use :mod:`asyncio` features with older Python (2.6+), you could download and install `Trollius `_ module. PySNMP's *asyncio* bindings will work with Trollius as well. In most examples approximate analogues of well known Net-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net-SNMP tools, better understanding what example code doe Here's a quick example on a simple SNMP GET by high-level API: .. include:: /../../examples/hlapi/trollius/manager/cmdgen/v1-get.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/trollius/manager/cmdgen/v1-get.py :start-after: """# :language: python To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .. include:: /../../examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python More examples on Command Generator API usage follow. .. toctree:: /examples/hlapi/trollius/manager/cmdgen/snmp-versions /examples/hlapi/trollius/manager/cmdgen/walking-operations Sending SNMP TRAP's and INFORM's is as easy with PySNMP library. The following code sends SNMP TRAP: .. include:: /../../examples/hlapi/trollius/agent/ntforg/default-v1-trap.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/trollius/agent/ntforg/default-v1-trap.py :start-after: """# :language: python More examples on Notification Originator API usage follow. .. toctree:: /examples/hlapi/trollius/agent/ntforg/common-notifications More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. pysnmp-4.4.12/docs/source/examples/hlapi/trollius/manager/000077500000000000000000000000001354244100700235625ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/trollius/manager/cmdgen/000077500000000000000000000000001354244100700250175ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/trollius/manager/cmdgen/snmp-versions.rst000066400000000000000000000014361354244100700304000ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/hlapi/trollius/manager/cmdgen/v1-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/trollius/manager/cmdgen/v1-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/trollius/manager/cmdgen/walking-operations.rst000066400000000000000000000007261354244100700313730ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Walking operations ------------------ .. include:: /../../examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/000077500000000000000000000000001354244100700217565ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/twisted/agent/000077500000000000000000000000001354244100700230545ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/twisted/agent/ntforg/000077500000000000000000000000001354244100700243535ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/twisted/agent/ntforg/advanced-topics.rst000066400000000000000000000010311354244100700301440ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Notification Originator -------------------------------- .. include:: /../../examples/hlapi/twisted/agent/ntforg/multiple-notifications-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/agent/ntforg/multiple-notifications-at-once.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/agent/ntforg/common-notifications.rst000066400000000000000000000015031354244100700312430ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Common notifications -------------------- .. include:: /../../examples/hlapi/twisted/agent/ntforg/default-v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/twisted/agent/ntforg/v2c-trap-inline-callbacks.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/agent/ntforg/v2c-trap-inline-callbacks.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/contents.rst000066400000000000000000000050271354244100700243510ustar00rootroot00000000000000 Asynchronous: Twisted ===================== `Twisted `_ is quite old and widly used I/O framework. With Twisted, your code will mostly live in isolated functions, but unlike as it is with callback-based design, with Twisted work-in-progress is represented by a :class:`~twisted.internet.defer.Deferred` class instance effectively carrying state and context of running operation. Your callback functions will be attached to these *Deferred* objects and invoked as *Deferred* is done. Based on *Twisted* infrastructure, individual asynchronous functions could be chained to run sequentially or in parallel. In most examples approximate analogues of well known Net-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net-SNMP tools, better understanding what example code doe Here's a quick example on a simple SNMP GET by high-level API: .. include:: /../../examples/hlapi/twisted/manager/cmdgen/v1-get.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/v1-get.py :start-after: """# :language: python To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .. include:: /../../examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python More examples on Command Generator API usage follow. .. toctree:: /examples/hlapi/twisted/manager/cmdgen/snmp-versions /examples/hlapi/twisted/manager/cmdgen/walking-operations /examples/hlapi/twisted/manager/cmdgen/transport-tweaks /examples/hlapi/twisted/manager/cmdgen/advanced-topics Sending SNMP TRAP's and INFORM's is as easy with PySNMP library. The following code sends SNMP TRAP: .. include:: /../../examples/hlapi/twisted/agent/ntforg/default-v1-trap.py :start-after: options: :end-before: Functionally .. literalinclude:: /../../examples/hlapi/twisted/agent/ntforg/default-v1-trap.py :start-after: """# :language: python More examples on Notification Originator API usage follow. .. toctree:: /examples/hlapi/twisted/agent/ntforg/common-notifications /examples/hlapi/twisted/agent/ntforg/advanced-topics More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/manager/000077500000000000000000000000001354244100700233705ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/twisted/manager/cmdgen/000077500000000000000000000000001354244100700246255ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/hlapi/twisted/manager/cmdgen/advanced-topics.rst000066400000000000000000000016501354244100700304250ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced Command Generator -------------------------- .. include:: /../../examples/hlapi/twisted/manager/cmdgen/multiple-concurrent-queries.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/multiple-concurrent-queries.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/twisted/manager/cmdgen/pull-mibs-from-multiple-agents-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/pull-mibs-from-multiple-agents-at-once.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/manager/cmdgen/snmp-versions.rst000066400000000000000000000014301354244100700302000ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/hlapi/twisted/manager/cmdgen/v1-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/v1-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/manager/cmdgen/transport-tweaks.rst000066400000000000000000000007631354244100700307150ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/hlapi/twisted/manager/cmdgen/custom-timeout-and-retries.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/custom-timeout-and-retries.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/hlapi/twisted/manager/cmdgen/walking-operations.rst000066400000000000000000000014471354244100700312020ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Walking operations ------------------ .. include:: /../../examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/hlapi/twisted/manager/cmdgen/pull-whole-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/hlapi/twisted/manager/cmdgen/pull-whole-mib.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/smi/000077500000000000000000000000001354244100700177665ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/smi/agent/000077500000000000000000000000001354244100700210645ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/smi/agent/implementing-mib-objects.rst000066400000000000000000000013511354244100700265020ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Agent side ---------- .. include:: /../../examples/smi/agent/custom-managed-object.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/smi/agent/custom-managed-object.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/smi/agent/operations-on-managed-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/smi/agent/operations-on-managed-objects.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/smi/manager/000077500000000000000000000000001354244100700214005ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/smi/manager/browsing-mib-tree.rst000066400000000000000000000022401354244100700254640ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Manager side ------------ .. include:: /../../examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/smi/manager/mib-tree-inspection.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/smi/manager/mib-tree-inspection.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/000077500000000000000000000000001354244100700203625ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/000077500000000000000000000000001354244100700222055ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/agent/000077500000000000000000000000001354244100700233035ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/agent/cmdrsp/000077500000000000000000000000001354244100700245735ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/agent/cmdrsp/agent-side-mib-implementations.rst000066400000000000000000000011301354244100700333130ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Agent-side MIB implementations ------------------------------ .. include:: /../../examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/agent/ntforg/000077500000000000000000000000001354244100700246025ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/agent/ntforg/transport-tweaks.rst000066400000000000000000000015771354244100700306760ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/000077500000000000000000000000001354244100700236175ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700250545ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/cmdgen/fetching-variables.rst000066400000000000000000000007461354244100700313520ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Fetching variables ------------------ .. include:: /../../examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/cmdgen/modifying-variables.rst000066400000000000000000000007071354244100700315450ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Modifying variables ------------------- .. include:: /../../examples/v1arch/asyncore/manager/cmdgen/v2c-set.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/cmdgen/v2c-set.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/cmdgen/transport-tweaks.rst000066400000000000000000000015441354244100700311420ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/cmdgen/walking-operations.rst000066400000000000000000000015551354244100700314310ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 MIB walking operations ---------------------- .. include:: /../../examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/ntfrcv/000077500000000000000000000000001354244100700251215ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v1arch/asyncore/manager/ntfrcv/transport-tweaks.rst000066400000000000000000000010221354244100700311760ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/000077500000000000000000000000001354244100700203645ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/000077500000000000000000000000001354244100700220315ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/agent/000077500000000000000000000000001354244100700231275ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/agent/cmdrsp/000077500000000000000000000000001354244100700244175ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/agent/cmdrsp/snmp-versions.rst000066400000000000000000000007431354244100700300000ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/contents.rst000066400000000000000000000034601354244100700244230ustar00rootroot00000000000000 Asynchronous: asyncio ===================== Python 3.4 introduced a new module - `asyncio `_ (former Tulip, PEP 3156) featuring infrastructure for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources. PySNMP library was originally built on top of Python's asynchronous I/O library called asyncio. The asyncio module offers similar functionality but uses much more modern and powerful language facilities. Functionally, asyncio can replace asyncio in PySNMP however its use requires understanding the concepts such as coroutines and generators. If your task is to embed SNMP stack into an existing asyncio-based app, using PySNMP's asyncio interfaces greatly simplifies the task. Older applications (Python 2.6+) can alternatively use `Trollius `_ instead of asyncio. Trollius is a backport of asyncio so it `supports `_ nearly the same API as asyncio. Full support of both modules is built into pysnmp. All SNMP-related functionality of Native PySNMP API to Standard SNMP Applications (`RFC3413 `_) remains available to asyncio-backed applications. We do not provide Command Generator and Notification Originator examples, as it is much easier to use :doc:`high-level interfaces ` instead. Command Responder Applications ------------------------------ .. toctree:: /examples/v3arch/asyncio/agent/cmdrsp/snmp-versions Notification Receiver Applications ---------------------------------- .. toctree:: /examples/v3arch/asyncio/manager/ntfrcv/transport-tweaks For more details on PySNMP programming model and interfaces, please refer to the documentation pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/manager/000077500000000000000000000000001354244100700234435ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/manager/ntfrcv/000077500000000000000000000000001354244100700247455ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncio/manager/ntfrcv/transport-tweaks.rst000066400000000000000000000007421354244100700310320ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/000077500000000000000000000000001354244100700222075ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/000077500000000000000000000000001354244100700233055ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/cmdrsp/000077500000000000000000000000001354244100700245755ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/cmdrsp/advanced-topics.rst000066400000000000000000000031011354244100700303660ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced topics --------------- .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/cmdrsp/agent-side-mib-implementations.rst000066400000000000000000000031401354244100700333200ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Agent-side MIB implementations ------------------------------ .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/cmdrsp/snmp-versions.rst000066400000000000000000000015351354244100700301560ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/cmdrsp/transport-tweaks.rst000066400000000000000000000024531354244100700306630ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/000077500000000000000000000000001354244100700246045ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/advanced-topics.rst000066400000000000000000000007171354244100700304070ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced topic -------------- .. include:: /../../examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/common-notifications.rst000066400000000000000000000021141354244100700314730ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Common notifications -------------------- .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v1-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-inform.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-inform.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/evaluating-notification-type.rst000066400000000000000000000016311354244100700331410ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Evaluating NOTIFICATION-TYPE ---------------------------- SNMP SMI defines notifications as a TRAP or INFORM PDU containing the indication of type (snmpTrapOID) and a set of MIB variables (Managed Objects Instances) fetched from Agent's MIB at the moment of notification. Consequently, sending specific NOTIFICATION-TYPE implies including certain set of OIDs into PDU. PySNMP offers this facility through NotificationType class. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/multiple-managers-operations.rst000066400000000000000000000031011354244100700331400ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Multiple managers operations ---------------------------- SNMPv3 framework is designed to allow Agents sending the same PDU to multiple Managers over different network transports, listening at different network addresses over different SNMP versions/credentials. The following few examples use this facility. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/snmp-versions.rst000066400000000000000000000026301354244100700301620ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v1-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v1-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v2c-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/v3-trap.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/v3-trap.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library-reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/agent/ntforg/transport-tweaks.rst000066400000000000000000000016401354244100700306670ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/contents.rst000066400000000000000000000052271354244100700246040ustar00rootroot00000000000000 Asynchronous: asyncore ====================== If you find yourself unable to use particular SNMP feature with the high-level (hlapi) API, your next step would be to use SNMPv3 engine services through one of the Standard SNMP Applications (`RFC3413 `_). There're a large number of SNMPv3 Native API example scripts on this website. Most of them serve a very specific purpose like talking arbitrary SNMP version or handling particular PDU type. That dedication of features serve the purpose of simplifying example code and easing your studies. Since all these examples are built on top of common PySNMP components like SNMP engine, asyncore-based I/O dispatcher, configuration datastore, you could always combine parts of the examples for getting a new breed of SNMP application best matching your needs. Command Generator Applications ------------------------------ .. toctree:: /examples/v3arch/asyncore/manager/cmdgen/snmp-versions /examples/v3arch/asyncore/manager/cmdgen/modifying-variables /examples/v3arch/asyncore/manager/cmdgen/walking-operations /examples/v3arch/asyncore/manager/cmdgen/table-operations /examples/v3arch/asyncore/manager/cmdgen/mib-tweaks /examples/v3arch/asyncore/manager/cmdgen/transport-tweaks /examples/v3arch/asyncore/manager/cmdgen/advanced-topics Command Responder Applications ------------------------------ .. toctree:: /examples/v3arch/asyncore/agent/cmdrsp/snmp-versions /examples/v3arch/asyncore/agent/cmdrsp/agent-side-mib-implementations /examples/v3arch/asyncore/agent/cmdrsp/transport-tweaks /examples/v3arch/asyncore/agent/cmdrsp/advanced-topics Notification Originator Applications ------------------------------------ .. toctree:: /examples/v3arch/asyncore/agent/ntforg/snmp-versions /examples/v3arch/asyncore/agent/ntforg/common-notifications /examples/v3arch/asyncore/agent/ntforg/evaluating-notification-type /examples/v3arch/asyncore/agent/ntforg/multiple-managers-operations /examples/v3arch/asyncore/agent/ntforg/transport-tweaks /examples/v3arch/asyncore/agent/ntforg/advanced-topics Notification Receiver Applications ---------------------------------- .. toctree:: /examples/v3arch/asyncore/manager/ntfrcv/snmp-versions /examples/v3arch/asyncore/manager/ntfrcv/transport-tweaks /examples/v3arch/asyncore/manager/ntfrcv/advanced-topics Proxy Forwarder Applications ---------------------------- .. toctree:: /examples/v3arch/asyncore/proxy/command/transport-conversion /examples/v3arch/asyncore/proxy/command/protocol-conversion For more details on PySNMP programming model and interfaces, please refer to the documentation pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/000077500000000000000000000000001354244100700236215ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700250565ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/advanced-topics.rst000066400000000000000000000016331354244100700306570ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced topics --------------- .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/mib-tweaks.rst000066400000000000000000000010361354244100700276530ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 MIB tweaks ---------- .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/modifying-variables.rst000066400000000000000000000007731354244100700315520ustar00rootroot00000000000000 .. toctree:: :maxdepth: 2 Modifying values ---------------- .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/snmp-versions.rst000066400000000000000000000026771354244100700304470ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/v1-get.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/v1-get.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/v2c-set.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/v2c-set.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/table-operations.rst000066400000000000000000000015701354244100700310630ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Table operations ---------------- .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/transport-tweaks.rst000066400000000000000000000032001354244100700311330ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library-reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/cmdgen/walking-operations.rst000066400000000000000000000016111354244100700314240ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Walking operations ------------------ .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/ntfrcv/000077500000000000000000000000001354244100700251235ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/ntfrcv/advanced-topics.rst000066400000000000000000000016411354244100700307230ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Advanced topics --------------- .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/observe-request-processing-over-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/ntfrcv/snmp-versions.rst000066400000000000000000000015571354244100700305100ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/manager/ntfrcv/transport-tweaks.rst000066400000000000000000000025031354244100700312050ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/multiple-network-transports-incl-ipv4-and-ipv6.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/proxy/000077500000000000000000000000001354244100700233705ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/proxy/command/000077500000000000000000000000001354244100700250065ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/proxy/command/protocol-conversion.rst000066400000000000000000000022771354244100700315740ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Protocol conversion ------------------- .. include:: /../../examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library-reference `. pysnmp-4.4.12/docs/source/examples/v3arch/asyncore/proxy/command/transport-conversion.rst000066400000000000000000000007661354244100700317700ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport conversion -------------------- .. include:: /../../examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library-reference `. pysnmp-4.4.12/docs/source/examples/v3arch/trollius/000077500000000000000000000000001354244100700222415ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/trollius/contents.rst000066400000000000000000000020461354244100700246320ustar00rootroot00000000000000 Asynchronous: trollius ====================== `Trollius `_ framework offers infrastructure that allows you writing single-threaded, concurrent code using Python coroutines. Trollius is a backport of `asyncio `_ to Python versions older than 3.3. Trollius supports nearly the same API as asyncio. Full support of both asyncio and trollius modules is built into pysnmp. All SNMP-related functionality of Native PySNMP API to Standard SNMP Applications (`RFC3413 `_) remains available to asyncio-backed applications. We do not provide Command Generator and Notification Originator examples, as it is much easier to use :doc:`high-level interfaces ` instead. As for Command Responder and Notification Receiver, those could be use in the same way as with :doc:`asyncio `. For more details on PySNMP programming model and interfaces, please refer to the documentation pysnmp-4.4.12/docs/source/examples/v3arch/twisted/000077500000000000000000000000001354244100700220475ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/twisted/agent/000077500000000000000000000000001354244100700231455ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/twisted/agent/cmdrsp/000077500000000000000000000000001354244100700244355ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/twisted/agent/cmdrsp/agent-side-mib-implementations.rst000066400000000000000000000010341354244100700331600ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Agent-side MIB implementations ------------------------------ .. include:: /../../examples/v3arch/twisted/agent/cmdrsp/implementing-scalar-mib-objects.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/twisted/agent/cmdrsp/implementing-scalar-mib-objects.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/twisted/agent/cmdrsp/snmp-versions.rst000066400000000000000000000015271354244100700300170ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions ---------------------- .. include:: /../../examples/v3arch/twisted/agent/cmdrsp/multiple-snmp-communities.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/twisted/agent/cmdrsp/multiple-snmp-communities.py :start-after: """# :language: python :download:`Download` script. .. include:: /../../examples/v3arch/twisted/agent/cmdrsp/multiple-usm-users.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/twisted/agent/cmdrsp/multiple-usm-users.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/twisted/agent/cmdrsp/transport-tweaks.rst000066400000000000000000000007341354244100700305230ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/twisted/agent/cmdrsp/multiple-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/twisted/agent/cmdrsp/multiple-interfaces.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/twisted/contents.rst000066400000000000000000000021371354244100700244410ustar00rootroot00000000000000 Asynchronous: Twisted ===================== `Twisted `_ is event-driven networking engine written in Python. It takes shape of a Python library which is used by many Python applications mostly for network communication purposes. All SNMP-related functionality of Native API to Standard SNMP Applications remains available to Twisted applications. We do not provide Command Generator and Notification Originator examples, as it is much easier to use :doc:`high-level interfaces ` instead. Command Responder Applications ------------------------------ .. toctree:: /examples/v3arch/twisted/agent/cmdrsp/snmp-versions /examples/v3arch/twisted/agent/cmdrsp/agent-side-mib-implementations /examples/v3arch/twisted/agent/cmdrsp/transport-tweaks Notification Receiver Applications ---------------------------------- .. toctree:: /examples/v3arch/twisted/manager/ntfrcv/snmp-versions /examples/v3arch/twisted/manager/ntfrcv/transport-tweaks For more details on PySNMP programming model and interfaces, please refer to the documentation pysnmp-4.4.12/docs/source/examples/v3arch/twisted/manager/000077500000000000000000000000001354244100700234615ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/twisted/manager/ntfrcv/000077500000000000000000000000001354244100700247635ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/examples/v3arch/twisted/manager/ntfrcv/snmp-versions.rst000066400000000000000000000007511354244100700303430ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Various SNMP versions --------------------- .. include:: /../../examples/v3arch/twisted/manager/ntfrcv/multiple-usm-users.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/twisted/manager/ntfrcv/multiple-usm-users.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/examples/v3arch/twisted/manager/ntfrcv/transport-tweaks.rst000066400000000000000000000007411354244100700310470ustar00rootroot00000000000000.. toctree:: :maxdepth: 2 Transport tweaks ---------------- .. include:: /../../examples/v3arch/twisted/manager/ntfrcv/multiple-interfaces.py :start-after: """ :end-before: """# .. literalinclude:: /../../examples/v3arch/twisted/manager/ntfrcv/multiple-interfaces.py :start-after: """# :language: python :download:`Download` script. See also: :doc:`library reference `. pysnmp-4.4.12/docs/source/faq.rst000066400000000000000000000006041354244100700166610ustar00rootroot00000000000000 FAQ === Here we have an ever-growing list of frequently asked questions regarding PySNMP usage issues. If you got an issue that you think is worth noting here, please open a `GitHub issue `_. Keep in mind that some the answers below may not be universally applicable to any PySNMP revision. .. toctree:: :maxdepth: 2 :glob: /faq/* pysnmp-4.4.12/docs/source/faq/000077500000000000000000000000001354244100700161275ustar00rootroot00000000000000pysnmp-4.4.12/docs/source/faq/getting-peer-information.rst000066400000000000000000000026021354244100700235760ustar00rootroot00000000000000 Getting peer address information -------------------------------- Q. How do I find out peer transport address or security information within my receiving app (CommandResponder or Notification Receiver)? A. SNMP architecture forces you to distinguish communicating entities only on the basis of their community names (SNMPv1/v2c) or ContextEngineId/ContextName pair (SNMPv3). In other words, if one SNMP Manager should anyhow differ from another, then they should use distinct community names or SNMP contexts. Transport information should never be used for the identification purposes, as in some cases it proves to be unreliable (cases include NAT device or a proxy in the middle, not to mention address spoofing). As practice reveals, even perfect design does not always cope well with the imperfect world. So we had to pinch a logic hole from the scope of an SNMP app down to transport layer. Now with the getTransportInfo(stateReference) method call you could get peer transport information upon receiving its SNMP message. .. code-block:: python # Callback function for receiving notifications def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) pysnmp-4.4.12/docs/source/faq/how-to-implement-agent-mib.rst000066400000000000000000000073571354244100700237430ustar00rootroot00000000000000 How to implement MIB at the Agent --------------------------------- Q. How to instantiate static MIB table at my SNMP Agent? A. You need to create MibScalarInstance class instances and register them with your Agent's SNMP engine (mibBuilder, more specifically). Here's an example code for a IP-MIB table: .. code-block:: python # SNMP Agent (AKA CommandResponder) is built around SNMP engine object snmpEngine = engine.SnmpEngine() # Import table columns ( ipAddressAddrType, ipAddressAddr, ipAddressIfIndex, ipAddressType, ipAddressPrefix, ipAddressOrigin, ipAddressStatus, ipAddressCreated, ipAddressLastChanged, ipAddressRowStatus, ipAddressStorageType ) = snmpEngine.msgAndPduDsp.mibInstrumController .mibBuilder.importSymbols( 'IP-MIB', 'ipAddressAddrType', 'ipAddressAddr', 'ipAddressIfIndex', 'ipAddressType', 'ipAddressPrefix', 'ipAddressOrigin', 'ipAddressStatus', 'ipAddressCreated', 'ipAddressLastChanged', 'ipAddressRowStatus', 'ipAddressStorageType' ) # Import MibScalarInstance MibScalarInstance, = snmpEngine.msgAndPduDsp.mibInstrumController. mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') # Create table columns instances _ipAddressAddrType = MibScalarInstance( ipAddressAddrType.name, (1, 4, 1, 2, 3, 4), ipAddressAddrType.syntax.clone(1) ) _ipAddressAddr = MibScalarInstance( ipAddressAddr.name, (1, 4, 1, 2, 3, 4), ipAddressAddr.syntax.clone('1.2.3.4') ) _ipAddressIfIndex = MibScalarInstance( ipAddressIfIndex.name, (1, 4, 1, 2, 3, 4), ipAddressIfIndex.syntax.clone(1) ) _ipAddressType = MibScalarInstance( ipAddressType.name, (1, 4, 1, 2, 3, 4), ipAddressType.syntax.clone(1) ) _ipAddressPrefix = MibScalarInstance( ipAddressPrefix.name, (1, 4, 1, 2, 3, 4), ipAddressPrefix.syntax.clone((0,0)) ) _ipAddressOrigin = MibScalarInstance( ipAddressOrigin.name, (1, 4, 1, 2, 3, 4), ipAddressOrigin.syntax.clone(1) ) _ipAddressStatus = MibScalarInstance( ipAddressStatus.name, (1, 4, 1, 2, 3, 4), ipAddressStatus.syntax.clone(1) ) _ipAddressCreated = MibScalarInstance( ipAddressCreated.name, (1, 4, 1, 2, 3, 4), ipAddressCreated.syntax.clone(800) ) _ipAddressLastChanged = MibScalarInstance( ipAddressLastChanged.name, (1, 4, 1, 2, 3, 4), ipAddressLastChanged.syntax.clone(600) ) _ipAddressRowStatus = MibScalarInstance( ipAddressRowStatus.name, (1, 4, 1, 2, 3, 4), ipAddressRowStatus.syntax.clone(1) ) _ipAddressStorageType = MibScalarInstance( ipAddressStorageType.name, (1, 4, 1, 2, 3, 4), ipAddressStorageType.syntax ) # add anonymous column instances snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.exportSymbols( '_IP-MIB', _ipAddressAddrType, _ipAddressAddr, _ipAddressIfIndex, _ipAddressType, _ipAddressPrefix, _ipAddressOrigin, _ipAddressStatus, _ipAddressCreated, _ipAddressLastChanged, _ipAddressRowStatus, _ipAddressStorageType ) # Command responder code would follow... Keep in mind that the values of this table row will not change by themselves. They basically hold a snapshot of a data set so your application may have to update them somehow. For example, an app could periodically lookup particular MibScalarInstance by OID at mibBuilder and update its "syntax" attribute with a new value. There are other ways for building MIB tables that represent dynamic Managed Objects. pysnmp-4.4.12/docs/source/faq/ignored-snmp-packets.rst000066400000000000000000000061041354244100700227140ustar00rootroot00000000000000 Ignored SNMP packets -------------------- Q. Some network devices do not respond to PySNMP-based management requests for particular OIDs. .. code-block:: bash $ pysnmpget -v2c -c public 10.0.0.33 1.3.6.1.2.1.2.2.1.10.3 SNMPv2-SMI::mib-2.2.2.1.10.3 = Counter32: 1519568842 $ snmpget.py -v2c -c public 10.0.0.33 1.3.6.1.2.1.2.2.1.10.4 requestTimedOut Meanwhile, tcpcump shows request-response sequence: .. code-block:: bash 13:33:30.161843 IP 10.0.0.33.snmp > 10.0.0.1.51094: GetResponse(31) interfaces.ifTable.ifEntry.ifInOctets.3=1532504859 13:33:30.161881 IP 10.0.0.33.snmp > 10.0.0.1.51094: GetResponse(31) interfaces.ifTable.ifEntry.ifInOctets.3=1532504859 In some cases, particularily when running v1arch PySNMP code, the following exception may be thrown on response processing: .. code-block:: python Traceback (most recent call last): .... File "build/bdist.linux-i686/egg/pyasn1/type/base.py", line 64, in __init__ File "build/bdist.linux-i686/egg/pyasn1/type/base.py", line 32, in _verifySubtypeSpec File "build/bdist.linux-i686/egg/pyasn1/type/constraint.py", line 33, in __call__ pyasn1.type.error.ValueConstraintError: ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(0, 4294967295)) failed at: ValueRangeConstraint(0, 4294967295) failed at: -1413698940 A. This appears to be a [widespread] bug in BER integer encoders. It usually gets noticed on Counter values as they are constrained to be positive while wrong encoding yelds them negative. Here's broken encoding: .. code-block:: python >>> decoder.decode('A\x04\xab\xbc\xaa\x84', asn1Spec=rfc1155.Counter()) Traceback (most recent call last): ... pyasn1.type.error.ValueConstraintError: ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(0, 4294967295)) failed at: ValueRangeConstraint(0, 4294967295) failed at: -1413698940 And here's a good one: .. code-block:: python >>> decoder.decode('A\x05\x00\xab\xbc\xaa\x84', >>> asn1Spec=rfc1155.Counter()) (Counter('2881268356'), '') Notice the third octet -- positive values must have its highest bit set to zero. Here's an example hack that converts negated values into their positive complimentaries for Counter type. .. code-block:: python from pysnmp.proto import rfc1155, rfc1902, api from pyasn1.codec.ber import encoder, decoder # --- hack Counter type def counterCloneHack(self, *args): if args and args[0] < 0: args = (0xffffffff+args[0]-1,) + args[1:] return self.__class__(*args) rfc1155.Counter.clone = counterCloneHack rfc1902.Counter32.clone = counterCloneHack Execute this hack before any SNMP message processing occures in your app. The bad news is that if this BER encoding bug also affects Integer values, in that case it is theoretically impossible to fix because, unlike Counter, Integer values may legally be negative so they could not unconditionally be converted into positives. Therefore the best solutoin would be to get vendors fixing their BER encoders. pysnmp-4.4.12/docs/source/faq/listening-on-multiple-interfaces.rst000066400000000000000000000023101354244100700252350ustar00rootroot00000000000000 Listening on multiple network interfaces ---------------------------------------- Q. I need my receiving entity (CommandResponder or Notification Receiver) to listen for SNMP messages on multiple network interfaces. How do I do that with pysnmp? A. Simply register multiple network transports with your SNMP engine. Each transport would be bound to an individual local transport endpoint (for instance, IP address & UDP port pair). .. code-block:: python # Security setup would follow ... # Setup first transport endpoint config.addSocketTransport( snmpEngine, udp.domainName + (1,), udp.UdpSocketTransport().openServerMode(('127.0.0.1', 162)) ) # Setup second transport endpoint config.addSocketTransport( snmpEngine, udp.domainName + (2,), udp.UdpSocketTransport().openServerMode(('192.168.1.1', 162)) ) # Receiver callback function implementation and Dispatcher invocation # would follow ... Notice extended transport domain specification (udp.domainName) in the code above. There we register each transport endpoint under distinct OID, however always within the canonical transport domain OID. pysnmp-4.4.12/docs/source/faq/non-printable-snmp-values-apps.rst000066400000000000000000000017651354244100700246530ustar00rootroot00000000000000 Garbaged SNMP values (apps) --------------------------- Q. When my PySNMP application prints out fetched values, some of them come out as a garbage on my screan. Here's my code: .. code-block:: python for varBind in varBinds: print(' = '.join([ str(x) for x in varBind ]) and the result is: .. code-block:: python 1.3.6.1.4.1.161.19.3.2.1.63.0 = 50000 1.3.6.1.4.1.161.19.3.2.1.4.0 = '\x01\x02\x03\x04' The IpAddress type seems to be the only one with this problem. A. Always use prettyPrint() method for all pyasn1-based objects -- it automatically converts ASN1 types to human-friendly form. .. code-block:: python > > > from pysnmp.proto import rfc1902 > > > a = rfc1902.IpAddress('1.2.3.4') > > > str(a) '\x01\x02\x03\x04' > > > a IpAddress('1.2.3.4') > > > a.prettyPrint() '1.2.3.4' > > > rfc1902.IpAddress.prettyPrint(a) '1.2.3.4' See `pyasn1 docs `_ for more information on pyasn1 data model. pysnmp-4.4.12/docs/source/faq/non-printable-snmp-values-tools.rst000066400000000000000000000030021354244100700250320ustar00rootroot00000000000000 Garbaged SNMP values (tools) ---------------------------- Q. When fetching data with snmp*.py command-line tools, some values do not print out nicely: .. code-block:: bash $ snmpget.py -v2c -c public 127.0.0.1 .1.3.6.1.4.1.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 SNMPv2-SMI::enterprises.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 = OctetString: ˇČ where Net-SNMP gives nicely formatted human-readable string: .. code-block:: bash $ snmpget -v2c -c public 127.0.0.1 .1.3.6.1.4.1.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 SNMPv2-SMI::enterprises.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 = Hex-STRING: 00 17 B7 22 08 C8 What can be done to PySNMP to make it returning HEX data in human-readable? A. The difference is that Net-SNMP prints values into hex by-default, whereas pysnmp does not do that. You can force snmpget.py to work similarily with the -OT command line parameter. .. code-block:: bash $ snmpget.py -OT -v2c -c public 127.0.0.1 .1.3.6.1.4.1.14988.1.1.1.2.1.1.0.23. 183.34.8.200.3 SNMPv2-SMI::enterprises.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 = OctetString: 00 17 b7 22 08 c8 Another matter is MIB lookup - when snmp*.py tool can use a MIB to figure out what are the display conventions for particular value type, it will reformat the value in a human-readable form. To let MIB lookup work, please pass appropriate MIB name to snmp*.py tool through command line: .. code-block:: bash $ snmpwalk.py -m IP-MIB,IF-MIB -v2c -c public 127.0.0.1 .1.3.6.1.4.1 pysnmp-4.4.12/docs/source/faq/oids-not-increasing.rst000066400000000000000000000037261354244100700225450ustar00rootroot00000000000000 Dealing with the "OID not increasing" error ------------------------------------------- Q. I'm walking a particular Agent with the `nextCmd()` or `bulkCmd()` functions. It works for some OIDs, but invariably fails at certain OID with the *OID not increasing* error. What does it mean and how do I fix that? A. The Agent you are talking to seems to be broken. The *OID not increasing* message means that in the course of fetching OIDs from the Agent, Manager receives an OID that is not greater than those passed in request. Due to the nature of GETNEXT/GETBULK algorithm, passing the same or lesser OID to Manager would result in fetching the same set of OIDs over and over again effectively creating an infinite loop between Manager and Agent so they may never reach the end of MIB. To prevent this the Manager tries to intervene and prevent such loop from happening. If you have to work with a broken Agent and can terminate the GETNEXT/GETBULK command at some point, you can pass the `ignoreNonIncreasingOid=True` keyword parameter to the `nextCmd()` or `bulkCmd()` to disable OID verification at the Manager side. .. code-block:: python for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6')), ignoreNonIncreasingOid=True): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind]) pysnmp-4.4.12/docs/source/faq/pass-custom-mib-to-manager.rst000066400000000000000000000036061354244100700237410ustar00rootroot00000000000000 How to pass MIB to the Manager ------------------------------ Q. How to make use of random MIBs at my Manager application? A. Starting from PySNMP 4.3.x, plain-text (ASN.1) MIBs can be automatically parsed into PySNMP form by the `PySMI `_ tool. PySNMP will call PySMI automatically, parsed PySNMP MIB will be cached in $HOME/.pysnmp/mibs/ (default location). MIB compiler could be configured to search for plain-text MIBs at multiple local and remote locations. As for remote MIB repos, you are welcome to use our collection of ASN.1 MIB files at `http://mibs.snmplabs.com/asn1/ `_ as shown below. .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/custom-asn1-mib-search-path.py :start-after: """# :language: python .. code: :language: python # Configure the SNMP engine with access to the # common Linux ASN.1 (Textual) MIB directories... from pysnmp import hlapi from pysnmp.smi import compiler engine = hlapi.Engine() builder = engine.getMibBuilder() compiler.addMibCompiler(builder, sources=[ '/usr/share/snmp/mibs', os.path.expanduser('~/.snmp/mibs'), 'http://mibs.snmplabs.com/asn1/@mib@', ]) :download:`Download` script. Alternatively, you can invoke the `mibdump.py `_ (shipped with PySMI) by hand and this way compile plain-text MIB into PySNMP format. Once the compiled MIBs are stored in a directory, add the directory to your MibBuilder's MibSources. .. code:: builder = engine.getMibBuilder() # Make ./mibs available to all OIDs that are created # e.g. with "MIB-NAME-MIB::identifier" builder.addMibSources(builder_module.DirMibSource( os.path.join( HERE, 'mibs') )) pysnmp-4.4.12/docs/source/faq/py2exe-throws-error.rst000066400000000000000000000023251354244100700225520ustar00rootroot00000000000000 My py2exe app can't find MIBs ----------------------------- Q. I packed my pysnmp-based application with py2exe. When I run my app, it throws a traceback like this: .. code-block:: bash File "pysnmp\entity\rfc3413\oneliner\cmdgen.pyc", line 116, in __init__ File "pysnmp\entity\engine.pyc", line 16, in __init__ File "pysnmp\proto\rfc3412.pyc", line 16, in __init__ File "pysnmp\smi\builder.pyc", line 143, in __init__ File "pysnmp\smi\builder.pyc", line 35, in init File "pysnmp\smi\builder.pyc", line 80, in _init ImportError: No module named mibs.instances PySNMP claims itself to be py2exe-friendly. How to make it working? A. You have to list pysnmp MIB directories explicitly at your app's setup.py so that py2exe would include them into the binary. .. code-block:: python from distutils.core import setup import sys options = {} if "py2exe" in sys.argv: import py2exe # fix executables options['console'] = ['myapp.py'] # add files not found my modulefinder options['options'] = { 'py2exe': { 'includes': [ 'pysnmp.smi.mibs.*', 'pysnmp.smi.mibs.instances.*' ] } } setup(**options) pysnmp-4.4.12/docs/source/faq/response-values-mib-resolution.rst000066400000000000000000000032761354244100700247720ustar00rootroot00000000000000 Resolve response values at MIB ------------------------------ Q. My CommandGenerator app reports OIDs and values in form of PyASN1 objects. How do I convert them into human-readable, symbolic names and values? A. The most easy to use interface to MIB lookup feature is supported by PySNMP 4.2.3 and later. Just pass the .. code-block:: python lookupNames=True, lookupValues=True parameters to getCmd(), setCmd(), nextCmd(), bulkCmd() methods of oneliner CommandGenerator. Then the OIDs in response variable-binding list will get replaced by similarily looking MibVariable instances, their prettyPrint() methods return MIB symbols instead of OIDs. Response values will still be PyASN1 objects but some may be replaced by TEXTUAL-CONVENTION decorators what make their prettyPrint() methods returning even more human-friendly output. .. code-block:: python >>> from pysnmp.entity.rfc3413.oneliner import cmdgen >>> >>> cmdGen = cmdgen.CommandGenerator() >>> >>> errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( ... cmdgen.CommunityData('public'), ... cmdgen.UdpTransportTarget(('localhost', 161)), ... '1.3.6.1.2.1.1.1.0', ... lookupNames=True, lookupValues=True ... ) >>> >>> name, value = varBinds[0] >>> name MibVariable(ObjectName(1.3.6.1.2.1.1.1.0)) >>> value DisplayString('Linux saturn 2.6.38.1 Sat Apr 9 23:39:07 CDT 2012 i686') >>> name.prettyPrint() 'SNMPv2-MIB::sysDescr."0"' >>> value.prettyPrint() 'Linux cray 2.6.37.6-smp #2 SMP Sat Apr 9 23:39:07 CDT 2011 i686' >>> If you are using older PySNMP versions it's strongly recommended to upgrade to the latest one. pysnmp-4.4.12/docs/source/faq/snmp-data-constraints-verification-failure.rst000066400000000000000000000030741354244100700272230ustar00rootroot00000000000000 SNMP data constraints verification error ---------------------------------------- Q. Will PySNMP Manager verify the values it sends to and receives from a distant Agent against local MIB constraints? A. Yes, it can do that. The Manager will verify the values you pass to SET request against a MIB if: The values are not already PyASN1 objects but some basic Python types (like integer or string). You tell PySNMP engine to load appropriate MIB where it could lookup the constraints (via the use of MibVariable) So, the following code fragment makes PySNMP engine loading SNMPv2-MIB and verifying that the 'new system name' value satisfies sysName constraints (if any). .. code-block:: python errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('localhost', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0), 'new system name' ) ) To verify the response values, you should pass at least lookupValues flag to CommandGenerator \*cmd() method you use. In the following example PySNMP will make sure that Agent-supplied value for SNMPv2-MIB::sysName Managed Object satisfies MIB constraints (if any). .. code-block:: python errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('localhost', 161)), cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0), lookupValues=True ) In case of constraint violation, a PySNMP exception will be raised. pysnmp-4.4.12/docs/source/faq/walk-whole-mib.rst000066400000000000000000000015071354244100700215030ustar00rootroot00000000000000 Walking whole MIB ----------------- Q. The nextCmd() and bulkCmd() methods of CommandGenerator app (oneliner version) stop working once returned OIDs went out of scope of request OIDs. In other words, if I request 1.3.6.1, I would get everything under the 1.3.6.1 prefix, but not 1.3.6.2. Is there any way to make it walking the whole MIB? A. Yes, just pass the lexicographicMode=True parameter to CommandGenerator nextCmd() and bulkCmd() methods (introduced in PySNMP 4.2.3+) or set CommandGenerator.lexicographicMode=True option before calling nextCmd() and bulkCmd() methods. .. code-block:: python cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd( ...., ...., ...., lexicographicMode=True ) pysnmp-4.4.12/docs/source/license.rst000066400000000000000000000000611354244100700175310ustar00rootroot00000000000000 License ======= .. include:: ../../LICENSE.rst pysnmp-4.4.12/docs/source/oldsite.rst000066400000000000000000000005041354244100700175540ustar00rootroot00000000000000 Old site archive ================ Starting from PySNMP 4.3.0, we redesigned all documentation and web-site. For previous versions of those please follow these links for `old examples `_ and `old documentation `_ . pysnmp-4.4.12/docs/source/quick-start.rst000066400000000000000000000035131354244100700203630ustar00rootroot00000000000000 Quick start =========== .. toctree:: :maxdepth: 2 Once you downloaded and installed PySNMP library on your Linux/Windows/OS X system, you should be able to solve the very basic SNMP task right from your Python prompt - fetch some data from a remote SNMP Agent (you'd need at least version 4.3.0 to run code from this page). Fetch SNMP variable ------------------- So just cut&paste the following code right into your Python prompt. The code will performs SNMP GET operation for a sysDescr.0 object at a publically available SNMP Command Responder at `demo.snmplabs.com `_: .. literalinclude:: /../../examples/hlapi/asyncore/sync/manager/cmdgen/v1-get.py :start-after: """# :language: python :download:`Download` script. If everything works as it should you will get: .. code-block:: python ... SNMPv2-MIB::sysDescr."0" = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m >>> on your console. Send SNMP TRAP -------------- To send a trivial TRAP message to our hosted Notification Receiver at `demo.snmplabs.com `_ , just cut&paste the following code into your interactive Python session: .. literalinclude:: /../../examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py :start-after: """# :language: python :download:`Download` script. Many ASN.1 MIB files could be downloaded from `mibs.snmplabs.com `_ or PySNMP could be :doc:`configured ` to download them automatically. For more sophisticated examples and use cases please refer to :doc:`examples ` and :doc:`library reference ` pages. pysnmp-4.4.12/examples/000077500000000000000000000000001354244100700147465ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/000077500000000000000000000000001354244100700160435ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/000077500000000000000000000000001354244100700175105ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/agent/000077500000000000000000000000001354244100700206065ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/agent/ntforg/000077500000000000000000000000001354244100700221055ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/agent/ntforg/default-v1-trap.py000066400000000000000000000025371354244100700254020ustar00rootroot00000000000000""" SNMPv1 TRAP with defaults +++++++++++++++++++++++++ Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #1 (warmStart) and Specific Trap 0 * with default Uptime * with default Agent Address * with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system" """# import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(): snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from sendNotification( snmpEngine, CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) if errorIndication: print(errorIndication) snmpEngine.transportDispatcher.closeDispatcher() asyncio.get_event_loop().run_until_complete(run()) pysnmp-4.4.12/examples/hlapi/asyncio/agent/ntforg/multiple-notifications-at-once.py000066400000000000000000000036611354244100700305130ustar00rootroot00000000000000""" Multiple concurrent notifications +++++++++++++++++++++++++++++++++ Send multiple SNMP notifications at once using the following options: * SNMPv2c and SNMPv3 * with community name 'public' * over IPv4/UDP * send INFORM notification * to multiple Managers * with TRAP ID 'coldStart' specified as a MIB symbol * include managed object information specified as var-bind objects pair Here we tag each SNMP-COMMUNITY-MIB::snmpCommunityTable row with the same tag as SNMP-TARGET-MIB::snmpTargetAddrTable row what leads to excessive tables information. Functionally similar to: | $ snmptrap -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 | $ snmpinform -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 | $ snmptrap -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 """# import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def sendone(snmpEngine, hostname, notifyType): (errorIndication, errorStatus, errorIndex, varBinds) = yield from sendNotification( snmpEngine, CommunityData('public', tag=hostname), UdpTransportTarget((hostname, 162), tagList=hostname), ContextData(), notifyType, NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s: at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.wait([sendone(snmpEngine, 'demo.snmplabs.com', 'trap'), sendone(snmpEngine, 'demo.snmplabs.com', 'inform')]) ) pysnmp-4.4.12/examples/hlapi/asyncio/manager/000077500000000000000000000000001354244100700211225ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/manager/cmdgen/000077500000000000000000000000001354244100700223575ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/manager/cmdgen/getbulk-to-eom.py000066400000000000000000000032171354244100700255670ustar00rootroot00000000000000""" Bulk walk MIB +++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs past SNMPv2-MIB::system * run till end-of-mib condition is reported by Agent * based on asyncio I/O framework Functionally similar to: | $ snmpbulkwalk -v3 -lnoAuthNoPriv -u usr-none-none -Cn0 -Cr50 \ | demo.snmplabs.com SNMPv2-MIB::system """# import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield from bulkCmd( snmpEngine, UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 50, *varBinds) if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ) ) else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = asyncio.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))]) ) multiple-concurrent-queries-over-ipv4-and-ipv6.py000066400000000000000000000030121354244100700336070ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncio/manager/cmdgen""" Concurrent queries ++++++++++++++++++ Send multiple SNMP GET requests at once using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to multiple Agents at demo.snmplabs.com * for instance of SNMPv2-MIB::sysDescr.0 MIB object * based on asyncio I/O framework Functionally similar to: | $ snmpget -v2c -c public demo.snmplabs.com:1161 SNMPv2-MIB::sysDescr.0 | $ snmpget -v2c -c public demo.snmplabs.com:2161 SNMPv2-MIB::sysDescr.0 | $ snmpget -v2c -c public demo.snmplabs.com:3161 SNMPv2-MIB::sysDescr.0 """# import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def getone(snmpEngine, hostname): errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData('public'), UdpTransportTarget(hostname), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ) ) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.wait([getone(snmpEngine, ('demo.snmplabs.com', 1161)), getone(snmpEngine, ('demo.snmplabs.com', 2161)), getone(snmpEngine, ('demo.snmplabs.com', 3161))]) ) pysnmp-4.4.12/examples/hlapi/asyncio/manager/cmdgen/multiple-sequential-queries.py000066400000000000000000000032141354244100700304070ustar00rootroot00000000000000""" Sequential queries ++++++++++++++++++ Send multiple SNMP GET requests one by one using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to multiple Agents at demo.snmplabs.com * for instance of SNMPv2-MIB::sysDescr.0 MIB object * based on asyncio I/O framework Functionally similar to: | $ snmpget -v2c -c public demo.snmplabs.com:1161 SNMPv2-MIB::sysDescr.0 | $ snmpget -v2c -c public demo.snmplabs.com:2161 SNMPv2-MIB::sysDescr.0 | $ snmpget -v2c -c public demo.snmplabs.com:3161 SNMPv2-MIB::sysDescr.0 """# import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def getone(snmpEngine, hostname): errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData('public'), UdpTransportTarget(hostname), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ) ) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) @asyncio.coroutine def getall(snmpEngine, hostnames): for hostname in hostnames: yield from getone(snmpEngine, hostname) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete(getall(snmpEngine, [('demo.snmplabs.com', 1161), ('demo.snmplabs.com', 2161), ('demo.snmplabs.com', 3161)])) pysnmp-4.4.12/examples/hlapi/asyncio/manager/cmdgen/v1-get.py000066400000000000000000000022761354244100700240430ustar00rootroot00000000000000""" SNMPv1 ++++++ Send SNMP GET request using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for an instance of SNMPv2-MIB::sysDescr.0 MIB object * Based on asyncio I/O framework Functionally similar to: | $ snmpget -v1 -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(): snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ) ) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() asyncio.get_event_loop().run_until_complete(run()) pysnmp-4.4.12/examples/hlapi/asyncore/000077500000000000000000000000001354244100700176665ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/agent/000077500000000000000000000000001354244100700207645ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/agent/ntforg/000077500000000000000000000000001354244100700222635ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/agent/ntforg/default-v1-trap.py000066400000000000000000000021101354244100700255430ustar00rootroot00000000000000""" SNMPv1 TRAP with defaults +++++++++++++++++++++++++ Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #1 (warmStart) and Specific Trap 0 * with default Uptime * with default Agent Address * with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi.asyncore import * snmpEngine = SnmpEngine() sendNotification( snmpEngine, CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/agent/ntforg/multiple-informs-at-once.py000066400000000000000000000040521354244100700274700ustar00rootroot00000000000000""" Multiple concurrent notifications +++++++++++++++++++++++++++++++++ Send multiple SNMP notifications at once using the following options: * SNMPv2c and SNMPv3 * with community name 'public' or USM username usr-md5-des * over IPv4/UDP * send INFORM notification * to multiple Managers * with TRAP ID 'coldStart' specified as a MIB symbol * include managed object information specified as var-bind objects pair | $ snmpinform -v2c -c public demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 | $ snmpinform -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget ), ... ) targets = ( # 1-st target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData()), # 2-nd target (SNMPv3 over IPv4/UDP) (UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData()), ) # noinspection PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print('Notification %s not sent: %s' % (sendRequestHandle, errorIndication)) elif errorStatus: print('Notification Receiver returned error for %s: %s @%s' % (sendRequestHandle, errorStatus, errorIndex)) else: print('Notification %s delivered:' % sendRequestHandle) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) snmpEngine = SnmpEngine() for authData, transportTarget, contextData in targets: sendPduHandle = sendNotification( snmpEngine, authData, transportTarget, contextData, 'inform', # NotifyType NotificationType( ObjectIdentity('SNMPv2-MIB', 'coldStart') ).addVarBinds(('1.3.6.1.2.1.1.1.0', 'my name')), cbFun=cbFun ) snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/agent/ntforg/multiple-traps-at-once.py000066400000000000000000000030001354244100700271340ustar00rootroot00000000000000""" Multiple concurrent queries +++++++++++++++++++++++++++ Send a bunch of different SNMP Notifications to different peers all at once, wait for responses asynchronously: * SNMPv1 and SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * to multiple Managers * with TRAP ID 'coldStart' specified as a MIB symbol * include managed object information specified as var-bind objects pair | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 demo.snmplabs.com 6 432 12345 1.3.6.1.2.1.1.1.0 s "my system" | $ snmptrap -v2c -c public demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) (CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData()), # 2-nd target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData()), ) snmpEngine = SnmpEngine() for authData, transportTarget, contextData in targets: sendNotification( snmpEngine, authData, transportTarget, contextData, 'trap', # NotifyType NotificationType( ObjectIdentity('SNMPv2-MIB', 'coldStart') ).addVarBinds( (ObjectIdentifier('1.3.6.1.2.1.1.1.0'), OctetString('my name')) ) ) snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/agent/ntforg/running-multiple-snmp-engines-at-once.py000066400000000000000000000067041354244100700321020ustar00rootroot00000000000000""" Multiple SNMP Engines +++++++++++++++++++++ Send SNMP notifications in behalf of multiple independend SNMP engines using the following options: * with a single transport dispatcher and two independent SNMP engines * SNMPv2c and SNMPv3 * with community name 'public' or USM username usr-md5-des * over IPv4/UDP * send IMFORM notification * to multiple Managers * with TRAP ID 'coldStart' specified as a MIB symbol * include managed object information specified as var-bind objects pair Within this script we have a single asynchronous TransportDispatcher and a single UDP-based transport serving two independent SNMP engines. We use a single instance of AsyncNotificationOriginator with each of SNMP Engines to communicate INFORM notification to remote systems. When we receive a [response] message from remote system we use a custom message router to choose what of the two SNMP engines data packet should be handed over. The selection criteria we employ here is based on peer's UDP port number. Other selection criterias are also possible. | $ snmpinform -v2c -c public demo.snmplabs.com:1162 123 1.3.6.1.6.3.1.1.5.1 | $ snmpinform -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.hlapi.asyncore import * from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher # List of targets in the following format: # ( ( authData, transportTarget ), ... ) targets = ( # 1-st target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 1162)), ContextData()), # 2-nd target (SNMPv3 over IPv4/UDP) (UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData()), ) # noinspection PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): snmpEngine = cbCtx if errorIndication: print('Notification %s for %s not sent: %s' % (sendRequestHandle, snmpEngine.snmpEngineID.prettyPrint(), errorIndication)) elif errorStatus: print('Notification Receiver returned error for request %s, SNMP Engine %s: %s @%s' % (sendRequestHandle, snmpEngine.snmpEngineID.prettyPrint(), errorStatus, errorIndex)) else: print('Notification %s for SNMP Engine %s delivered:' % (sendRequestHandle, snmpEngine.snmpEngineID.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Instantiate the single transport dispatcher object transportDispatcher = AsyncoreDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain transportDispatcher.registerRoutingCbFun( lambda td, ta, d: ta[1] % 3 and 'A' or 'B' ) snmpEngineA = SnmpEngine() snmpEngineA.registerTransportDispatcher(transportDispatcher, 'A') snmpEngineB = SnmpEngine() snmpEngineB.registerTransportDispatcher(transportDispatcher, 'B') for authData, transportTarget, contextData in targets: snmpEngine = (transportTarget.getTransportInfo()[1][1] % 3 and snmpEngineA or snmpEngineB) sendPduHandle = sendNotification( snmpEngine, authData, transportTarget, contextData, 'inform', # NotifyType NotificationType( ObjectIdentity('SNMPv2-MIB', 'coldStart') ).addVarBinds(('1.3.6.1.2.1.1.1.0', 'my name')), cbFun=cbFun, cbCtx=snmpEngine ) transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/manager/000077500000000000000000000000001354244100700213005ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700225355ustar00rootroot00000000000000multiple-concurrent-queries-over-ipv4-and-ipv6.py000066400000000000000000000056511354244100700340000ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/manager/cmdgen""" Multiple concurrent queries +++++++++++++++++++++++++++ Send a bunch of different SNMP GET requests to different peers all at once, wait for responses asynchronously: * with SNMPv1, community 'public' and with SNMPv2c, community 'public' and with SNMPv3, user 'usr-md5-des', MD5 auth and DES privacy * over IPv4/UDP and over IPv6/UDP * to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 * for instances of SNMPv2-MIB::sysDescr.0 and SNMPv2-MIB::sysLocation.0 MIB objects """# from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) (CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 2-nd target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 3-nd target (SNMPv2c over IPv4/UDP) - same community and # different transport address. (CommunityData('public'), UdpTransportTarget(('localhost', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysContact', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0)))), # 4-nd target (SNMPv3 over IPv4/UDP) (UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 5-th target (SNMPv3 over IPv6/UDP) (UsmUserData('usr-md5-none', 'authkey1'), Udp6TransportTarget(('::1', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # N-th target # ... ) # Wait for responses or errors # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): authData, transportTarget = cbCtx print('%s via %s' % (authData, transportTarget)) if errorIndication: print(errorIndication) return True elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) return True else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() # Submit GET requests for authData, transportTarget, varNames in targets: getCmd(snmpEngine, authData, transportTarget, ContextData(), *varNames, **dict(cbFun=cbFun, cbCtx=(authData, transportTarget))) snmpEngine.transportDispatcher.runDispatcher() pull-mibs-from-multiple-agents-at-once-over-ipv4-and-ipv6.py000066400000000000000000000047371354244100700356170ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/manager/cmdgen""" Walk multiple Agents at once ++++++++++++++++++++++++++++ Iterate over MIBs of multiple SNMP Agents asynchronously using the following options: * with SNMPv1, community 'public' and with SNMPv2c, community 'public' and with SNMPv3, user 'usr-md5-des', MD5 auth and DES privacy * over IPv4/UDP and over IPv6/UDP * to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 * pull variables till EOM """# from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) (CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('1.3.6.1.2.1')), ObjectType(ObjectIdentity('1.3.6.1.3.1')))), # 2-nd target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('1.3.6.1.4.1')),)), # 3-nd target (SNMPv3 over IPv4/UDP) (UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')),)), # 4-th target (SNMPv3 over IPv6/UDP) (UsmUserData('usr-md5-none', 'authkey1'), Udp6TransportTarget(('::1', 161)), (ObjectType(ObjectIdentity('IF-MIB', 'ifTable')),)) # N-th target # ... ) # Wait for responses or errors, submit GETNEXT requests for further OIDs # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): (authData, transportTarget) = cbCtx print('%s via %s' % (authData, transportTarget)) if errorIndication: print(errorIndication) return elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) return True # continue table retrieval snmpEngine = SnmpEngine() # Submit initial GETNEXT requests and wait for responses for authData, transportTarget, varBinds in targets: nextCmd(snmpEngine, authData, transportTarget, ContextData(), *varBinds, **dict(cbFun=cbFun, cbCtx=(authData, transportTarget))) snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/manager/cmdgen/pull-whole-mib.py000066400000000000000000000026601354244100700257500ustar00rootroot00000000000000""" Walk whole MIB ++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs in IF-MIB Functionally similar to: | $ snmpwalk -v3 -lauthNoPriv -u usr-md5-none -A authkey1 -X privkey1 \ | demo.snmplabs.com IF-MIB:: """# from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) return True # request lower layers to do GETNEXT and call us back snmpEngine = SnmpEngine() nextCmd(snmpEngine, UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')), ObjectType(ObjectIdentity('IF-MIB', 'ifTable')), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() query-multiple-snmp-engines-over-ipv4-and-ipv6.py000066400000000000000000000071011354244100700337010ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/manager/cmdgen""" Multiple SNMP engines +++++++++++++++++++++ Send multiple SNMP GET requests to multiple peers using multiple independend SNMP engines. Deal with peers asynchronously. SNMP options are: * with SNMPv1, community 'public' and with SNMPv2c, community 'public' and with SNMPv3, user 'usr-md5-des', MD5 auth and DES privacy * over IPv4/UDP and over IPv6/UDP * to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 * for instances of SNMPv2-MIB::sysDescr.0 and SNMPv2-MIB::sysLocation.0 MIB objects Within this script we have a single asynchronous TransportDispatcher and a single UDP-based transport serving two independent SNMP engines. We use a single instance of AsyncCommandGenerator with each of SNMP Engines to comunicate GET command request to remote systems. When we receive a [response] message from remote system we use a custom message router to choose what of the two SNMP engines data packet should be handed over. The selection criteria we employ here is based on peer's UDP port number. Other selection criterias are also possible. """# from pysnmp.hlapi.asyncore import * from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher # List of targets in the following format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) (CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 2-nd target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 1161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 3-nd target (SNMPv3 over IPv4/UDP) (UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 2161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))) # N-th target # ... ) # Wait for responses or errors # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): (snmpEngine, authData, transportTarget) = cbCtx print('snmpEngine %s: %s via %s' % (snmpEngine.snmpEngineID.prettyPrint(), authData, transportTarget)) if errorIndication: print(errorIndication) return True elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) return True else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) # Instantiate the single transport dispatcher object transportDispatcher = AsyncoreDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain transportDispatcher.registerRoutingCbFun( lambda td, ta, d: ta[1] % 3 and 'A' or 'B' ) snmpEngineA = SnmpEngine() snmpEngineA.registerTransportDispatcher(transportDispatcher, 'A') snmpEngineB = SnmpEngine() snmpEngineB.registerTransportDispatcher(transportDispatcher, 'B') for authData, transportTarget, varBinds in targets: snmpEngine = transportTarget.getTransportInfo()[1][1] % 3 and \ snmpEngineA or snmpEngineB getCmd(snmpEngine, authData, transportTarget, ContextData(), *varBinds, **dict(cbFun=cbFun, cbCtx=(snmpEngine, authData, transportTarget))) transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/manager/cmdgen/v2c-get.py000066400000000000000000000022441354244100700243600ustar00rootroot00000000000000""" SNMPv2c +++++++ Send SNMP GET request using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for two instances of SNMPv2-MIB::sysDescr.0 MIB object, Functionally similar to: | $ snmpget -v2c -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() getCmd(snmpEngine, CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/hlapi/asyncore/sync/000077500000000000000000000000001354244100700206425ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/000077500000000000000000000000001354244100700217405ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/000077500000000000000000000000001354244100700232375ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/custom-contextengineid.py000066400000000000000000000025771354244100700303230ustar00rootroot00000000000000""" INFORM with custom ContextEngineId ++++++++++++++++++++++++++++++++++ Send SNMP notification using the following options: * SNMPv3 * with user 'usr-md5-none', MD5 auth, no priv * send INFORM notification * in behalf of contextEngineId 0x8000000004030201, contextName '' * over IPv4/UDP * with TRAP ID 'warmStart' specified as a string OID Sending SNMPv3 Notification in behalf of non-default ContextEngineId requires having a collection of Managed Objects registered under the ContextEngineId being used. Functionally similar to: | $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 -E 0x8000000004030201 demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(OctetString(hexValue='8000000004030201')), 'inform', NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.2'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/custom-contextname.py000066400000000000000000000025351354244100700274530ustar00rootroot00000000000000""" INFORM with custom ContextName ++++++++++++++++++++++++++++++ Send SNMP notification using the following options: * SNMPv3 * with user 'usr-md5-none', MD5 auth, no priv * send INFORM notification * in behalf of contextEngineId = SnmpEngineId, contextName 'my-context' * over IPv4/UDP * with TRAP ID 'warmStart' specified as a string OID Sending SNMPv3 Notification in behalf of non-default ContextName requires having a collection of Managed Objects registered under the ContextName being used. Functionally similar to: | $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 -n my-context demo.snmplabs.com 12345 0.3.6.1.6.3.1.1.5.2 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(contextName='my-context'), 'inform', NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.2'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/custom-v1-trap.py000066400000000000000000000026351354244100700264210ustar00rootroot00000000000000""" Custom SNMPv1 TRAP ++++++++++++++++++ Send SNMPv1 TRAP through unified SNMPv3 message processing framework. Original v1 TRAP fields are mapped into dedicated variable-bindings, (see `RFC2576 `_) for details. * SNMPv1 * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #6 (enterpriseSpecific) and Specific Trap 432 * overriding Uptime value with 12345 * overriding Agent Address with '127.0.0.1' * overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 6 432 12345 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.4.1.20408.4.1.1.2.0.432'), ).addVarBinds( ('1.3.6.1.2.1.1.3.0', 12345), ('1.3.6.1.6.3.18.1.3.0', '127.0.0.1'), ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) ) if errorIndication: print(errorIndication) pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/default-v1-trap.py000066400000000000000000000022271354244100700265300ustar00rootroot00000000000000""" SNMPv1 TRAP with defaults +++++++++++++++++++++++++ Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #1 (warmStart) and Specific Trap 0 * with default Uptime * with default Agent Address * with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) ) if errorIndication: print(errorIndication) send-notification-with-additional-varbinds.py000066400000000000000000000022741354244100700340410ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg""" Sending additional var-binds ++++++++++++++++++++++++++++ Send SNMP notification using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send INFORM notification * with TRAP ID 'coldStart' specified as a MIB symbol * include managed object information specified as a MIB symbol Functionally similar to: | $ snmpinform -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'inform', NotificationType( ObjectIdentity('SNMPv2-MIB', 'coldStart') ).addVarBinds( ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0), 'my system') ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/v2c-trap-with-notification-objects.py000066400000000000000000000023351354244100700323360ustar00rootroot00000000000000""" SNMPv2c TRAP via NOTIFICATION-TYPE ++++++++++++++++++++++++++++++++++ Initialize TRAP message contents from variables specified in *NOTIFICATION-TYPE* SMI macro. * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * with TRAP ID 'linkUp' specified as a MIB symbol * include values for managed objects implicitly added to notification (via NOTIFICATION-TYPE->OBJECTS) Functionally similar to: | $ snmptrap -v2c -c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.2.2.1.1.123 i 123 1.3.6.1.2.1.2.2.1.7.123 i 1 1.3.6.1.2.1.2.2.1.8.123 i 1 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('IF-MIB', 'linkUp'), instanceIndex=(123,), objects={('IF-MIB', 'ifIndex'): 123, ('IF-MIB', 'ifAdminStatus'): 'up', ('IF-MIB', 'ifOperStatus'): 'up'} ) ) ) if errorIndication: print(errorIndication) pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/v3-inform.py000066400000000000000000000024371354244100700254370ustar00rootroot00000000000000""" INFORM, auth: MD5 privacy: DES ++++++++++++++++++++++++++++++ Send SNMP INFORM notification using the following options: * SNMPv3 * with user 'usr-md5-des', auth: MD5, priv DES * over IPv4/UDP * send INFORM notification * with TRAP ID 'warmStart' specified as a string OID * include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' Functionally similar to: | $ snmpinform -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 demo.snmplabs.com 12345 1.3.6.1.4.1.20408.4.1.1.2 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'inform', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0'), 'system name') ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/agent/ntforg/v3-trap.py000066400000000000000000000027001354244100700251040ustar00rootroot00000000000000""" SNMPv3 TRAP: auth SHA, privacy: AES128 ++++++++++++++++++++++++++++++++++++++ Send SNMP notification using the following options: * SNMPv3 * with authoritative snmpEngineId = 0x8000000001020304 (USM must be configured at the Receiver accordingly) * with user 'usr-sha-aes128', auth: SHA, priv: AES128 * over IPv4/UDP * send TRAP notification * with TRAP ID 'authenticationFailure' specified as a MIB symbol * do not include any additional managed object information SNMPv3 TRAPs requires pre-sharing the Notification Originator's value of SnmpEngineId with Notification Receiver. To facilitate that we will use static (e.g. not autogenerated) version of snmpEngineId. Functionally similar to: | $ snmptrap -v3 -e 8000000001020304 -l authPriv -u usr-sha-aes -A authkey1 -X privkey1 -a SHA -x AES demo.snmplabs.com 12345 1.3.6.1.4.1.20408.4.1.1.2 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(OctetString(hexValue='8000000001020304')), UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'trap', NotificationType(ObjectIdentity('SNMPv2-MIB', 'authenticationFailure')) ) ) if errorIndication: print(errorIndication) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/000077500000000000000000000000001354244100700222545ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/000077500000000000000000000000001354244100700235115ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/coerce-set-value-to-mib-spec.py000066400000000000000000000020201354244100700313350ustar00rootroot00000000000000""" Coerce value to SET to MIB spec +++++++++++++++++++++++++++++++ Send SNMP SET request using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * setting SNMPv2-MIB::sysName.0 to new value (type taken from MIB) Functionally similar to: | $ snmpset -v2c -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 = "new system name" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysORDescr', 1), 'new system name')) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/custom-asn1-mib-search-path.py000066400000000000000000000022061354244100700311770ustar00rootroot00000000000000""" Custom ASN.1 MIB path +++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for IF-MIB::ifInOctets.1 MIB object * pass non-default ASN.1 MIB source to MIB compiler Functionally similar to: | $ snmpget -v2c -c public -M /usr/share/snmp demo.snmplabs.com IF-MIB::ifInOctets.1 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1).addAsn1MibSource('file:///usr/share/snmp', 'http://mibs.snmplabs.com/asn1/@mib@'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/custom-contextengineid-and-contextname.py000066400000000000000000000027531354244100700336540ustar00rootroot00000000000000""" Custom ContextEngineId and ContextName ++++++++++++++++++++++++++++++++++++++ Send SNMP SET request using the following options: * with SNMPv3 with user 'usr-md5-none', MD5 auth and no privacy protocols * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * addressing particular set of Managed Objects at remote SNMP Engine by: * contextEngineId 0x80004fb805636c6f75644dab22cc and * contextName 'a172334d7d97871b72241397f713fa12' * setting SNMPv2-MIB::sysName.0 to new value (type taken from MIB) Functionally similar to: | $ snmpset -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -E 80004fb805636c6f75644dab22cc -n a172334d7d97871b72241397f713fa12 demo.snmplabs.com SNMPv2-MIB::sysORDescr.1 = "new system name" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(contextEngineId=OctetString(hexValue='80004fb805636c6f75644dab22cc'), contextName='da761cfc8c94d3aceef4f60f049105ba'), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysORDescr', 1), 'new system name')) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/custom-contextengineid.py000066400000000000000000000024531354244100700305660ustar00rootroot00000000000000""" Custom ContextEngineId ++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols * use remote SNMP Engine ID 0x80004fb805636c6f75644dab22cc (USM autodiscovery will run) * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * setting SNMPv2-MIB::sysName.0 to new value (type coerced from MIB) Functionally similar to: | $ snmpset -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -E 80004fb805636c6f75644dab22cc demo.snmplabs.com SNMPv2-MIB::sysORDescr.1 = "new system name" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), UsmUserData('usr-md5-des', 'authkey1', 'privkey1', securityEngineId=OctetString(hexValue='80004fb805636c6f75644dab22cc')), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0), 'new system name')) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/custom-pysnmp-mibs-search-path.py000066400000000000000000000030261354244100700320470ustar00rootroot00000000000000""" Custom PySNMP MIBs location +++++++++++++++++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs within TCP-MIB::tcpConnTable column * TCP-MIB Python module will be searched by a user-specified filesystem path (/opt/mib/pysnmp) and in Python package (python_packaged_mibs) which should be in sys.path Functionally similar to: | $ snmpbulkwalk -v3 -lnoAuthNoPriv -u usr-none-none -Cn0 -Cr50 demo.snmplabs.com TCP-MIB::tcpConnTable """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 50, ObjectType( ObjectIdentity('TCP-MIB', 'tcpConnTable').addMibSource('/opt/mibs/pysnmp').addMibSource('python_packaged_mibs') ), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/custom-timeout-and-retries.py000066400000000000000000000032111354244100700312710ustar00rootroot00000000000000""" Custom request timeout ++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for an OID in string form * use custom timeout and request retries values Transport timing settings (maximum number of request retries and individual request timeout in seconds) can be set on a per-target basis as explained by the code that follows. Keep in mind that while timeout value can be specified in fractions of a second, default pysnmp timer resolution is quite low (about 0.5 sec) so there's no much point in using timeouts which is not a multiple of 0.5 Internal timer can be programmatically adjusted to finer resolution if needed. If retries value is set to 0, pysnmp will issue a single request. Even if no response arrives, there will be no retry. Likewise, retries=1 means one initial request plus one retry. Functionally similar to: | $ snmpget -v1 -c public -t 2 -r 0 demo.snmplabs.com 1.3.6.1.2.1.1.1.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget( ('demo.snmplabs.com', 161), timeout=2.0, retries=0 ), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/custom-v3-security-name.py000066400000000000000000000022321354244100700305050ustar00rootroot00000000000000""" Custom SecurityName +++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-md5-none', securityName 'myuser' MD5 authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for an OID in text form The securityName parameter can be thought as an alias to userName and allows you to address a USM Table row just as userName does. However securityName can be made human-readable, also it is not an index in usmUserTable, thus duplicate securityName parameters are possible. """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1', securityName='myuser'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/fetch-variables-over-ipv6.py000066400000000000000000000021461354244100700307600ustar00rootroot00000000000000""" GET over IPv6 +++++++++++++ Send SNMP GET request using the following options: * with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols * over IPv6/UDP * to an Agent at [::1]:161 * for three OIDs in string form Functionally similar to: | $ snmpget -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 udp6:[::1]:161 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.2.0 1.3.6.1.2.1.1.3.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), Udp6TransportTarget(('::1', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.2.0')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/get-table-object-by-index.py000066400000000000000000000022011354244100700307030ustar00rootroot00000000000000""" GET table row +++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for IF-MIB::ifInOctets.1 and IF-MIB::ifOutOctets.1 MIB object * perform response OIDs and values resolution at MIB Functionally similar to: | $ snmpget -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 demo.snmplabs.com IF-MIB::ifInOctets.1 IF-MIB::ifOutOctets.1 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1)), ObjectType(ObjectIdentity('IF-MIB', 'ifOutOctets', 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/get-table-object-by-multiple-indices.py000066400000000000000000000025611354244100700330540ustar00rootroot00000000000000""" Fetch table row by composite index ++++++++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-sha-aes128', SHA auth, AES128 privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for TCP-MIB::tcpConnLocalAddress."0.0.0.0".22."0.0.0.0".0 MIB object Functionally similar to: | $ snmpget -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -a SHA -x AES demo.snmplabs.com TCP-MIB::tcpConnLocalAddress."0.0.0.0".22."0.0.0.0".0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('TCP-MIB', 'tcpConnLocalAddress', '0.0.0.0', 22, '0.0.0.0', 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) getbulk-fetch-scalar-and-table-variables-over-ipv6.py000066400000000000000000000027531354244100700354300ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen""" Fetch scalar and table variables ++++++++++++++++++++++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols * over IPv6/UDP * to an Agent at [::1]:161 * with values non-repeaters = 1, max-repetitions = 25 * for IP-MIB::ipAdEntAddr and all columns of the IF-MIB::ifEntry table * stop when response OIDs leave the scopes of the table Functionally similar to: | $ snmpbulkwalk -v3 -lauthPriv -u usr-md5-des -A authkey1 -X privkey1 -Cn1, -Cr25 demo.snmplabs.com IP-MIB::ipAdEntAddr IP-MIB::ipAddrEntry """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), Udp6TransportTarget(('::1', 161)), ContextData(), 1, 25, ObjectType(ObjectIdentity('IP-MIB', 'ipAdEntAddr')), ObjectType(ObjectIdentity('IP-MIB', 'ipAddrEntry')), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/getbulk-limit-number-of-packets.py000066400000000000000000000025131354244100700321550ustar00rootroot00000000000000""" Walk Agent, limit number of packets +++++++++++++++++++++++++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs past SNMPv2-MIB::system * run till end-of-mib condition is reported by Agent OR maxCalls == 10 request-response interactions occur Functionally similar to: | $ snmpbulkwalk -v3 -lnoAuthNoPriv -u usr-none-none -Cn0 -Cr50 demo.snmplabs.com SNMPv2-MIB::system """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 50, ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')), maxCalls=10): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/getbulk-limit-number-of-variables.py000066400000000000000000000026561354244100700325030ustar00rootroot00000000000000""" Walk MIB, limit number of response rows +++++++++++++++++++++++++++++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * with values non-repeaters = 0, max-repetitions = 25 * for two OIDs in string form * stop when response OIDs leave the scopes of initial OIDs OR number of response rows reach fixed value (20) Functionally similar to: | $ snmpbulkwalk -v2c -c public demo.snmplabs.com -Cn0 -Cr25 1.3.6.1.2.1.2.2 1.3.6.1.2.1.2.3 """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 25, ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2')), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.3')), lexicographicMode=False, maxRows=20): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([ x.prettyPrint() for x in varBind ])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/getnext-limit-number-of-variables.py000066400000000000000000000030041354244100700325100ustar00rootroot00000000000000""" Fetch fixed amount of MIB variables +++++++++++++++++++++++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv3, user 'usr-sha-aes128', SHA auth, AES128 privacy * over UDP/IPv4 * to an Agent at demo.snmplabs.com:161 * for all OIDs past SNMPv2-MIB * run till end-of-mib condition is reported by Agent OR maxRows == 100 * ignoring non-increasing OIDs whenever reported by Agent Functionally similar to: | $ snmpwalk -v3 -lauthPriv -u usr-sha-aes128 -A authkey1 -X privkey1 -a MD5 -x AES demo.snmplabs.com SNMPv2-MIB::system """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB')), maxRows=100, ignoreNonIncreasingOid=True): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/getnext-multiple-oids-to-eom.py000066400000000000000000000023661354244100700315330ustar00rootroot00000000000000""" Fetch two OID branches ++++++++++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for two OIDs in string form * stop when response OIDs leave the scopes of initial OIDs Functionally similar to: | $ snmpwalk -v2c -c public demo.snmplabs.com 1.3.6.1.2.1.2.2.1.2 1.3.6.1.2.1.2.2.1.3 """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.2')), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2.1.3')), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([ x.prettyPrint() for x in varBind ])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/multiple-get-calls.py000066400000000000000000000024571354244100700275770ustar00rootroot00000000000000""" Sequence Of GET's +++++++++++++++++ Send two SNMP GET requests in a row using the following options: * with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for IF-MIB::ifInOctets.1 and IF-MIB::ifOutOctets.1 MIB objects Use a queue of MIB objects to query. The next() call is used to forward Python iterator to the position where it could consume input Functionally similar to: | $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com IF-MIB::ifInOctets.1 """# from pysnmp.hlapi import * queue = [[ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1))], [ObjectType(ObjectIdentity('IF-MIB', 'ifOutOctets', 1))]] iter = getCmd(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData()) next(iter) while queue: errorIndication, errorStatus, errorIndex, varBinds = iter.send(queue.pop()) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/preload-pysnmp-mibs.py000066400000000000000000000023001354244100700277600ustar00rootroot00000000000000""" Preload PySNMP MIBs +++++++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs starting from 1.3.6 * preload all Python MIB modules found in search path Functionally similar to: | $ snmpwalk -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -m ALL demo.snmplabs.com:161 1.3.6 """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6').loadMibs())): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-mib.py000066400000000000000000000021231354244100700267160ustar00rootroot00000000000000""" Walk whole MIB ++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs in IF-MIB Functionally similar to: | $ snmpwalk -v3 -lauthPriv -u usr-md5-none -A authkey1 -X privkey1 demo.snmplabs.com IF-MIB:: """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB'))): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/pull-whole-snmp-table.py000066400000000000000000000031631354244100700302160ustar00rootroot00000000000000""" Fetch whole SNMP table ++++++++++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for some columns of the IF-MIB::ifEntry table * stop when response OIDs leave the scopes of initial OIDs Functionally similar to: | $ snmpwalk -v1 -c public demo.snmplabs.com IF-MIB::ifDescr IF-MIB::ifType IF-MIB::ifMtu IF-MIB::ifSpeed IF-MIB::ifPhysAddress IF-MIB::ifType """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')), ObjectType(ObjectIdentity('IF-MIB', 'ifType')), ObjectType(ObjectIdentity('IF-MIB', 'ifMtu')), ObjectType(ObjectIdentity('IF-MIB', 'ifSpeed')), ObjectType(ObjectIdentity('IF-MIB', 'ifPhysAddress')), ObjectType(ObjectIdentity('IF-MIB', 'ifType')), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) query-agents-from-multuple-threads-over-ipv4-and-ipv6.py000066400000000000000000000102571354244100700361460ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen""" Query Agents from multiple threads ++++++++++++++++++++++++++++++++++ Send a bunch of SNMP GET requests simultaneously using the following options: * process 5 GET requests in 3 parallel threads * with SNMPv1, community 'public' and with SNMPv2c, community 'public' and with SNMPv3, user 'usr-md5-des', MD5 auth and DES privacy * over IPv4/UDP and over IPv6/UDP * to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 * for instances of SNMPv2-MIB::sysDescr.0 and SNMPv2-MIB::sysLocation.0 MIB objects """# from sys import version_info from threading import Thread from pysnmp.hlapi import * if version_info[0] == 2: from Queue import Queue else: from queue import Queue # List of targets in the following format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) (CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 2-nd target (SNMPv2c over IPv4/UDP) (CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 3-nd target (SNMPv2c over IPv4/UDP) - same community and # different transport address. (CommunityData('public'), UdpTransportTarget(('localhost', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysContact', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysName', 0)))), # 4-nd target (SNMPv3 over IPv4/UDP) (UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # 5-th target (SNMPv3 over IPv6/UDP) (UsmUserData('usr-md5-none', 'authkey1'), Udp6TransportTarget(('::1', 161)), (ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))), # N-th target # ... ) class Worker(Thread): def __init__(self, requests, responses): Thread.__init__(self) self.snmpEngine = SnmpEngine() self.requests = requests self.responses = responses self.setDaemon(True) self.start() def run(self): while True: authData, transportTarget, varBinds = self.requests.get() self.responses.append( next(getCmd(self.snmpEngine, authData, transportTarget, ContextData(), *varBinds)) ) if hasattr(self.requests, 'task_done'): # 2.5+ self.requests.task_done() class ThreadPool(object): def __init__(self, num_threads): self.requests = Queue(num_threads) self.responses = [] for _ in range(num_threads): Worker(self.requests, self.responses) def addRequest(self, authData, transportTarget, varBinds): self.requests.put((authData, transportTarget, varBinds)) def getResponses(self): return self.responses def waitCompletion(self): if hasattr(self.requests, 'join'): self.requests.join() # 2.5+ else: from time import sleep # this is a lame substitute for missing .join() # adding an explicit synchronization might be a better solution while not self.requests.empty(): sleep(1) pool = ThreadPool(3) # Submit GET requests for authData, transportTarget, varBinds in targets: pool.addRequest(authData, transportTarget, varBinds) # Wait for responses or errors pool.waitCompletion() # Walk through responses for errorIndication, errorStatus, errorIndex, varBinds in pool.getResponses(): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/set-multiple-scalar-values.py000066400000000000000000000027141354244100700312530ustar00rootroot00000000000000""" SET scalars values ++++++++++++++++++ Send SNMP SET request using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * setting three var-bindings to new values Please note, that in this example MIB lookup is only used for the second var-bindins. For the rest, value types are inferred from passed objects. Functionally similar to: | $ snmpset -v1 -c public demo.snmplabs.com 1.3.6.1.2.1.1.9.1.2.1 o 1.3.6.1.4.1.20408.1.1 1.3.6.1.2.1.1.9.1.2.1 = 1.3.6.1.4.1.20408.1.1 1.3.6.1.2.1.1.9.1.3.1 s "new system name" """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.9.1.2.1'), ObjectIdentifier('1.3.6.1.4.1.20408.1.1')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.9.1.2.1'), '1.3.6.1.4.1.20408.1.1'), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.9.1.3.1'), OctetString('new system name'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/specific-v3-engine-id.py000066400000000000000000000046561354244100700300460ustar00rootroot00000000000000""" Discover SNMPv3 SecurityEngineId ++++++++++++++++++++++++++++++++ Send SNMP GET request using the following scenario and options: * try to communicate with a SNMPv3 Engine using: * a non-existing user * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * if remote SNMP Engine ID is discovered, send SNMP GET request: * with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy at discovered securityEngineId * to the same SNMP Engine ID * for an OID in text form """# from pysnmp.hlapi import * snmpEngine = SnmpEngine() transportTarget = UdpTransportTarget(('demo.snmplabs.com', 161)) # # To discover remote SNMP EngineID we will tap on SNMP engine inner workings # by setting up execution point observer setup on INTERNAL class PDU processing # observerContext = {} # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at execution point's local scope snmpEngine.observer.registerObserver( lambda e, p, v, c: c.update(securityEngineId=v['securityEngineId']), 'rfc3412.prepareDataElements:internal', cbCtx=observerContext ) # Send probe SNMP request with invalid credentials authData = UsmUserData('non-existing-user') errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(snmpEngine, authData, transportTarget, ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ) # See if our SNMP engine received REPORT PDU containing securityEngineId if 'securityEngineId' not in observerContext: print("Can't discover peer EngineID, errorIndication: %s" % errorIndication) raise Exception() securityEngineId = observerContext.pop('securityEngineId') print('Remote securityEngineId = %s' % securityEngineId.prettyPrint()) # # Query remote SNMP Engine using usmUserTable entry configured for it # authData = UsmUserData('usr-md5-none', 'authkey1', securityEngineId=securityEngineId) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(snmpEngine, authData, transportTarget, ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/usm-localized-keys.py000066400000000000000000000034111354244100700276030ustar00rootroot00000000000000""" SNMPv3: localized auth and privacy keys +++++++++++++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-md5-des', MD5 authentication, DES encryption * use localized auth and privacy keys instead of pass-phrase or master keys * configure authoritative SNMP engine ID (0x0000000000 can be used as well) * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for SNMPv2-MIB::sysDescr.0 MIB object instance Functionally similar to: | $ snmpget -v3 -l authPriv \ -u usr-md5-des \ -e 0x80004fb805636c6f75644dab22cc \ -3k 0x6b99c475259ef7976cf8d028a3381eeb \ -3K 0x92b5ef98f0a216885e73944e58c07345 \ demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-md5-des', authKey=OctetString( hexValue='6b99c475259ef7976cf8d028a3381eeb'), privKey=OctetString( hexValue='92b5ef98f0a216885e73944e58c07345'), authKeyType=usmKeyTypeLocalized, privKeyType=usmKeyTypeLocalized, securityEngineId=OctetString( hexValue='80004fb805636c6f75644dab22cc')), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/usm-master-keys.py000066400000000000000000000027731354244100700271420ustar00rootroot00000000000000""" SNMPv3: master auth and privacy keys ++++++++++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-md5-des', MD5 authentication, DES encryption * use master auth and privacy keys instead of pass-phrase * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for SNMPv2-MIB::sysDescr.0 MIB object instance Functionally similar to: | $ snmpget -v3 -l authPriv \ -u usr-md5-des \ -3m 0x1dcf59e86553b3afa5d32fd5d61bf0cf \ -3M 0xec5ab55e93e1d85cb6846d0f23e845e0 \ demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-md5-des', authKey=OctetString( hexValue='1dcf59e86553b3afa5d32fd5d61bf0cf'), privKey=OctetString( hexValue='ec5ab55e93e1d85cb6846d0f23e845e0'), authKeyType=usmKeyTypeMaster, privKeyType=usmKeyTypeMaster), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/usm-md5-des.py000066400000000000000000000020221354244100700261170ustar00rootroot00000000000000""" SNMPv3: auth MD5, privacy DES +++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-md5-des', MD5 authentication, DES encryption * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for IF-MIB::ifInOctets.1 MIB object Functionally similar to: | $ snmpget -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 demo.snmplabs.com IF-MIB::ifInOctets.1 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/usm-md5-none.py000066400000000000000000000017711354244100700263150ustar00rootroot00000000000000""" SNMPv3: auth MD5, no privacy ++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for IF-MIB::ifInOctets.1 MIB object Functionally similar to: | $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com IF-MIB::ifInOctets.1 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/usm-none-none.py000066400000000000000000000017161354244100700265660ustar00rootroot00000000000000""" SNMPv3: no auth, no privacy +++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no encryption * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for IF-MIB::ifInOctets.1 MIB object Functionally similar to: | $ snmpget -v3 -l noAuthNoPriv -u usr-none-none demo.snmplabs.com IF-MIB::ifInOctets.1 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets', 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/usm-sha-aes128.py000066400000000000000000000031001354244100700264330ustar00rootroot00000000000000""" SNMPv3: auth SHA, privacy AES128 ++++++++++++++++++++++++++++++++ Send SNMP GET request using the following options: * with SNMPv3, user 'usr-sha-aes', SHA authentication, AES128 encryption * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for SNMPv2-MIB::sysDescr.0 MIB object Available authentication protocols: #. usmHMACMD5AuthProtocol #. usmHMACSHAAuthProtocol #. usmHMAC128SHA224AuthProtocol #. usmHMAC192SHA256AuthProtocol #. usmHMAC256SHA384AuthProtocol #. usmHMAC384SHA512AuthProtocol #. usmNoAuthProtocol Available privacy protocols: #. usmDESPrivProtocol #. usm3DESEDEPrivProtocol #. usmAesCfb128Protocol #. usmAesCfb192Protocol #. usmAesCfb256Protocol #. usmNoPrivProtocol Functionally similar to: | $ snmpget -v3 -l authPriv -u usr-sha-aes -A authkey1 -X privkey1 -a SHA -x AES demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData('usr-sha-aes', 'authkey1', 'privkey1', authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/v1-get.py000066400000000000000000000016471354244100700251760ustar00rootroot00000000000000""" SNMPv1 ++++++ Send SNMP GET request using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for two instances of SNMPv2-MIB::sysDescr.0 MIB object, Functionally similar to: | $ snmpget -v1 -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/v2c-get.py000066400000000000000000000016761354244100700253440ustar00rootroot00000000000000""" SNMPv2c +++++++ Send SNMP GET request using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for two OIDs in string form Functionally similar to: | $ snmpget -v2c -c public demo.snmplabs.com 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.6.0 """# from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')), ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0'))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/v2c-getbulk.py000066400000000000000000000024721354244100700262150ustar00rootroot00000000000000""" Bulk walk MIB +++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * with values non-repeaters = 0, max-repetitions = 25 * for two OIDs in string form * stop when response OIDs leave the scopes of initial OIDs Functionally similar to: | $ snmpbulkwalk -v2c -c public demo.snmplabs.com -Cn0 -Cr25 1.3.6.1.2.1.2.2 1.3.6.1.2.1.2.3 """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 25, ObjectType(ObjectIdentity('1.3.6.1.2.1.2.2')), ObjectType(ObjectIdentity('1.3.6.1.2.1.2.3')), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/asyncore/sync/manager/cmdgen/waive-mib-lookup.py000066400000000000000000000024111354244100700272500ustar00rootroot00000000000000""" Waive MIB lookup ++++++++++++++++ Perform SNMP GETNEXT operation with the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for an OID in string form * do not resolve response OIDs and values into human-freidly form False lookupMib keyword arguments could make pysnmp waiving OIDs and values resolution in response variable-bindings, into human friendly form. Functionally similar to: | $ snmpwalk -v2c -c public -ObentU demo.snmplabs.com 1.3.6.1.2.1 """# from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('1.3.6.1.2.1.1')), lookupMib=False): if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) break else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) pysnmp-4.4.12/examples/hlapi/trollius/000077500000000000000000000000001354244100700177205ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/trollius/agent/000077500000000000000000000000001354244100700210165ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/trollius/agent/ntforg/000077500000000000000000000000001354244100700223155ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/trollius/agent/ntforg/default-v1-trap.py000066400000000000000000000033571354244100700256130ustar00rootroot00000000000000""" SNMPv1 TRAP with defaults +++++++++++++++++++++++++ Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #1 (warmStart) and Specific Trap 0 * with default Uptime * with default Agent Address * with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' * use trollius I/O framework Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system" """# import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(): snmpEngine = SnmpEngine() (errorIndication, errorStatus, errorIndex, varBinds) = yield trollius.From( sendNotification( snmpEngine, CommunityData('public'), # mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 162)), ContextData(), 'inform', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s: at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() trollius.get_event_loop().run_until_complete(run()) pysnmp-4.4.12/examples/hlapi/trollius/manager/000077500000000000000000000000001354244100700213325ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/trollius/manager/cmdgen/000077500000000000000000000000001354244100700225675ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/trollius/manager/cmdgen/getbulk-to-eom.py000066400000000000000000000032331354244100700257750ustar00rootroot00000000000000""" Bulk walk MIB +++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs past SNMPv2-MIB::system * run till end-of-mib condition is reported by Agent * based on trollius I/O framework Functionally similar to: | $ snmpbulkwalk -v3 -lnoAuthNoPriv -u usr-none-none -Cn0 -Cr50 demo.snmplabs.com SNMPv2-MIB::system """# import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield trollius.From( bulkCmd(snmpEngine, UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 50, *varBinds) ) if errorIndication: print(errorIndication) break elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = trollius.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))]) ) pysnmp-4.4.12/examples/hlapi/trollius/manager/cmdgen/v1-get.py000066400000000000000000000023441354244100700242470ustar00rootroot00000000000000""" SNMPv1 ++++++ Send SNMP GET request using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for an instance of SNMPv2-MIB::sysDescr.0 MIB object * Based on trollius I/O framework Functionally similar to: | $ snmpget -v1 -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(): snmpEngine = SnmpEngine() (errorIndication, errorStatus, errorIndex, varBinds) = yield trollius.From( getCmd(snmpEngine, CommunityData('public', mpModel=0), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() trollius.get_event_loop().run_until_complete(run()) pysnmp-4.4.12/examples/hlapi/twisted/000077500000000000000000000000001354244100700175265ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/twisted/agent/000077500000000000000000000000001354244100700206245ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/twisted/agent/ntforg/000077500000000000000000000000001354244100700221235ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/twisted/agent/ntforg/default-v1-trap.py000066400000000000000000000033601354244100700254130ustar00rootroot00000000000000""" SNMPv1 TRAP with defaults +++++++++++++++++++++++++ Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #1 (warmStart) and Specific Trap 0 * with default Uptime * with default Agent Address * with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s "my system" """# from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print('%s: %s at %s' % ( hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?' ) ) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print('%s failure: %s' % (hostname, errorIndication)) # noinspection PyUnusedLocal def run(reactor, hostname): d = sendNotification( SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget((hostname, 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(run, ['demo.snmplabs.com']) pysnmp-4.4.12/examples/hlapi/twisted/agent/ntforg/multiple-notifications-at-once.py000066400000000000000000000043421354244100700305260ustar00rootroot00000000000000""" Multiple concurrent notifications +++++++++++++++++++++++++++++++++ Send multiple SNMP notifications at once using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP and INFORM notification * to multiple Managers * with TRAP ID 'coldStart' specified as a MIB symbol * include managed object information specified as var-bind objects pair Here we tag each SNMP-COMMUNITY-MIB::snmpCommunityTable row with the same tag as SNMP-TARGET-MIB::snmpTargetAddrTable row what leads to excessive tables information. Functionally similar to: | $ snmptrap -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 | $ snmpinform -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 """# from twisted.internet.defer import DeferredList from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print('%s failure: %s' % (hostname, errorIndication)) # noinspection PyUnusedLocal def sendone(reactor, snmpEngine, hostname, notifyType): d = sendNotification( snmpEngine, CommunityData('public', tag=hostname), UdpTransportTarget((hostname, 162), tagList=hostname), ContextData(), notifyType, NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', OctetString('my system')) ) ) d.addCallback(success, hostname).addErrback(failure, hostname) return d def sendall(reactor, destinations): snmpEngine = SnmpEngine() return DeferredList( [sendone(reactor, snmpEngine, hostname, notifyType) for hostname, notifyType in destinations] ) react(sendall, [[('demo.snmplabs.com', 'trap'), ('demo.snmplabs.com', 'inform')]]) pysnmp-4.4.12/examples/hlapi/twisted/agent/ntforg/v2c-trap-inline-callbacks.py000066400000000000000000000023471354244100700273320ustar00rootroot00000000000000""" SNMPv2c TRAP via Twisted inline callbacks +++++++++++++++++++++++++++++++++++++++++ Send SNMPv2c TRAP through unified SNMPv3 message processing framework using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * with Generic Trap #1 (warmStart) and Specific Trap 0 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v2c -c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 1.3.6.1.2.1.1.1.0 s "Hello from Twisted" """# from twisted.internet.task import react, defer from pysnmp.hlapi.twisted import * @defer.inlineCallbacks def sendtrap(reactor, snmpEngine, hostname): yield sendNotification( snmpEngine, CommunityData('public', mpModel=0), UdpTransportTarget((hostname, 162)), ContextData(), 'trap', NotificationType( ObjectIdentity('1.3.6.1.6.3.1.1.5.2') ).addVarBinds( ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), OctetString('Hello from Twisted')) ) ) # Preserve SnmpEngine instance across [potentially] multiple calls to safe on initialization snmpEngine = SnmpEngine() react(sendtrap, [snmpEngine, 'demo.snmplabs.com']) pysnmp-4.4.12/examples/hlapi/twisted/manager/000077500000000000000000000000001354244100700211405ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/000077500000000000000000000000001354244100700223755ustar00rootroot00000000000000pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/custom-timeout-and-retries.py000066400000000000000000000026611354244100700301650ustar00rootroot00000000000000""" SNMPv2c +++++++ Send SNMP GET request using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP with non-default timeout and no retries * to an Agent at demo.snmplabs.com:161 * for two instances of SNMPv2-MIB::sysDescr.0 MIB object, * based on Twisted I/O framework Functionally similar to: | $ snmpget -v2c -c public -r 0 -t 2 demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print('%s failure: %s' % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSysDescr(reactor, hostname): snmpEngine = SnmpEngine() d = getCmd(snmpEngine, CommunityData('public'), UdpTransportTarget((hostname, 161), timeout=2.0, retries=0), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(getSysDescr, ['demo.snmplabs.com']) pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/getbulk-to-eom.py000066400000000000000000000031371354244100700256060ustar00rootroot00000000000000""" Bulk walk MIB +++++++++++++ Send a series of SNMP GETBULK requests using the following options: * with SNMPv3, user 'usr-none-none', no authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs past SNMPv2-MIB::system * run till end-of-mib condition is reported by Agent * based on Twisted I/O framework Functionally similar to: | $ snmpbulkwalk -v3 -lnoAuthNoPriv -u usr-none-none -Cn0 -Cr50 demo.snmplabs.com SNMPv2-MIB::system """# from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) - 1][0] or '?')) else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[-1]): return getbulk(reactor, snmpEngine, *varBindTable[-1]) def failure(errorIndication): print(errorIndication) def getbulk(reactor, snmpEngine, varBinds): d = bulkCmd(snmpEngine, UsmUserData('usr-none-none'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), 0, 50, varBinds) d.addCallback(success, reactor, snmpEngine).addErrback(failure) return d react(getbulk, [SnmpEngine(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))]) pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/multiple-concurrent-queries.py000066400000000000000000000033541354244100700304420ustar00rootroot00000000000000""" Concurrent queries ++++++++++++++++++ Send multiple SNMP GET requests at once using the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for two instances of SNMPv2-MIB::sysDescr.0 and SNMPv2-MIB::sysLocation.0 MIB object, * based on Twisted I/O framework Functionally similar to: | $ snmpget -v2c -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 | $ snmpget -v2c -c public demo.snmplabs.com SNMPv2-MIB::sysLocation.0 """# from twisted.internet.defer import DeferredList from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print('%s failure: %s' % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSystem(reactor, hostname): snmpEngine = SnmpEngine() def getScalar(objectType): d = getCmd(snmpEngine, CommunityData('public', mpModel=0), UdpTransportTarget((hostname, 161)), ContextData(), objectType) d.addCallback(success, hostname).addErrback(failure, hostname) return d return DeferredList( [getScalar(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))), getScalar(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysLocation', 0)))] ) react(getSystem, ['demo.snmplabs.com']) pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/pull-mibs-from-multiple-agents-at-once.py000066400000000000000000000036311354244100700322530ustar00rootroot00000000000000""" Walk multiple Agents at once ++++++++++++++++++++++++++++ * with SNMPv3 with user 'usr-md5-none', MD5 auth and no privacy protocols * over IPv4/UDP * to Agents at demo.snmplabs.com:161 and demo.snmplabs.com:1161 * for multiple MIB subtrees and tables * for whole MIB * based on Twisted I/O framework Functionally similar to: | $ snmpget -v2c -c public demo.snmplabs.com:161 SNMPv2-MIB::system | $ snmpget -v2c -c public demo.snmplabs.comL1161 SNMPv2-MIB::system """# from twisted.internet.defer import DeferredList from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine, hostname): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) - 1][0] or '?')) else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[-1]): return getbulk(reactor, snmpEngine, hostname, *varBindTable[-1]) def failure(errorIndication): print(errorIndication) def getbulk(reactor, snmpEngine, hostname, varBinds): d = bulkCmd(snmpEngine, UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(hostname), ContextData(), 0, 25, varBinds) d.addCallback(success, reactor, snmpEngine, hostname).addErrback(failure) return d def getall(reactor, hostnames): snmpEngine = SnmpEngine() return DeferredList( [getbulk(reactor, snmpEngine, hostname, ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))) for hostname in hostnames] ) react(getall, [(('demo.snmplabs.com', 161), ('demo.snmplabs.com', 1161))]) pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/pull-whole-mib.py000066400000000000000000000030141354244100700256020ustar00rootroot00000000000000""" Walk whole MIB ++++++++++++++ Send a series of SNMP GETNEXT requests using the following options: * with SNMPv3, user 'usr-md5-none', MD5 authentication, no privacy * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for all OIDs in IF-MIB * based on Twisted I/O framework Functionally similar to: | $ snmpwalk -v3 -lauthPriv -u usr-md5-none -A authkey1 -X privkey1 demo.snmplabs.com IF-MIB:: """# from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) - 1][0] or '?')) else: for varBindRow in varBindTable: for varBind in varBindRow: print(' = '.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[-1]): return getnext(reactor, snmpEngine, *varBindTable[-1]) def failure(errorIndication): print(errorIndication) def getnext(reactor, snmpEngine, varBinds): d = nextCmd(snmpEngine, UsmUserData('usr-md5-none', 'authkey1'), UdpTransportTarget(('demo.snmplabs.com', 161)), ContextData(), varBinds) d.addCallback(success, reactor, snmpEngine).addErrback(failure) return d react(getnext, [SnmpEngine(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'system'))]) pysnmp-4.4.12/examples/hlapi/twisted/manager/cmdgen/v1-get.py000066400000000000000000000025071354244100700240560ustar00rootroot00000000000000""" SNMPv1 ++++++ Send SNMP GET request using the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for two instances of SNMPv2-MIB::sysDescr.0 MIB object, * based on Twisted I/O framework Functionally similar to: | $ snmpget -v1 -c public demo.snmplabs.com SNMPv2-MIB::sysDescr.0 """# from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print('%s: %s at %s' % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for varBind in varBinds: print(' = '.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print('%s failure: %s' % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSysDescr(reactor, hostname): d = getCmd(SnmpEngine(), CommunityData('public', mpModel=0), UdpTransportTarget((hostname, 161)), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(getSysDescr, ['demo.snmplabs.com']) pysnmp-4.4.12/examples/smi/000077500000000000000000000000001354244100700155365ustar00rootroot00000000000000pysnmp-4.4.12/examples/smi/agent/000077500000000000000000000000001354244100700166345ustar00rootroot00000000000000pysnmp-4.4.12/examples/smi/agent/custom-managed-object.py000066400000000000000000000031041354244100700233540ustar00rootroot00000000000000""" Implementing MIB objects ++++++++++++++++++++++++ This script explains how SNMP Agent application could model real-world data as Managed Objects defined in MIB. """# from pysnmp.smi import builder # MIB Builder is normally pre-created by SNMP engine mibBuilder = builder.MibBuilder() # # This may be done in a stand-alone file and then loaded up # by SNMP Agent # # A base class for a custom Managed Object MibScalarInstance, = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance' ) # Managed object specification sysLocation, = mibBuilder.importSymbols('SNMPv2-MIB', 'sysLocation') # Custom Managed Object class MySysLocationInstance(MibScalarInstance): # noinspection PyUnusedLocal def readGet(self, name, *args): # Just return a custom value return name, self.syntax.clone('The Leaky Cauldron') sysLocationInstance = MySysLocationInstance( sysLocation.name, (0,), sysLocation.syntax ) # Register Managed Object with a MIB tree mibBuilder.exportSymbols( # '__' prefixed MIB modules take precedence on indexing '__MY-LOCATION-MIB', sysLocationInstance=sysLocationInstance ) if __name__ == '__main__': # # This is what is done internally by Agent. # from pysnmp.smi import instrum, exval mibInstrum = instrum.MibInstrumController(mibBuilder) print('Remote manager read access to MIB instrumentation (table walk)') oid, val = (), None while 1: oid, val = mibInstrum.readNextVars(((oid, val),))[0] if exval.endOfMib.isSameTypeWith(val): break print(oid, val.prettyPrint()) pysnmp-4.4.12/examples/smi/agent/operations-on-managed-objects.py000066400000000000000000000031201354244100700250200ustar00rootroot00000000000000""" Agent operations on MIB +++++++++++++++++++++++ This script explains how SNMP Agent application manipulates its MIB possibly triggered by SNMP Manager's commands. """# # SNMP agent backend e.g. Agent access to Managed Objects from pysnmp.smi import builder, instrum, exval print('Loading MIB modules...'), mibBuilder = builder.MibBuilder().loadModules( 'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB' ) print('done') print('Building MIB tree...'), mibInstrum = instrum.MibInstrumController(mibBuilder) print('done') print('Building table entry index from human-friendly representation...'), snmpCommunityEntry, = mibBuilder.importSymbols( 'SNMP-COMMUNITY-MIB', 'snmpCommunityEntry' ) instanceId = snmpCommunityEntry.getInstIdFromIndices('my-router') print('done') print('Create/update SNMP-COMMUNITY-MIB::snmpCommunityEntry table row: ') varBinds = mibInstrum.writeVars( ((snmpCommunityEntry.name + (2,) + instanceId, 'mycomm'), (snmpCommunityEntry.name + (3,) + instanceId, 'mynmsname'), (snmpCommunityEntry.name + (7,) + instanceId, 'volatile')) ) for oid, val in varBinds: print('%s = %s' % ('.'.join([str(x) for x in oid]), not val.isValue and 'N/A' or val.prettyPrint())) print('done') print('Read whole MIB (table walk)') oid, val = (), None while True: oid, val = mibInstrum.readNextVars(((oid, val),))[0] if exval.endOfMib.isSameTypeWith(val): break print('%s = %s' % ('.'.join([str(x) for x in oid]), not val.isValue and 'N/A' or val.prettyPrint())) print('done') print('Unloading MIB modules...'), mibBuilder.unloadModules() print('done') pysnmp-4.4.12/examples/smi/manager/000077500000000000000000000000001354244100700171505ustar00rootroot00000000000000pysnmp-4.4.12/examples/smi/manager/configure-mib-viewer-and-resolve-pdu-varbinds.py000066400000000000000000000024421354244100700303620ustar00rootroot00000000000000""" PDU var-binds to MIB objects ++++++++++++++++++++++++++++ This script explains how Python application could turn SNMP PDU variable-bindings into MIB objects or the other way around. The code that configures MIB compiler is similar to what happens inside the pysnmp.hlapi API. """# from pysnmp.smi import builder, view, compiler, rfc1902 # Assemble MIB browser mibBuilder = builder.MibBuilder() mibViewController = view.MibViewController(mibBuilder) compiler.addMibCompiler(mibBuilder, sources=['file:///usr/share/snmp/mibs', 'http://mibs.snmplabs.com/asn1/@mib@']) # Pre-load MIB modules we expect to work with mibBuilder.loadModules('SNMPv2-MIB', 'SNMP-COMMUNITY-MIB') # This is what we can get in TRAP PDU varBinds = [ ('1.3.6.1.2.1.1.3.0', 12345), ('1.3.6.1.6.3.1.1.4.1.0', '1.3.6.1.6.3.1.1.5.2'), ('1.3.6.1.6.3.18.1.3.0', '0.0.0.0'), ('1.3.6.1.6.3.18.1.4.0', ''), ('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'), ('1.3.6.1.2.1.1.1.0', 'my system') ] # Run var-binds through MIB resolver # You may want to catch and ignore resolution errors here varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds] for varBind in varBinds: print(varBind.prettyPrint()) pysnmp-4.4.12/examples/smi/manager/convert-between-pdu-varbinds-and-mib-objects.py000066400000000000000000000073011354244100700301620ustar00rootroot00000000000000""" MIB objects to PDU var-binds ++++++++++++++++++++++++++++ This script explains how Python application (typically pysnmp-based SNMP Manager) could turn SNMP PDU variable-bindings into MIB objects or the other way around. The code below does not explicitly add MIB compiler - that happens behind the scenes. Examples below try to demo different kinds of MIB objects to work with. """# from pysnmp.smi import builder, view, rfc1902, error # MIB Builder manages pysnmp MIBs mibBuilder = builder.MibBuilder() # MIB View Controller implements various queries to loaded MIBs mibView = view.MibViewController(mibBuilder) # Obtain MIB object information by MIB object name mibVar = rfc1902.ObjectIdentity('IF-MIB', 'ifInOctets', 1) # Optionally attach PySMI MIB compiler to MIB Builder that would # create pysnmp MIBs on demand from ASN.1 sources downloaded from # a web site. try: mibVar.addAsn1MibSource('http://mibs.snmplabs.com/asn1/@mib@') except error.SmiError: print('WARNING: not using MIB compiler (PySMI not installed)') mibVar.resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by its [sequence] OID mibVar = rfc1902.ObjectIdentity(tuple(mibVar)).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by its [string] OID mibVar = rfc1902.ObjectIdentity(str(mibVar)).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by a mix of OID/label parts mibVar = rfc1902.ObjectIdentity((1, 3, 6, 1, 2, 'mib-2', 1, 'sysDescr')).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by a label mibVar = rfc1902.ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr').resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain the first MIB object in given MIB module mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB').resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain the last MIB object in given MIB module mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB', last=True).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Another way to obtain the first (or last) symbol in MIB module mibVar = rfc1902.ObjectIdentity('SNMPv2-MIB', '').resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB symbol from whatever MIB it is defined at (MIB should be loaded) mibVar = rfc1902.ObjectIdentity('', 'sysDescr', 0).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Create an OID-value pair (called variable-binding in SNMP) varBind = rfc1902.ObjectType( rfc1902.ObjectIdentity('SNMPv2-MIB', 'sysObjectID', 0), '1.3.6.1' ).resolveWithMib(mibView) print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint()) # Create just OID varBind = rfc1902.ObjectType( rfc1902.ObjectIdentity('SNMPv2-MIB', 'sysObjectID', 0) ).resolveWithMib(mibView) print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint()) # Create var-binds from MIB notification object (without OBJECTS clause) varBinds = rfc1902.NotificationType( rfc1902.ObjectIdentity('SNMPv2-MIB', 'coldStart') ).resolveWithMib(mibView) print(['%s = %s(%s)' % (x[0].prettyPrint(), x[1].__class__.__name__, x[1].prettyPrint()) for x in varBinds]) # Create var-binds from MIB notification object (with OBJECTS clause) varBinds = rfc1902.NotificationType( rfc1902.ObjectIdentity('IF-MIB', 'linkUp'), instanceIndex=(1,), objects={('IF-MIB', 'ifOperStatus'): 'down'} ).resolveWithMib(mibView) print(varBinds.prettyPrint()) pysnmp-4.4.12/examples/smi/manager/mib-tree-inspection.py000066400000000000000000000050501354244100700233770ustar00rootroot00000000000000""" SNMP MIB browser ++++++++++++++++ This script explains how Python application (typically SNMP Manager) could load SNMP MIB modules into memory and introspect Managed Objects defined in MIB. """# from pysnmp.smi import builder, view, compiler, error # Create MIB loader/builder mibBuilder = builder.MibBuilder() # Optionally attach PySMI MIB compiler (if installed) #print('Attaching MIB compiler...'), #compiler.addMibCompiler(mibBuilder, sources=['/usr/share/snmp/mibs']) #print('done') # Optionally set an alternative path to compiled MIBs print('Setting MIB sources...') mibBuilder.addMibSources(builder.DirMibSource('/opt/pysnmp_mibs')) print(mibBuilder.getMibSources()) print('done') print('Loading MIB modules...'), mibBuilder.loadModules( 'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB', 'IP-MIB' ) print('done') print('Indexing MIB objects...'), mibView = view.MibViewController(mibBuilder) print('done') 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('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('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('MIB object value pretty print: '), mibNode, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'snmpEngineID') print(mibNode.syntax.prettyPrint()) print('MIB symbol location lookup by name: '), modName, symName, suffix = mibView.getNodeLocation(('snmpCommunityEntry',)) print(symName, modName) print('MIB node lookup by location: '), rowNode, = mibBuilder.importSymbols(modName, symName) print(rowNode) print('Conceptual table index value to oid conversion: '), oid = rowNode.getInstIdFromIndices('router') print(oid) print('Conceptual table index oid to value conversion: '), print(rowNode.getIndicesFromInstId(oid)) 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)) oid, label, suffix = mibView.getNextNodeName(oid) except error.NoSuchObjectError: break print('Modules traversal') modName = mibView.getFirstModuleName() while 1: if modName: print(modName) try: modName = mibView.getNextModuleName(modName) except error.SmiError: break pysnmp-4.4.12/examples/v1arch/000077500000000000000000000000001354244100700161325ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/000077500000000000000000000000001354244100700177555ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/agent/000077500000000000000000000000001354244100700210535ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/agent/cmdrsp/000077500000000000000000000000001354244100700223435ustar00rootroot00000000000000implementing-scalar-mib-objects-over-ipv4-and-ipv6.py000066400000000000000000000121151354244100700342400ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/agent/cmdrsp""" Implementing scalar MIB objects +++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/GETNEXT queries with the following options: * SNMPv1 or SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:161 * over IPv6/UDP, listening at [::1]:161 * serving two Managed Objects Instances (sysDescr.0 and sysUptime.0) Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 | $ snmpwalk -v2c -c public udp6:[::1] .1.3.6 The Command Receiver below uses two distinct transports for communication with Command Generators - UDP over IPv4 and UDP over IPv6. """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api import time, bisect class SysDescr(object): name = (1, 3, 6, 1, 2, 1, 1, 1, 0) 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' ) class Uptime(object): name = (1, 3, 6, 1, 2, 1, 1, 3, 0) birthday = time.time() 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 ) mibInstr = ( SysDescr(), Uptime() # sorted by object name ) mibInstrIdx = {} for mibVar in mibInstr: mibInstrIdx[mibVar.name] = mibVar def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): while wholeMsg: msgVer = api.decodeMessageVersion(wholeMsg) if msgVer in api.protoModules: pMod = api.protoModules[msgVer] else: print('Unsupported SNMP version %s' % msgVer) return reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message(), ) rspMsg = pMod.apiMessage.getResponse(reqMsg) rspPDU = pMod.apiMessage.getPDU(rspMsg) reqPDU = pMod.apiMessage.getPDU(reqMsg) varBinds = [] pendingErrors = [] errorIndex = 0 # GETNEXT PDU if reqPDU.isSameTypeWith(pMod.GetNextRequestPDU()): # Produce response var-binds for oid, val in pMod.apiPDU.getVarBinds(reqPDU): errorIndex = errorIndex + 1 # Search next OID to report nextIdx = bisect.bisect(mibInstr, oid) if nextIdx == len(mibInstr): # Out of MIB varBinds.append((oid, val)) pendingErrors.append( (pMod.apiPDU.setEndOfMibError, errorIndex) ) else: # Report value if OID is found varBinds.append( (mibInstr[nextIdx].name, mibInstr[nextIdx](msgVer)) ) elif reqPDU.isSameTypeWith(pMod.GetRequestPDU()): for oid, val in pMod.apiPDU.getVarBinds(reqPDU): if oid in mibInstrIdx: varBinds.append((oid, mibInstrIdx[oid](msgVer))) else: # No such instance varBinds.append((oid, val)) pendingErrors.append( (pMod.apiPDU.setNoSuchInstanceError, errorIndex) ) break else: # Report unsupported request type pMod.apiPDU.setErrorStatus(rspPDU, 'genErr') pMod.apiPDU.setVarBinds(rspPDU, varBinds) # Commit possible error indices to response PDU for f, i in pendingErrors: f(rspPDU, i) transportDispatcher.sendMessage( encoder.encode(rspMsg), transportDomain, transportAddress ) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openServerMode(('localhost', 161)) ) # UDP/IPv6 transportDispatcher.registerTransport( udp6.domainName, udp6.Udp6SocketTransport().openServerMode(('::1', 161)) ) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-agent') # ) transportDispatcher.jobStarted(1) try: # Dispatcher will never finish as job#1 never reaches zero transportDispatcher.runDispatcher() except: transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v1arch/asyncore/agent/ntforg/000077500000000000000000000000001354244100700223525ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/agent/ntforg/send-inform-over-ipv4-and-ipv6.py000066400000000000000000000054651354244100700304320ustar00rootroot00000000000000""" INFORM over multiple transports +++++++++++++++++++++++++++++++ The following script sends SNMP INFORM notification using the following options: * with SNMPv2c * with community name 'public' * over IPv4/UDP and IPv6/UDP * send INFORM notification * to a Manager at demo.snmplabs.com:162 and [::1]:162 * with TRAP ID 'coldStart' specified as an OID The following Net-SNMP command will produce similar SNMP notification: | $ snmpinform -v2c -c public udp:demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 | $ snmpinform -v2c -c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 """# from time import time from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.dgram import udp, udp6 from pyasn1.codec.ber import encoder, decoder from pysnmp.proto.api import v2c as pMod # Build PDU reqPDU = pMod.InformRequestPDU() pMod.apiTrapPDU.setDefaults(reqPDU) # Build message trapMsg = pMod.Message() pMod.apiMessage.setDefaults(trapMsg) pMod.apiMessage.setCommunity(trapMsg, 'public') pMod.apiMessage.setPDU(trapMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow - startedAt > 3: raise Exception("Request timed out") # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: print('INFORM message delivered, response var-binds follow') for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsynsockDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp.domainName, ('demo.snmplabs.com', 162) ) transportDispatcher.jobStarted(1) # UDP/IPv6 # transportDispatcher.registerTransport( # udp6.domainName, udp6.Udp6SocketTransport().openClientMode() # ) # transportDispatcher.sendMessage( # encoder.encode(trapMsg), udp6.domainName, ('::1', 162) # ) # transportDispatcher.jobStarted(1) # Dispatcher will finish as all scheduled messages are sent transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() pysnmp-4.4.12/examples/v1arch/asyncore/agent/ntforg/send-trap-over-ipv4-and-ipv6.py000066400000000000000000000045621354244100700301030ustar00rootroot00000000000000""" TRAP over multiple transports +++++++++++++++++++++++++++++ The following script sends two SNMP TRAP notification using the following options: * with SNMPv1 * with community name 'public' * over IPv4/UDP and IPv6/UDP * send TRAP notification * to a Manager at demo.snmplabs.com:162 and [::1] * with TRAP ID 'coldStart' specified as an OID * include managed objects information: * with default Uptime value * with default Agent Address with '127.0.0.1' * overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 The following Net-SNMP commands will produce similar SNMP notification: | $ snmptrap -v1 -c public udp:demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345 | $ snmptrap -v1 -c public udp6:[::1] 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345 """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder from pysnmp.proto import api # Protocol version to use pMod = api.protoModules[api.protoVersion1] # pMod = api.protoModules[api.protoVersion2c] # Build PDU trapPDU = pMod.TrapPDU() pMod.apiTrapPDU.setDefaults(trapPDU) # Traps have quite different semantics across proto versions if pMod == api.protoModules[api.protoVersion1]: pMod.apiTrapPDU.setEnterprise(trapPDU, (1, 3, 6, 1, 1, 2, 3, 4, 1)) pMod.apiTrapPDU.setGenericTrap(trapPDU, 'coldStart') # Build message trapMsg = pMod.Message() pMod.apiMessage.setDefaults(trapMsg) pMod.apiMessage.setCommunity(trapMsg, 'public') pMod.apiMessage.setPDU(trapMsg, trapPDU) transportDispatcher = AsyncoreDispatcher() # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp.domainName, ('demo.snmplabs.com', 162) ) # UDP/IPv6 transportDispatcher.registerTransport( udp6.domainName, udp6.Udp6SocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp6.domainName, ('::1', 162) ) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openClientMode() # ) # transportDispatcher.sendMessage( # encoder.encode(trapMsg), unix.domainName, '/tmp/snmp-manager' # ) # Dispatcher will finish as all scheduled messages are sent transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() pysnmp-4.4.12/examples/v1arch/asyncore/manager/000077500000000000000000000000001354244100700213675ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700226245ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/broadcast-agent-discovery.py000066400000000000000000000062721354244100700302500ustar00rootroot00000000000000""" Broadcast SNMP message (IPv4) +++++++++++++++++++++++++++++ Send SNMP GET request to broadcast address and wait for respons(es): * with SNMPv2c, community 'public' * over IPv4/UDP * to all Agents via broadcast address 255.255.255.255:161 * for OIDs in tuple form Here we send out a single SNMP request and wait for potentially many SNMP responses from multiple SNMP Agents listening in local broadcast domain. Since we can't predict the exact number of Agents responding, this script just waits for arbitrary time for collecting all responses. This technology is also known as SNMP-based discovery. This script performs similar to the following Net-SNMP command: | $ snmpget -v2c -c public -ObentU 255.255.255.255 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Broadcast manager settings maxWaitForResponses = 5 maxNumberResponses = 10 # Protocol version to use # pMod = api.protoModules[api.protoVersion1] pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.GetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, (('1.3.6.1.2.1.1.1.0', pMod.Null('')), ('1.3.6.1.2.1.1.3.0', pMod.Null(''))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, 'public') pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() class StopWaiting(Exception): pass def cbTimerFun(timeNow): if timeNow - startedAt > maxWaitForResponses: raise StopWaiting() # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 udpSocketTransport = udp.UdpSocketTransport().openClientMode().enableBroadcast() transportDispatcher.registerTransport(udp.domainName, udpSocketTransport) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, ('255.255.255.255', 161) ) # wait for a maximum of 10 responses or time out transportDispatcher.jobStarted(1, maxNumberResponses) # Dispatcher will finish as all jobs counter reaches zero try: transportDispatcher.runDispatcher() except StopWaiting: transportDispatcher.closeDispatcher() else: raise pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/fetch-scalar-value.py000066400000000000000000000062731354244100700266540ustar00rootroot00000000000000""" Fetch scalar MIB variables (SNMPv1) +++++++++++++++++++++++++++++++++++ Perform SNMP GET operation with the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for OIDs in tuple form This script performs similar to the following Net-SNMP command: | $ snmpget -v1 -c public -ObentU demo.snmplabs.com 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Protocol version to use pMod = api.protoModules[api.protoVersion1] # pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.GetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, (('1.3.6.1.2.1.1.1.0', pMod.Null('')), ('1.3.6.1.2.1.1.3.0', pMod.Null(''))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, 'public') pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow - startedAt > 3: raise Exception("Request timed out") # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161) ) transportDispatcher.jobStarted(1) ## UDP/IPv6 (second copy of the same PDU will be sent) # transportDispatcher.registerTransport( # udp6.domainName, udp6.Udp6SocketTransport().openClientMode() # ) # Pass message to dispatcher # transportDispatcher.sendMessage( # encoder.encode(reqMsg), udp6.domainName, ('::1', 161) # ) # transportDispatcher.jobStarted(1) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openClientMode() # ) # # Pass message to dispatcher # transportDispatcher.sendMessage( # encoder.encode(reqMsg), unix.domainName, '/tmp/snmp-agent' # ) # transportDispatcher.jobStarted(1) # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/getbulk-pull-whole-mib.py000066400000000000000000000073341354244100700274750ustar00rootroot00000000000000""" Bulk walk Agent MIB (SNMPv2c) +++++++++++++++++++++++++++++ Perform SNMP GETBULK operation with the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for OID in tuple form * with non-repeaters=0 and max-repeaters=25 This script performs similar to the following Net-SNMP command: | $ snmpbulkwalk -v2c -c public -ObentU -Cn0 -Cr25 demo.snmplabs.com 1.3.6 """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.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") # noinspection PyUnusedLocal 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): # Format var-binds table varBindTable = v2c.apiBulkPDU.getVarBindTable(reqPDU, rspPDU) # Check for SNMP errors reported errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU) if errorStatus and errorStatus != 2: errorIndex = v2c.apiBulkPDU.getErrorIndex(rspPDU) print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[int(errorIndex) - 1] or '?')) transportDispatcher.jobFinished(1) break # 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 = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161) ) transportDispatcher.jobStarted(1) # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/getnext-pull-whole-mib.py000066400000000000000000000065511354244100700275160ustar00rootroot00000000000000""" Walk Agent MIB (SNMPv1) +++++++++++++++++++++++ Perform SNMP GETNEXT operation with the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for OID in tuple form This script performs similar to the following Net-SNMP command: | $ snmpwalk -v1 -c public -ObentU demo.snmplabs.com 1.3.6 """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Protocol version to use pMod = api.protoModules[api.protoVersion1] # pMod = api.protoModules[api.protoVersion2c] # SNMP table header headVars = [pMod.ObjectIdentifier((1, 3, 6))] # Build PDU reqPDU = pMod.GetNextRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds(reqPDU, [(x, pMod.null) for x in headVars]) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, 'public') pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow - startedAt > 3: raise Exception("Request timed out") # noinspection PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU, headVars=headVars): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus and errorStatus != 2: raise Exception(errorStatus) # Format var-binds table varBindTable = pMod.apiPDU.getVarBindTable(reqPDU, rspPDU) # Report SNMP table for tableRow in varBindTable: for name, val in tableRow: print('from: %s, %s = %s' % ( transportAddress, name.prettyPrint(), val.prettyPrint() ) ) # Stop on EOM for oid, val in varBindTable[-1]: if not isinstance(val, pMod.Null): break else: transportDispatcher.jobFinished(1) # Generate request for next row pMod.apiPDU.setVarBinds( reqPDU, [(x, pMod.null) for x, y in varBindTable[-1]] ) pMod.apiPDU.setRequestID(reqPDU, pMod.getNextRequestID()) transportDispatcher.sendMessage( encoder.encode(reqMsg), transportDomain, transportAddress ) global startedAt if time() - startedAt > 3: raise Exception('Request timed out') startedAt = time() return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161) ) transportDispatcher.jobStarted(1) transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/spoof-source-address.py000066400000000000000000000075431354244100700272560ustar00rootroot00000000000000""" Spoof IPv4 source address +++++++++++++++++++++++++ Send SNMP GET request from a non-local IP address: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * from a non-local, spoofed IP 1.2.3.4 (root and Python 3.3+ required) * for OIDs in string form This script performs similar to the following Net-SNMP command: | $ snmpget -v2c -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 But unlike the above command, this script issues SNMP request from a non-default, non-local IP address. It is indeed possible to originate SNMP traffic from any valid local IP addresses. It could be a secondary IP interface, for instance. Superuser privileges are only required to send spoofed packets. Alternatively, sending from local interface could also be achieved by binding to it (via openClientMode() parameter). Agent would respond to the IP address you used as a source. So this script could only get a response if that source address is somehow routed to the host this script is running on. Otherwise it just times out. """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto import api from pyasn1.codec.ber import encoder, decoder from time import time # Send request message to this address transportAddress = udp.UdpTransportAddress(('104.236.166.95', 161)) # Send request message from this non-local (!) IP address transportAddress.setLocalAddress(('1.2.3.4', 0)) # Protocol version to use # pMod = api.protoModules[api.protoVersion1] pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.GetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, (('1.3.6.1.2.1.1.1.0', pMod.Null('')), ('1.3.6.1.2.1.1.3.0', pMod.Null(''))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, 'public') pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() class StopWaiting(Exception): pass def cbTimerFun(timeNow): if timeNow - startedAt > 3: raise StopWaiting() # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # Initialize UDP/IPv4 transport udpSocketTransport = udp.UdpSocketTransport().openClientMode() # Use sendmsg()/recvmsg() for socket communication (required for # IP source spoofing functionality) udpSocketTransport.enablePktInfo() # Enable IP source spoofing (requires root privileges) udpSocketTransport.enableTransparent() transportDispatcher.registerTransport(udp.domainName, udpSocketTransport) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, transportAddress ) # We might never receive any response as we sent request with fake source IP transportDispatcher.jobStarted(1) # Dispatcher will finish as all jobs counter reaches zero try: transportDispatcher.runDispatcher() except StopWaiting: transportDispatcher.closeDispatcher() else: raise pysnmp-4.4.12/examples/v1arch/asyncore/manager/cmdgen/v2c-set.py000066400000000000000000000053151354244100700244650ustar00rootroot00000000000000""" SET string and integer scalars (SNMPv2c) ++++++++++++++++++++++++++++++++++++++++ Perform SNMP SET operation with the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at demo.snmplabs.com:161 * for OIDs in string form and values in form of pyasn1 objects This script performs similar to the following Net-SNMP command: | $ snmpset -v2c -c public -ObentU demo.snmplabs.com 1.3.6.1.2.1.1.9.1.3.1 s 'New description' 1.3.6.1.2.1.1.9.1.4.1 t 12 """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Protocol version to use # pMod = api.protoModules[api.protoVersion1] pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.SetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, # A list of Var-Binds to SET (('1.3.6.1.2.1.1.9.1.3.1', pMod.OctetString('New system description')), ('1.3.6.1.2.1.1.9.1.4.1', pMod.TimeTicks(12))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, 'public') pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow - startedAt > 3: raise Exception("Request timed out") # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, ('demo.snmplabs.com', 161) ) transportDispatcher.jobStarted(1) # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() pysnmp-4.4.12/examples/v1arch/asyncore/manager/ntfrcv/000077500000000000000000000000001354244100700226715ustar00rootroot00000000000000pysnmp-4.4.12/examples/v1arch/asyncore/manager/ntfrcv/listen-on-ipv4-and-ipv6-interfaces.py000066400000000000000000000061451354244100700316040ustar00rootroot00000000000000""" Listen for notifications at IPv4 & IPv6 interfaces ++++++++++++++++++++++++++++++++++++++++++++++++++ Receive SNMP TRAP messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:162 * over IPv6/UDP, listening at [::1]:162 * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test | $ snmptrap -v2c -c public udp6:[::1] 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test Notification Receiver below uses two different transports for communication with Notification Originators - UDP over IPv4 and UDP over IPv6. """# from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import decoder from pysnmp.proto import api # noinspection PyUnusedLocal def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): while wholeMsg: msgVer = int(api.decodeMessageVersion(wholeMsg)) if msgVer in api.protoModules: pMod = api.protoModules[msgVer] else: print('Unsupported SNMP version %s' % msgVer) return reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message(), ) 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' % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint())) print('Agent Address: %s' % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())) print('Generic Trap: %s' % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint())) print('Specific Trap: %s' % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint())) print('Uptime: %s' % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint())) varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU) else: varBinds = pMod.apiPDU.getVarBinds(reqPDU) print('Var-binds:') for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openServerMode(('localhost', 162)) ) # UDP/IPv6 transportDispatcher.registerTransport( udp6.domainName, udp6.Udp6SocketTransport().openServerMode(('::1', 162)) ) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openServerMode('/tmp/snmp-manager') # ) transportDispatcher.jobStarted(1) try: # Dispatcher will never finish as job#1 never reaches zero transportDispatcher.runDispatcher() except: transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/000077500000000000000000000000001354244100700161345ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncio/000077500000000000000000000000001354244100700176015ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncio/agent/000077500000000000000000000000001354244100700206775ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncio/agent/cmdrsp/000077500000000000000000000000001354244100700221675ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncio/agent/cmdrsp/multiple-usm-users.py000066400000000000000000000051331354244100700263370ustar00rootroot00000000000000""" Multiple SNMP USM users +++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user: - 'usr-md5-des', auth: MD5, priv DES or - 'usr-sha-none', auth: SHA, no privacy - 'usr-sha-aes128', auth: SHA, priv AES * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 * using asyncio network transport (available since Python 3.4) Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 | $ snmpwalk -v3 -u usr-sha-none -l authNoPriv -a SHA -A authkey1 localhost .1.3.6 | $ snmpwalk -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 localhost .1.3.6 Requires Python 3.4 and later! """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncio.dgram import udp import asyncio # Get the event loop for this thread loop = asyncio.get_event_loop() # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-none, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Run asyncio main loop loop.run_forever() pysnmp-4.4.12/examples/v3arch/asyncio/manager/000077500000000000000000000000001354244100700212135ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncio/manager/ntfrcv/000077500000000000000000000000001354244100700225155ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncio/manager/ntfrcv/multiple-interfaces.py000066400000000000000000000043411354244100700270450ustar00rootroot00000000000000""" Serving multiple network interfaces +++++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:162 over IPv4/UDP, listening at 127.0.0.1:2162 * using Asyncio framework for network transport * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test | $ snmpinform -v2c -c public 127.0.0.1:2162 123 1.3.6.1.6.3.1.1.5.1 Requires Python 3.4 and later! """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncio.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv import asyncio # Get the event loop for this thread loop = asyncio.get_event_loop() # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode(('127.0.0.1', 2162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal 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())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run asyncio main loop loop.run_forever() pysnmp-4.4.12/examples/v3arch/asyncore/000077500000000000000000000000001354244100700177575ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/agent/000077500000000000000000000000001354244100700210555ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/000077500000000000000000000000001354244100700223455ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/alternative-mib-tree.py000066400000000000000000000047421354244100700267460ustar00rootroot00000000000000""" Serve non-default MIB tree ++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM username usr-md5-none * using alternative set of Managed Objects addressed by contextEngineId: 8000000001020304, contextName: my-context * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v3 -u usr-md5-none -l authNoPriv -A authkey1 -E 8000000001020304 -n my-context 127.0.0.1 .1.3.6 | $ snmpwalk -v3 -u usr-md5-none -l authNoPriv -A authkey1 -E 8000000001020304 127.0.0.1 .1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.smi import instrum, builder from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-none, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Create an SNMP context with ContextEngineId = 8000000001020304 snmpContext = context.SnmpContext( snmpEngine, contextEngineId=v2c.OctetString(hexValue='8000000001020304') ) # Create an [empty] set of Managed Objects (MibBuilder), pass it to # Management Instrumentation Controller and register at SNMP Context # under ContextName 'my-context' snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name instrum.MibInstrumController(builder.MibBuilder()) # Managed Objects ) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/custom-mib-controller.py000066400000000000000000000045741354244100700271710ustar00rootroot00000000000000""" Custom MIB Controller +++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM username usr-none-none * using alternative set of Managed Objects addressed by contextName: my-context * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 The following Net-SNMP command will send GET request to this Agent: | $ snmpget -v3 -u usr-none-none -l noAuthNoPriv -n my-context -Ir 127.0.0.1 sysDescr.0 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.smi import instrum from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-none-none, auth: NONE, priv NONE config.addV3User( snmpEngine, 'usr-none-none' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-none-none', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # Very basic Management Instrumentation Controller without # any Managed Objects attached. It supports only GET's and # always echos request var-binds in response. class EchoMibInstrumController(instrum.AbstractMibInstrumController): def readVars(self, varBinds, acInfo=(None, None)): return [(ov[0], v2c.OctetString('You queried OID %s' % ov[0])) for ov in varBinds] # Create a custom Management Instrumentation Controller and register at # SNMP Context under ContextName 'my-context' snmpContext.registerContextName( v2c.OctetString('my-context'), # Context Name EchoMibInstrumController() # Management Instrumentation ) # Register GET&SET Applications at the SNMP engine for a custom SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/custom-snmp-engine-id.py000066400000000000000000000037001354244100700270410ustar00rootroot00000000000000""" Specific SNMP Engine ID +++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with SNMP EngineID: 8000000004030201 * with USM user 'usr-md5-des', auth: MD5, priv DES * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 The following Net-SNMP command will walk this Agent: | $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -e 8000000004030201 localhost .1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto import rfc1902 # Create SNMP engine snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue='8000000004030201')) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/detailed-vacm-configuration.py000066400000000000000000000067651354244100700303010ustar00rootroot00000000000000""" Detailed VACM configuration +++++++++++++++++++++++++++ Serves MIB subtrees under different conditions: * Respond to SNMPv2c commands * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:161 * Serve MIB under non-default contextName `abcd` * Allow access to `SNMPv2-MIB::system` subtree * Although deny access to `SNMPv2-MIB::sysUpTime` by a bit mask * Use partial context name matching (`a`) This example demonstrates detailed VACM configuration performed via low-level VACM calls: `addContext`, `addVacmGroup`, `addVacmAccess` and `addVacmView`. Each function populates one of the tables defined in `SNMP-VIEW-BASED-ACM-MIB` and used strictly as described in the above mentioned MIB. The following Net-SNMP's commands will GET a value at this Agent: | $ snmpget -v2c -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0 However this command will fail: | $ snmpget -v2c -c public 127.0.0.1 SNMPv2-MIB::sysUpTime.0 This command will not reveal `SNMPv2-MIB::sysUpTime.0` among other objects: | $ snmpwalk -v2c -c public 127.0.0.1 SNMPv2-MIB::system """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # Register default MIB instrumentation controller with a new SNMP context contextName = 'abcd' snmpContext = context.SnmpContext(snmpEngine) snmpContext.registerContextName( contextName, snmpEngine.msgAndPduDsp.mibInstrumController) # Add new SNMP community name, map it to a new security name and # SNMP context securityName = 'my-area' communityName = 'public' config.addV1System( snmpEngine, securityName, communityName, contextEngineId=snmpContext.contextEngineId, contextName=contextName) # VACM configuration settings securityModel = 2 # SNMPv2c securityLevel = 1 # noAuthNoPriv vacmGroup = 'my-group' readViewName = 'my-read-view' # We will match by context name prefix contextPrefix = contextName[:1] # Populate SNMP-VIEW-BASED-ACM-MIB::vacmContextTable config.addContext(snmpEngine, contextName) # Populate SNMP-VIEW-BASED-ACM-MIB::vacmSecurityToGroupTable config.addVacmGroup( snmpEngine, vacmGroup, securityModel, securityName) # Populate SNMP-VIEW-BASED-ACM-MIB::vacmAccessTable config.addVacmAccess( snmpEngine, vacmGroup, contextPrefix, securityModel, securityLevel, 'prefix', readViewName, '', '') # Populate SNMP-VIEW-BASED-ACM-MIB::vacmViewTreeFamilyTable # Allow the whole system subtree config.addVacmView( snmpEngine, readViewName, 'included', '1.3.6.1.2.1.1.1', '1.1.1.1.1.1.1.0') # ...but exclude one sub-branch (just one scalar OID) config.addVacmView( snmpEngine, readViewName, 'excluded', '1.3.6.1.2.1.1.3', '1.1.1.1.1.1.1.1') # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except Exception: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/implementing-scalar-mib-objects.py000066400000000000000000000046431354244100700310550ustar00rootroot00000000000000""" Implementing scalar MIB objects +++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv2c * with SNMP community "public" * serving custom Managed Object Instance defined within this script * allow read access only to the subtree where the custom MIB object resides * over IPv4/UDP, listening at 127.0.0.1:161 The following Net-SNMP commands will walk this Agent: | $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 """# import sys from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 5)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- create custom Managed Object Instance --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() MibScalar, MibScalarInstance = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalar', 'MibScalarInstance' ) class MyStaticMibScalarInstance(MibScalarInstance): # noinspection PyUnusedLocal,PyUnusedLocal def getValue(self, name, idx): return self.getSyntax().clone( 'Python %s running on a %s platform' % (sys.version, sys.platform) ) mibBuilder.exportSymbols( '__MY_MIB', MibScalar((1, 3, 6, 5, 1), v2c.OctetString()), MyStaticMibScalarInstance((1, 3, 6, 5, 1), (0,), v2c.OctetString()) ) # --- end of Managed Object Instance initialization ---- # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/implementing-snmp-table.py000066400000000000000000000102171354244100700274500ustar00rootroot00000000000000""" Implementing conceptual table +++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv2c * with SNMP community "public" * define a simple SNMP Table within a newly created EXAMPLE-MIB * pre-populate SNMP Table with a single row of values * allow read access only to the subtree where example SNMP Table resides * over IPv4/UDP, listening at 127.0.0.1:161 The following Net-SNMP commands will populate and walk a table: | $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.2.97.98.99 s "my value" | $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 4 | $ snmpwalk -v2c -c public 127.0.0.1 1.3.6 ...while the following command will destroy the same row | $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 6 | $ snmpwalk -v2c -c public 127.0.0.1 1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 6), (1, 3, 6, 6)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- define custom SNMP Table within a newly defined EXAMPLE-MIB --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalarInstance' ) RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus') mibBuilder.exportSymbols( '__EXAMPLE-MIB', # table object exampleTable=MibTable((1, 3, 6, 6, 1)).setMaxAccess('readcreate'), # table row object, also carries references to table indices exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5)).setMaxAccess('readcreate').setIndexNames((0, '__EXAMPLE-MIB', 'exampleTableColumn1')), # table column: string index exampleTableColumn1=MibTableColumn((1, 3, 6, 6, 1, 5, 1), v2c.OctetString()).setMaxAccess('readcreate'), # table column: string value exampleTableColumn2=MibTableColumn((1, 3, 6, 6, 1, 5, 2), v2c.OctetString()).setMaxAccess('readcreate'), # table column: integer value with default exampleTableColumn3=MibTableColumn((1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123)).setMaxAccess('readcreate'), # table column: row status exampleTableStatus=MibTableColumn((1, 3, 6, 6, 1, 5, 4), RowStatus('notExists')).setMaxAccess('readcreate') ) # --- end of custom SNMP table definition, empty table now exists --- # --- populate custom SNMP table with one row --- (exampleTableEntry, exampleTableColumn2, exampleTableColumn3, exampleTableStatus) = mibBuilder.importSymbols( '__EXAMPLE-MIB', 'exampleTableEntry', 'exampleTableColumn2', 'exampleTableColumn3', 'exampleTableStatus' ) rowInstanceId = exampleTableEntry.getInstIdFromIndices('example record one') mibInstrumentation = snmpContext.getMibInstrum() mibInstrumentation.writeVars( ((exampleTableColumn2.name + rowInstanceId, 'my string value'), (exampleTableColumn3.name + rowInstanceId, 123456), (exampleTableStatus.name + rowInstanceId, 'createAndGo')) ) # --- end of SNMP table population --- # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/listen-on-ipv4-and-ipv6-interfaces.py000066400000000000000000000040331354244100700312520ustar00rootroot00000000000000""" Serve multiple network transports +++++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv2c * with SNMP community "public" * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 and over IPv6/UDP, listening at [::1]:161 Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 | $ snmpwalk -v2c -c public udp6:[::1] .1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp, udp6 # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 at 127.0.0.1:161 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # UDP over IPv6 at [::1]:161 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/listen-on-multiple-interfaces.py000066400000000000000000000040421354244100700306010ustar00rootroot00000000000000""" Listen on multiple network interfaces +++++++++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv2c * with SNMP community "public" * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 and 127.0.0.2:161 interfaces Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 | $ snmpwalk -v2c -c public 127.0.0.2 .1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 at 127.0.0.1:161 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # UDP over IPv4 at 127.0.0.2:161 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode(('127.0.0.2', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/listening-on-virtual-network-interface.py000066400000000000000000000061321354244100700324400ustar00rootroot00000000000000""" Running at secondary network interface ++++++++++++++++++++++++++++++++++++++ Listen on all local IPv4 interfaces respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user 'usr-md5-des', auth: MD5, priv DES * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 0.0.0.0:161 * preserve local IP address when responding (Python 3.3+ required) The following Net-SNMP command will walk this Agent: | $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 In the situation when UDP responder receives a datagram targeted to a secondary (AKA virtial) IP interface or a non-local IP interface (e.g. routed through policy routing or iptables TPROXY facility), OS stack will by default put primary local IP interface address into the IP source field of the response IP packet. Such datagram may not reach the sender as either the sender itself or a stateful firewall somewhere in between would not be able to match response to original request. The following script solves this problem by preserving original request destination IP address and put it back into response IP packet's source address field. To respond from a non-local (e.g. spoofed) IP address, uncomment the .enableTransparent() method call and run this script as root. """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # Initialize asyncore-based UDP/IPv4 transport udpSocketTransport = udp.UdpSocketTransport().openServerMode(('0.0.0.0', 161)) # Use sendmsg()/recvmsg() for socket communication (used for preserving # original destination IP address when responding) udpSocketTransport.enablePktInfo() # Enable IP source spoofing (requires root privileges) # udpSocketTransport.enableTransparent() # Register this transport at SNMP Engine config.addTransport( snmpEngine, udp.domainName, udpSocketTransport ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.observer.unregisterObserver() snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-communities.py000066400000000000000000000042041354244100700300570ustar00rootroot00000000000000""" Multiple SNMP communities +++++++++++++++++++++++++ Respond to SNMP GET/SET/GETNEXT queries with the following options: * SNMPv1 * with SNMP community "public" (read access) or "private" (write access) * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 Allow read/write access to all objects in the same MIB subtree. The following Net-SNMP's commands will GET/SET a value at this Agent: | $ snmpget -v1 -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0 | $ snmpset -v1 -c private 127.0.0.1 SNMPv2-MIB::sysLocation.0 s "far away" """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv1 setup # SecurityName <-> CommunityName mapping. # Here we configure two distinct CommunityName's to control read and write # operations. config.addV1System(snmpEngine, 'my-read-area', 'public') config.addV1System(snmpEngine, 'my-write-area', 'private') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 1, 'my-read-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 1, 'my-write-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/multiple-snmp-engines.py000066400000000000000000000064021354244100700271550ustar00rootroot00000000000000""" Multiple SNMP Engines +++++++++++++++++++++ Run multiple SNMP Engines each with a complete Command Responder. Bind each SNMP Engine to a dedicated network transport endpoint: * IPv4/UDP, listening at 127.0.0.1:161 * IPv4/UDP, listening at 127.0.0.2:161 Each Command Responder will respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user 'usr-md5-des', auth: MD5, priv DES * allow read access to SNMPv2-MIB objects (1.3.6) * allow write access to SNMPv2-MIB objects (1.3.6.1.2.1) The following Net-SNMP commands will walk the first and the second Agent respectively: | $ snmpwalk -Ob -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 127.0.0.1 usmUserEntry | $ snmpwalk -Ob -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 127.0.0.2 usmUserEntry Notice differently configured snmpEngineId's in usmUserEntry columns. """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.proto import rfc1902 from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp # Configuration parameters for each of SNMP Engines snmpEngineInfo = ( ('0102030405060708', udp.domainName + (0,), ('127.0.0.1', 161)), ('0807060504030201', udp.domainName + (1,), ('127.0.0.2', 161)) ) # Instantiate the single transport dispatcher object transportDispatcher = AsyncoreDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain transportDispatcher.registerRoutingCbFun(lambda td, t, d: td) # Instantiate and configure SNMP Engines for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo: # Create SNMP engine with specific engineID snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue=snmpEngineId)) # Register SNMP Engine object with transport dispatcher. Request incoming # data from specific transport endpoint to be funneled to this SNMP Engine. snmpEngine.registerTransportDispatcher(transportDispatcher, transportDomain) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: transportDispatcher.runDispatcher() except: transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/multiple-usm-users.py000066400000000000000000000052001354244100700265100ustar00rootroot00000000000000""" Multiple SNMP USM users +++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user 'usr-md5-des', auth: MD5, priv DES or with USM user 'usr-sha-none', auth: SHA, no privacy with USM user 'usr-sha-aes128', auth: SHA, priv AES * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 | $ snmpwalk -v3 -u usr-sha-none -l authNoPriv -a SHA -A authkey1 localhost .1.3.6 | $ snmpwalk -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 localhost .1.3.6 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 1161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-none, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/cmdrsp/observe-request-processing.py000066400000000000000000000062451354244100700302330ustar00rootroot00000000000000""" Observe SNMP engine operations ++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user 'usr-md5-des', auth: MD5, priv DES or * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 * registers its own execution observer to snmpEngine The following Net-SNMP command will walk this Agent: | $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 This script will report some details on request processing as seen by rfc3412.receiveMessage() and rfc3412.returnResponsePdu() abstract interfaces. """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Execution point observer setup # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at code point's local scope # noinspection PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): print('Execution point: %s' % execpoint) print('* transportDomain: %s' % '.'.join([str(x) for x in variables['transportDomain']])) print('* transportAddress: %s (local %s)' % ('@'.join([str(x) for x in variables['transportAddress']]), '@'.join([str(x) for x in variables['transportAddress'].getLocalAddress()]))) print('* securityModel: %s' % variables['securityModel']) print('* securityName: %s' % variables['securityName']) print('* securityLevel: %s' % variables['securityLevel']) print('* contextEngineId: %s' % variables['contextEngineId'].prettyPrint()) print('* contextName: %s' % variables['contextName'].prettyPrint()) print('* PDU: %s' % variables['pdu'].prettyPrint()) snmpEngine.observer.registerObserver( requestObserver, 'rfc3412.receiveMessage:request', 'rfc3412.returnResponsePdu' ) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.observer.unregisterObserver() snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/000077500000000000000000000000001354244100700223545ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/multiple-different-notifications-at-once.py000066400000000000000000000074201354244100700327230ustar00rootroot00000000000000""" Notification over multiple SNMP versions ++++++++++++++++++++++++++++++++++++++++ Send SNMP INFORM notifications to multiple Managers using different security settings: * SNMPv2c * with community name 'public' * AND * SNMPv3 * with user 'usr-md5-none', auth: MD5, priv NONE * over IPv4/UDP * send INFORM notification * to multiple Managers at 104.236.166.95:162, 104.236.166.95:162 * with TRAP ID 'coldStart' specified as an OID * include managed objects information: 1.3.6.1.2.1.1.1.0 = 'Example Notificator' Functionally similar to: | $ snmpinform -v3 -l authPriv -u usr-md5-none -A authkey1 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' | $ snmpinform -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SNMPv2c: # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds-1', 'my-area', 'noAuthNoPriv', 1) # SNMPv3: config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds-2', 'usr-md5-none', 'authNoPriv') # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) # First target config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('104.236.166.95', 162), 'my-creds-1', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('104.236.166.95', 162), 'my-creds-2', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2&3), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print('Notification %s, status - %s' % (sendRequestHandle, errorIndication and errorIndication or 'delivered')) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')) ], cbFun ) print('Notifications %s are scheduled to be sent' % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/send-custom-pdu.py000066400000000000000000000047761354244100700257730ustar00rootroot00000000000000""" Send crafted TRAP PDU +++++++++++++++++++++ Initialize TRAP PDU and pass it over to unified SNMPv3 message processing framework for further treatment. * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * initialize TRAP PDU with the following var-binds: 1.3.6.1.2.1.1.3.0 = 123 1.3.6.1.6.3.1.1.4.1.0 = 1.3.6.1.6.3.1.1.5.1 Functionally similar to: | $ snmptrap -v2c -c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Create named target config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds' ) # *** SNMP engine configuration is complete by this line *** # Create SNMP v2c TRAP PDU with defaults trapPDU = v2c.TrapPDU() v2c.apiTrapPDU.setDefaults(trapPDU) # Set custom var-binds to TRAP PDU v2c.apiTrapPDU.setVarBinds( trapPDU, [ # sysUpTime (v2c.ObjectIdentifier('1.3.6.1.2.1.1.3.0'), v2c.TimeTicks(123)), # snmpTrapPDU ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))) ] ) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher ntfOrg.sendPdu( snmpEngine, # Notification targets 'my-nms', # target address None, '', # contextEngineId, contextName trapPDU, cbFun ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/send-inform-to-multiple-managers.py000066400000000000000000000067341354244100700312250ustar00rootroot00000000000000""" Notification to multiple addresses ++++++++++++++++++++++++++++++++++ Send SNMP TRAP notifications to multiple Managers using different security settings: * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * to multiple Managers at 104.236.166.95:162, 104.236.166.95:162 * with TRAP ID 'coldStart' specified as an OID * include managed objects information: 1.3.6.1.2.1.1.1.0 = 'Example Notificator' 1.3.6.1.2.1.1.5.0 = 'Notificator Example' Functionally similar to: | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) # First target config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Third target config.addTargetAddr( snmpEngine, 'my-nms-3', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example')) ] ) print('Notifications are scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/send-notification-over-ipv4-and-ipv6.py000066400000000000000000000064411354244100700316230ustar00rootroot00000000000000""" Notification over multiple network protocols ++++++++++++++++++++++++++++++++++++++++++++ Send SNMP INFORM notifications to multiple Managers over different network protocols: * SNMPv2c * with community name 'public' * over IPv4/UDP and UDP/IPv6 * send TRAP notification * to two Managers through different network transports * with TRAP ID 'coldStart' specified as an OID * include managed objects information: 1.3.6.1.2.1.1.1.0 = 'Example Notificator' 1.3.6.1.2.1.1.5.0 = 'Notificator Example' Functionally similar to: | $ snmptrap -v2c -c public udp:104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' | $ snmptrap -v2c -c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoints and bind it with security settings yielding # a target name: # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # UDP/IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms-2', udp6.domainName, ('::1', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example')) ] ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/send-packet-from-specific-address.py000066400000000000000000000051151354244100700312750ustar00rootroot00000000000000""" Send packet from specific network interface/port ++++++++++++++++++++++++++++++++++++++++++++++++ Send SNMP notification using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * to a Manager at 104.236.166.95 UDP port 162 * from local address 0.0.0.0, UDP port 61024 * send TRAP notification * with TRAP ID 'coldStart' specified as an OID Functionally similar to: | $ snmptrap -v1 -c public 104.236.166.95 1.3.6.1.6.3.1.1.5.1 0.0.0.0 1 0 0 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv1 -> 0) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # Setup transport endpoint and bind it with security settings yielding # a target name. Pay attention to the openClientMode() parameter -- it's # used to originate packets from particular local IP:port config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode(iface=('0.0.0.0', 61024)) ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (1), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))) ] ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and stop snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/send-trap-to-multiple-managers.py000066400000000000000000000066601354244100700306770ustar00rootroot00000000000000""" Notification to multiple SNMP managers ++++++++++++++++++++++++++++++++++++++ Send SNMP TRAP notifications to multiple Managers using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * to multiple Managers at 104.236.166.95:162, 104.236.166.95:162 * with TRAP ID 'coldStart' specified as an OID * include managed objects information: 1.3.6.1.2.1.1.1.0 = 'Example Notificator' 1.3.6.1.2.1.1.5.0 = 'Notificator Example' Functionally similar to: | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example notification' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) # First target config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Third target config.addTargetAddr( snmpEngine, 'my-nms-3', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM) # to what targets (chosen by tag) and with what credentials. config.addNotificationTarget( snmpEngine, 'my-notification', 'my-creds', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example')) ] ) print('Notifications are scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/usm-md5-none.py000066400000000000000000000056111354244100700251550ustar00rootroot00000000000000""" SNMPv3 INFORM, auth: MD5, privacy: none +++++++++++++++++++++++++++++++++++++++ Send SNMP INFORM notification using the following options: * SNMPv3 * with user 'usr-md5-none', auth: MD5, priv NONE * over IPv4/UDP * to a Manager at demo.snmplabs.com:162 * send INFORM notification * with TRAP ID 'warmStart' specified as an OID * include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' Functionally similar to: | $ snmpinform -v3 -l authNoPriv -u usr-md5-none -A authkey1 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = 'system name' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Add USM user config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 3, 'usr-md5-none', 'authNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds: SNMPv2-MIB::coldStart, ... [((1, 3, 6, 1, 6, 3, 1, 1, 5, 1), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('system name'))], cbFun ) print('Notification %s scheduled to be sent' % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/v1-trap.py000066400000000000000000000063741354244100700242320ustar00rootroot00000000000000""" SNMPv1 TRAP +++++++++++ Send SNMP notification using the following options: * SNMPv1 * with community name 'public' * over IPv4/UDP * to a Manager at 104.236.166.95:162 * send TRAP notification * with TRAP ID 'coldStart' specified as an OID * include managed objects information: * overriding Uptime value with 12345 * overriding Agent Address with '104.236.166.95' * overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 * include managed object information '1.3.6.1.2.1.1.1.0' = 'my system' Functionally similar to: | $ snmptrap -v1 -c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 104.236.166.95 6 432 12345 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv1 -> 0) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (1), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # Uptime value with 12345 (v2c.ObjectIdentifier('1.3.6.1.2.1.1.3.0'), v2c.TimeTicks(12345)), # trap OID: Generic Trap #6 (enterpriseSpecific) # and Specific Trap 432 (v2c.ObjectIdentifier('1.3.6.1.6.3.1.1.5.1'), v2c.ObjectIdentifier('1.3.6.1.4.1.20408.4.1.1.2.0.432')), # Agent Address with '127.0.0.1' (v2c.ObjectIdentifier('1.3.6.1.6.3.18.1.3.0'), v2c.IpAddress('127.0.0.1')), # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 (v2c.ObjectIdentifier('1.3.6.1.6.3.1.1.4.3.0'), v2c.ObjectIdentifier('1.3.6.1.4.1.20408.4.1.1.2')), # managed object '1.3.6.1.2.1.1.1.0' = 'my system' (v2c.ObjectIdentifier('1.3.6.1.2.1.1.1.0'), v2c.OctetString('my system')) ] ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and stop snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/v2c-inform.py000066400000000000000000000063101354244100700247100ustar00rootroot00000000000000""" INFORM notification +++++++++++++++++++ Send SNMP INFORM notification using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send INFORM notification * to a Manager at 104.236.166.95:162 * with TRAP ID 'coldStart' specified as an OID * include managed objects information: 1.3.6.1.2.1.1.1.0 = 'Example Notificator' 1.3.6.1.2.1.1.5.0 = 'Notificator Example' Functionally similar to: | $ snmpinform -v2c -c public 104.236.166.95 12345 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s 'Example Notificator' 1.3.6.1.2.1.1.5.0 s 'Notificator Example' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping (+ transport binding) config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'inform' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example')) ], cbFun ) print('Notification %s scheduled to be sent' % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/v2c-trap-with-notification-objects.py000066400000000000000000000064501354244100700314550ustar00rootroot00000000000000""" Sending notification with OBJECT's ++++++++++++++++++++++++++++++++++ Send SNMP TRAP notification using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * to a Manager at 104.236.166.95:162 * with TRAP ID IF-MIB::ifLink as MIB symbol The IF-MIB::ifLink NOTIFICATION-TYPE implies including four other var-binds into the notification message describing the incident occurred. These var-binds are: IF-MIB::ifIndex."x" IF-MIB::ifAdminStatus."x" IF-MIB::ifOperStatus."x" IF-MIB::ifDescr."x" Where "x" is MIB table index (instance index). Functionally similar to: | $ snmptrap -v2c -c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.3 IF-MIB::ifIndex."1" IF-MIB::ifAdminStatus."1" IF-MIB::ifOperStatus."1" IF-MIB::ifDescr."1" """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.smi import rfc1902, view # # Here we fill in some values for Managed Objects Instances (invoked # later while building TRAP message) by NOTIFICATION-TYPE macro evaluation. # In real Agent app, these values should already be initialized during # Agent runtime. # instanceIndex = (1,) objects = { ('IF-MIB', 'ifIndex'): instanceIndex[0], ('IF-MIB', 'ifAdminStatus'): 'up', ('IF-MIB', 'ifOperStatus'): 'down', ('IF-MIB', 'ifDescr'): 'eth0' } # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # MIB view controller is used for MIB lookup purposes mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoints and bind it with security settings yielding # a target name: # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, 'my-notification', # notification targets None, '', # contextEngineId, contextName rfc1902.NotificationType( rfc1902.ObjectIdentity('IF-MIB', 'linkUp'), instanceIndex=instanceIndex, objects=objects ).resolveWithMib(mibViewController) ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/v2c-trap.py000066400000000000000000000061311354244100700243650ustar00rootroot00000000000000""" SNMPv2c TRAP ++++++++++++ Send SNMP TRAP notification using the following options: * SNMPv2c * with community name 'public' * over IPv4/UDP * send TRAP notification * to a Manager at 104.236.166.95:162 * with TRAP ID 'coldStart' specified as an OID * include managed objects information: 1.3.6.1.2.1.1.1.0 = 'Example Notificator' 1.3.6.1.2.1.1.5.0 = 'Notificator Example' Functionally similar to: | $ snmptrap -v2c -c public 104.236.166.95 12345 1.3.6.1.4.1.20408.4.1.1.2 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public', transportTag='all-my-managers') # Specify security settings per SecurityName (SNMPv2c -> 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, # Notification targets 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString('Example Notificator')), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example')) ], cbFun ) print('Notification %s is scheduled to be sent' % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/agent/ntforg/v3-trap.py000066400000000000000000000055471354244100700242350ustar00rootroot00000000000000""" SNMPv3 TRAP, auth: MD5, privacy: DES ++++++++++++++++++++++++++++++++++++ Send SNMP TRAP notification using the following options: * SNMPv3 * with user 'usr-md5-des', auth: MD5, priv DES * over IPv4/UDP * send TRAP notification * to a Manager at 104.236.166.95:162 * with TRAP ID 'warmStart' specified as an OID * include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' Functionally similar to: | $ snmptrap -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -e 8000000001020304 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s "my system" """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance with specific (and locally unique) # SnmpEngineId -- it must also be known to the receiving party # and configured at its VACM users table. snmpEngine = engine.SnmpEngine( snmpEngineID=v2c.OctetString(hexValue='8000000001020304') ) # Add USM user config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv') # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('104.236.166.95', 162), 'my-creds', tagList='all-my-managers' ) # Specify what kind of notification should be sent (TRAP or INFORM), # to what targets (chosen by tag) and what filter should apply to # the set of targets (selected by tag) config.addNotificationTarget( snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap' ) # Allow NOTIFY access to Agent's MIB by this SNMP model (3), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets 'my-notification', # notification targets None, '', # contextEngineId, contextName # var-binds [ # SNMPv2-SMI::snmpTrapOID.0 = SNMPv2-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString('Notificator Example')) ] ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/000077500000000000000000000000001354244100700213715ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/000077500000000000000000000000001354244100700226265ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/custom-contextengineid-and-contextname.py000066400000000000000000000046701354244100700327710ustar00rootroot00000000000000""" Custom ContextEngineId and ContextName ++++++++++++++++++++++++++++++++++++++ Send a SNMP GET request with the following options: * with SNMPv3 with user 'usr-md5-none', SHA auth and no privacy protocols * for MIB instance identified by * contextEngineId: 0x80004fb805636c6f75644dab22cc, * contextName: da761cfc8c94d3aceef4f60f049105ba * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form This script performs similar to the following Net-SNMP command: | $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 -E 80004fb805636c6f75644dab22cc -n da761cfc8c94d3aceef4f60f049105ba -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-md5-none, auth: MD5, priv: NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message, pass custom ContextEngineId & ContextName cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', # contextEngineId rfc1902.OctetString(hexValue='80004fb805636c6f75644dab22cc'), # contextName rfc1902.OctetString('da761cfc8c94d3aceef4f60f049105ba'), [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/custom-timeout-and-retries.py000066400000000000000000000041001354244100700304040ustar00rootroot00000000000000""" SNMPv2c, custom timeout +++++++++++++++++++++++ Send a SNMP GET request: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * wait 3 seconds for response, retry 5 times (plus one initial attempt) * for an OID in tuple form This script performs similar to the following Net-SNMP command: | $ snmpget -v2c -c public -ObentU -r 5 -t 1 104.236.166.95 1.3.6.1.2.1.1.1.0 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv2c setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds', timeout=300, # in 1/100 sec retryCount=5 ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/fetch-variables-over-ipv6.py000066400000000000000000000043361354244100700301000ustar00rootroot00000000000000""" Walk Agent over IPv6 ++++++++++++++++++++ Send a series of SNMP GETNEXT requests with the following options: * with SNMPv3 with user 'usr-md5-none', MD5 auth and no privacy protocols * over IPv6/UDP * to an Agent at [::1]:161 * for two OIDs in tuple form * stop on end-of-mib condition for both OIDs This script performs similar to the following Net-SNMP command: | $ snmpwalk -v3 -l authNoPriv -u usr-md5-none -A authkey1 -ObentU udp6:[::1]:161 1.3.6.1.2.1.1 1.3.6.1.4.1.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp6 from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-md5-des, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp6.domainName, ('::1', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return True # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/getbulk-fetch-scalar-and-table-variables.py000066400000000000000000000047361354244100700327740ustar00rootroot00000000000000""" Fetch scalar and table variables ++++++++++++++++++++++++++++++++ Send a series of SNMP GETBULK requests with the following options: * with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * with values non-repeaters = 1, max-repetitions = 25 * for two OIDs in tuple form (first OID is non-repeating) * stop on end-of-mib condition for both OIDs This script performs similar to the following Net-SNMP command: | $ snmpbulkwalk -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -C n1 -C r25 -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdgen from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequesthandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # stop on error if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return True # signal dispatcher to continue walking # Prepare initial request to be sent cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName 0, 25, # non-repeaters, max-repetitions (((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)), cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/getbulk-multiple-oids-to-eom.py000066400000000000000000000044371354244100700306300ustar00rootroot00000000000000""" Bulk walk MIB +++++++++++++ Send a series of SNMP GETBULK requests * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * with values non-repeaters = 0, max-repetitions = 25 * for two OIDs in tuple form * stop on end-of-mib condition for both OIDs This script performs similar to the following Net-SNMP command: | $ snmpbulkwalk -v2c -c public -C n0 -C r25 -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 """# from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdgen from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv2c setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequesthandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # stop on error if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return True # signal dispatcher to continue walking # Prepare initial request to be sent cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName 0, 25, # non-repeaters, max-repetitions [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-and-resolve-with-mib.py000066400000000000000000000060301354244100700333750ustar00rootroot00000000000000""" Walk Agent and resolve variables at MIB +++++++++++++++++++++++++++++++++++++++ Send a series of SNMP GETNEXT requests with the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for two OIDs in tuple form * stop on end-of-mib condition for both OIDs This script performs similar to the following Net-SNMP command: | $ snmpwalk -v1 -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.smi import compiler, view, rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Attach MIB compiler to SNMP Engine (MIB Builder) # This call will fail if PySMI is not present on the system compiler.addMibCompiler(snmpEngine.getMibBuilder()) # ... alternatively, this call will not complain on missing PySMI # compiler.addMibCompiler(snmpEngine.getMibBuilder(), ifAvailable=True) # Used for MIB objects resolution mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) # # # SNMPv1/2c setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here if errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for varBind in varBindRow: print(rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]), varBind[1]).resolveWithMib(mibViewController).prettyPrint()) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [rfc1902.ObjectType(rfc1902.ObjectIdentity('iso.org.dod')).resolveWithMib(mibViewController), rfc1902.ObjectType(rfc1902.ObjectIdentity('IF-MIB', 'ifMIB')).resolveWithMib(mibViewController)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/getnext-multiple-oids-to-eom.py000066400000000000000000000045301354244100700306430ustar00rootroot00000000000000""" Fetch two subtrees in parallel ++++++++++++++++++++++++++++++ Send a series of SNMP GETNEXT requests with the following options: * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for two OIDs in tuple form * stop on end-of-mib condition for both OIDs This script performs similar to the following Net-SNMP command: | $ snmpwalk -v1 -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1/2c setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here if errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/observe-request-processing.py000066400000000000000000000066361354244100700305200ustar00rootroot00000000000000""" Report SNMP engine processing details +++++++++++++++++++++++++++++++++++++ Send SNMP GET request with the following options: * with SNMPv3 with user 'usr-sha-aes', SHA auth and AES128 privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form * also registers its own execution observer to snmpEngine While execution, this script will report some details on request processing as seen by rfc3412.sendPdu() and rfc3412.receiveMessage() abstract interfaces. This script performs similar to the following Net-SNMP command: | $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Execution point observer setup # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at code point's local scope # noinspection PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): print('Execution point: %s' % execpoint) print('* transportDomain: %s' % '.'.join([str(x) for x in variables['transportDomain']])) print('* transportAddress: %s' % '@'.join([str(x) for x in variables['transportAddress']])) print('* securityModel: %s' % variables['securityModel']) print('* securityName: %s' % variables['securityName']) print('* securityLevel: %s' % variables['securityLevel']) print('* contextEngineId: %s' % (variables['contextEngineId'] and variables['contextEngineId'].prettyPrint() or '',)) print('* contextName: %s' % variables['contextName'].prettyPrint()) print('* PDU: %s' % variables['pdu'].prettyPrint()) snmpEngine.observer.registerObserver( requestObserver, 'rfc3412.sendPdu', 'rfc3412.receiveMessage:response' ) # # SNMPv3/USM setup # # user: usr-sha-aes, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() snmpEngine.observer.unregisterObserver() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/pull-subtree.py000066400000000000000000000045431354244100700256310ustar00rootroot00000000000000""" Pull MIB subtree ++++++++++++++++ Send a series of SNMP GETNEXT requests * with SNMPv3 with user 'usr-none-none', no auth and no privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in string form * stop whenever received OID goes out of initial prefix (it may be a table) This script performs similar to the following Net-SNMP command: | $ snmpwalk -v3 -l noAuthNoPriv -u usr-none-none -ObentU 104.236.166.95:161 1.3.6.1.2.1.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Initial OID prefix initialOID = rfc1902.ObjectName('1.3.6.1.2.1.1') # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-none-none, auth: none, priv: none config.addV3User( snmpEngine, 'usr-none-none', ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-none-none', 'noAuthNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: if initialOID.isPrefixOf(oid): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) else: return False # signal dispatcher to stop return True # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [(initialOID, None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/send-packets-from-specific-interface.py000066400000000000000000000045371354244100700322540ustar00rootroot00000000000000""" Send packets from specific local interface ++++++++++++++++++++++++++++++++++++++++++ Send a series of SNMP GETNEXT requests with the following options: * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * sending packets from primary local interface 0.0.0.0, local port 61024 * for two OIDs in tuple form * stop on end-of-mib condition for both OIDs This script performs similar to the following Net-SNMP command: | $ snmpwalk -v2c -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1/2c setup (if you use SNMPv1 or v2c) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode(('0.0.0.0', 61024)) ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1][0] or '?')) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 2, 1, 11), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/set-multiple-scalar-values.py000066400000000000000000000045201354244100700303650ustar00rootroot00000000000000""" SET string and integer scalars ++++++++++++++++++++++++++++++ Send SNMP SET request with the following options: * with SNMPv1 with community name 'private' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for OIDs in tuple form and an integer and string-typed values This script performs similar to the following Net-SNMP command: | $ snmpset -v1 -c private -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.3.1 s 'my value' 1.3.6.1.2.1.1.9.1.4.1 t 123 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'private') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here elif errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString('my value')), ((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/spoof-source-address.py000066400000000000000000000057611354244100700272600ustar00rootroot00000000000000""" Spoof source address ++++++++++++++++++++ Send a SNMP GET request * with SNMPv2c, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * from a non-local, spoofed IP 1.2.3.4 (root and Python 3.3+ required) * for an OID in tuple form This script performs similar to the following Net-SNMP command: | $ snmpget -v2c -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0 But unlike the above command, this script issues SNMP request from a non-default, non-local IP address. It is indeed possible to originate SNMP traffic from any valid local IP addresses. It could be a secondary IP interface, for instance. Superuser privileges are only required to send spoofed packets. Alternatively, sending from local interface could also be achieved by binding to it (via openClientMode() parameter). """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # Initialize asyncore-based UDP/IPv4 transport udpSocketTransport = udp.UdpSocketTransport().openClientMode() # Use sendmsg()/recvmsg() for socket communication (required for # IP source spoofing functionality) udpSocketTransport.enablePktInfo() # Enable IP source spoofing (requires root privileges) udpSocketTransport.enableTransparent() # Register this transport at SNMP Engine config.addTransport( snmpEngine, udp.domainName, udpSocketTransport ) # Configure destination IPv4 address as well as source IPv4 address config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds', sourceAddress=('1.2.3.4', 0) ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here elif errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/usm-sha-aes128.py000066400000000000000000000042211354244100700255550ustar00rootroot00000000000000""" SNMPv3, auth: SHA, privacy: AES128 ++++++++++++++++++++++++++++++++++ Send a SNMP GET request * with SNMPv3 with user 'usr-sha-aes', SHA auth and AES128 privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form This script performs similar to the following Net-SNMP command: | $ snmpget -v3 -l authPriv -u usr-sha-aes -a SHA -A authkey1 -x AES -X privkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-aes, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-aes', 'authPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() config.delTransport( snmpEngine, udp.domainName ).closeTransport() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/usm-sha-none.py000066400000000000000000000041671354244100700255220ustar00rootroot00000000000000""" Set string value ++++++++++++++++ Send a SNMP SET request with the following options: * with SNMPv3 with user 'usr-sha-none', SHA auth and no privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form and a string-typed value This script performs similar to the following Net-SNMP command: | $ snmpset -v3 -l authNoPriv -u usr-sha-none -a SHA -A authkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.3.1 s 'my new value' """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr-sha-none, auth: SHA, priv none config.addV3User( snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-sha-none', 'authNoPriv') # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString('my new value'))], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/v1-get.py000066400000000000000000000040051354244100700243020ustar00rootroot00000000000000""" SNMPv1 ++++++ * with SNMPv1, community 'public' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form This script performs similar to the following Net-SNMP command: | $ snmpget -v1 -c public -ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here elif errorStatus and errorStatus != 2: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/cmdgen/v2c-set.py000066400000000000000000000040301354244100700244600ustar00rootroot00000000000000""" Set scalar value ++++++++++++++++ Send a SNMP SET request * with SNMPv2c with community name 'private' * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form and an integer-typed value This script performs similar to the following Net-SNMP command: | $ snmpset -v2c -c private -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.4.1 t 123 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv2c setup # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'private') # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 1) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('104.236.166.95', 161), 'my-creds' ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?')) else: for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, 'my-router', None, '', # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv/000077500000000000000000000000001354244100700226735ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv/determine-peer-network-address.py000066400000000000000000000044151354244100700312700ustar00rootroot00000000000000""" Receive notifications noting peer address +++++++++++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:162 * use observer facility to pull lower-level request details from SNMP engine * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.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() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): # Get an execution context... execContext = snmpEngine.observer.getExecutionContext( 'rfc3412.receiveMessage:request' ) # ... and use inner SNMP engine data to figure out peer address print('Notification from %s, ContextEngineId "%s", ContextName "%s"' % ('@'.join([str(x) for x in execContext['transportAddress']]), contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv/multiple-network-interfaces.py000066400000000000000000000042011354244100700307050ustar00rootroot00000000000000""" Serving multiple network interfaces +++++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:162 over IPv4/UDP, listening at 127.0.0.1:2162 * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test | $ snmpinform -v2c -c public 127.0.0.1:2162 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.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() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode(('127.0.0.1', 2162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise multiple-network-transports-incl-ipv4-and-ipv6.py000066400000000000000000000042211354244100700341510ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv""" Using multiple network transports +++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:162 over IPv6/UDP, listening at [::1]:162 * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test | $ snmptrap -v2c -c public udp6:[::1]:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test | $ snmpinform -v2c -c public 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # UDP over IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv/multiple-usm-users.py000066400000000000000000000072251354244100700270470ustar00rootroot00000000000000""" Multiple SNMP USM users +++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv3 * with USM users: * 'usr-md5-des', auth: MD5, priv DES, ContextEngineId: 8000000001020304 * 'usr-md5-none', auth: MD5, priv NONE, ContextEngineId: 8000000001020304 * 'usr-sha-aes128', auth: SHA, priv AES, ContextEngineId: 8000000001020304 * over IPv4/UDP, listening at 127.0.0.1:162 * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 | $ snmptrap -v3 -u usr-md5-none -l authNoPriv -A authkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 | $ snmpinform -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv from pysnmp.proto.api import v2c # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1', securityEngineId=v2c.OctetString(hexValue='8000000001020304') ) # user: usr-md5-none, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) # user: usr-md5-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1', securityEngineId=v2c.OctetString(hexValue='8000000001020304') ) # user: usr-sha-aes128, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1', securityEngineId=v2c.OctetString(hexValue='8000000001020304') ) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise observe-request-processing-over-ipv4-and-ipv6.py000066400000000000000000000064161354244100700337550ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv""" Observe SNMP engine internal operations +++++++++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * over IPv4/UDP, listening at 127.0.0.1:162 over IPv6/UDP, listening at [::1]:162 * registers its own execution observer to snmpEngine * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v1 -c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test | $ snmptrap -v2c -c public udp6:[::1]:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test | $ snmpinform -v2c -c public 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Execution point observer setup # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at code point's local scope # noinspection PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): print('Execution point: %s' % execpoint) print('* transportDomain: %s' % '.'.join([str(x) for x in variables['transportDomain']])) print('* transportAddress: %s' % '@'.join([str(x) for x in variables['transportAddress']])) print('* securityModel: %s' % variables['securityModel']) print('* securityName: %s' % variables['securityName']) print('* securityLevel: %s' % variables['securityLevel']) print('* contextEngineId: %s' % variables['contextEngineId'].prettyPrint()) print('* contextName: %s' % variables['contextName'].prettyPrint()) print('* PDU: %s' % variables['pdu'].prettyPrint()) snmpEngine.observer.registerObserver( requestObserver, 'rfc3412.receiveMessage:request', 'rfc3412.returnResponsePdu' ) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # UDP over IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.observer.unregisterObserver() snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/manager/ntfrcv/regexp-community-name.py000066400000000000000000000063221354244100700275020ustar00rootroot00000000000000""" Serve SNMP Community names defined by regexp ++++++++++++++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with any SNMP community matching regexp '.*love.*' * over IPv4/UDP, listening at 127.0.0.1:162 * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v1 -c rollover 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test | $ snmpinform -v2c -c glove 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 The Notification Receiver below taps on v1/v2c SNMP security module to deliver certains values, normally internal to SNMP Engine, up to the context of user application. This script examines the value of CommunityName, as it came from peer SNMP Engine, and may modify it to match the only locally configured CommunityName 'public'. This effectively makes NotificationReceiver accepting messages with CommunityName's, not explicitly configured to local SNMP Engine. """# from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv import re # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at execution point's local scope. # If at this execution point passed variables are modified, their new # values will be propagated back and used by SNMP Engine for securityName # selection. # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): if re.match('.*love.*', str(variables['communityName'])): print('Rewriting communityName \'%s\' from %s into \'public\'' % (variables['communityName'], ':'.join([str(x) for x in variables['transportInformation'][1]]))) variables['communityName'] = variables['communityName'].clone('public') snmpEngine.observer.registerObserver( requestObserver, 'rfc2576.processIncomingMsg:writable' ) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode(('127.0.0.1', 162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/proxy/000077500000000000000000000000001354244100700211405ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/proxy/command/000077500000000000000000000000001354244100700225565ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/asyncore/proxy/command/ipv6-to-ipv4-conversion.py000066400000000000000000000077721354244100700275140ustar00rootroot00000000000000""" IPv6-to-IPv4 conversion +++++++++++++++++++++++ Act as a local SNMPv1/v2c Agent listening on a UDP/IPv6 transport, relay messages to distant SNMPv1/2c Agent over UDP/IPv4 transport: * with local SNMPv2c community 'public' * local Agent listening at [::1]:161 * remote SNMPv2c community 'public' * remote Agent listening at 104.236.166.95:161 This script can be queried with the following Net-SNMP command: | $ snmpget -v2c -c public udp6:[::1]:161 sysDescr.0 due to proxy, it is equivalent to | $ snmpget -v2c -c public 104.236.166.95:161 sysDescr.0 Warning: for production operation you would need to modify this script so that it will re-map possible duplicate request-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request-IDs to Agents. """# from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode(('::1', 161)) ) # Manager section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openClientMode() ) # # SNMPv1/2c setup (Agent role) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, '1-my-area', 'public') # # SNMPv1/v2c setup (Manager role) # # Here we configure securityName lexicographically lesser than '1-my-area' # to let it match first in snmpCommunityTable on response processing. # config.addV1System(snmpEngine, '0-distant-area', 'public', transportTag='remote') # # Transport target used by Manager # config.addTargetParams( snmpEngine, 'distant-agent-auth', '0-distant-area', 'noAuthNoPriv', 1 ) config.addTargetAddr( snmpEngine, 'distant-agent', udp.domainName, ('104.236.166.95', 161), 'distant-agent-auth', retryCount=0, tagList='remote' ) # Default SNMP context config.addContext(snmpEngine, '') class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, 'distant-agent', contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, 'error', None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu( snmpEngine, stateReference, PDU ) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/proxy/command/v2c-to-v1-conversion.py000066400000000000000000000077351354244100700267650ustar00rootroot00000000000000""" SNMPv2c-to-SNMPv1 conversion ++++++++++++++++++++++++++++ Act as a local SNMPv2c Agent, relay messages to distant SNMPv1 Agent: * over IPv4/UDP * with local SNMPv2c community public * local Agent listening at 127.0.0.1:161 * remote SNMPv1, community public * remote Agent listening at 104.236.166.95:161 This script can be queried with the following Net-SNMP command: | $ snmpbulkwalk -v2c -c public -ObentU 127.0.0.1:161 system due to proxy, it is equivalent to | $ snmpwalk -v1 -c public 104.236.166.95:161 system Warning: for production operation you would need to modify this script so that it will re-map possible duplicate request-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request-IDs to Agents. """# from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # Manager section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() ) # # SNMPv2c setup (Agent role) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # SNMPv1 setup (Manager role) # # SecurityName <-> CommunityName <-> Transport mapping config.addV1System(snmpEngine, 'distant-area', 'public', transportTag='distant') # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'distant-agent-auth', 'distant-area', 'noAuthNoPriv', 0) config.addTargetAddr( snmpEngine, 'distant-agent', udp.domainName + (2,), ('104.236.166.95', 161), 'distant-agent-auth', retryCount=0, tagList='distant' ) # Default SNMP context config.addContext(snmpEngine, '') class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, 'distant-agent', contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, 'error', None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu( snmpEngine, stateReference, PDU ) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/proxy/command/v2c-to-v3-conversion.py000066400000000000000000000077131354244100700267630ustar00rootroot00000000000000""" SNMPv2c-to-SNMPv3 conversion ++++++++++++++++++++++++++++ Act as a local SNMPv1/v2c Agent, relay messages to distant SNMPv3 Agent: * over IPv4/UDP * with local SNMPv2c community 'public' * local Agent listening at 127.0.0.1:161 * remote SNMPv3 user usr-md5-none, MD5 auth and no privacy protocols * remote Agent listening at 104.236.166.95:161 This script can be queried with the following Net-SNMP command: | $ snmpget -v2c -c public 127.0.0.1:161 1.3.6.1.2.1.1.1.0 due to proxy, it is equivalent to | $ snmpget -v3 -l authNoPriv -u usr-md5-none -A authkey1 -ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 Warning: for production operation you would need to modify this script so that it will re-map possible duplicate request-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request-IDs to Agents. """# from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # Manager section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() ) # # SNMPv1/2c setup (Agent role) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # SNMPv3/USM setup (Manager role) # # user: usr-md5-none, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) # # Transport target used by Manager # config.addTargetParams( snmpEngine, 'distant-agent-auth', 'usr-md5-none', 'authNoPriv' ) config.addTargetAddr( snmpEngine, 'distant-agent', udp.domainName + (2,), ('104.236.166.95', 161), 'distant-agent-auth', retryCount=0 ) # Default SNMP context config.addContext(snmpEngine, '') class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, 'distant-agent', contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, 'error', None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu( snmpEngine, stateReference, PDU ) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/asyncore/proxy/command/v3-to-v2c-conversion.py000066400000000000000000000101001354244100700267430ustar00rootroot00000000000000""" SNMPv3-to-SNMPv2c conversion ++++++++++++++++++++++++++++ Act as a local SNMPv3 Agent, relay messages to distant SNMPv1/v2c Agent: * over IPv4/UDP * with local SNMPv3 user usr-md5-des, MD5 auth and DES privacy protocols * local Agent listening at 127.0.0.1:161 * remote SNMPv1, community public * remote Agent listening at 104.236.166.95:161 This script can be queried with the following Net-SNMP command: | $ snmpget -v3 -l authPriv -u usr-md5-des -A authkey1 -X privkey1 -ObentU 127.0.0.1:161 1.3.6.1.2.1.1.1.0 due to proxy, it is equivalent to | $ snmpget -v2c -c public 104.236.166.95:161 1.3.6.1.2.1.1.1.0 Warning: for production operation you would need to modify this script so that it will re-map possible duplicate request-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request-IDs to Agents. """# from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode(('127.0.0.1', 161)) ) # Manager section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openClientMode() ) # # SNMPv3/USM setup (Agent role) # # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # # SNMPv1/2c setup (Manager role) # # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 - 0, SNMPv2c - 1) config.addTargetParams(snmpEngine, 'distant-agent-auth', 'my-area', 'noAuthNoPriv', 0) config.addTargetAddr( snmpEngine, 'distant-agent', udp.domainName + (2,), ('104.236.166.95', 161), 'distant-agent-auth', retryCount=0 ) # Default SNMP context config.addContext(snmpEngine, '') class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, 'distant-agent', contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, 'error', None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu(snmpEngine, stateReference, PDU) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise pysnmp-4.4.12/examples/v3arch/twisted/000077500000000000000000000000001354244100700176175ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/twisted/agent/000077500000000000000000000000001354244100700207155ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/twisted/agent/cmdrsp/000077500000000000000000000000001354244100700222055ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/twisted/agent/cmdrsp/implementing-scalar-mib-objects.py000066400000000000000000000045001354244100700307050ustar00rootroot00000000000000""" Implementing scalar MIB objects +++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv2c * with SNMP community "public" * serving custom Managed Object Instance defined within this script * allow read access only to the subtree where the custom MIB object resides * over IPv4/UDP, listening at 127.0.0.1:161 * using Twisted fraework for network transport Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 """# import sys from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.proto import rfc1902 from pysnmp.carrier.twisted.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 5)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # --- create custom Managed Object Instance --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() MibScalar, MibScalarInstance = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalar', 'MibScalarInstance' ) class MyStaticMibScalarInstance(MibScalarInstance): # noinspection PyUnusedLocal,PyUnusedLocal def getValue(self, name, idx): return self.getSyntax().clone( 'Python %s running on a %s platform' % (sys.version, sys.platform) ) mibBuilder.exportSymbols( '__MY_MIB', MibScalar((1, 3, 6, 5, 1), rfc1902.OctetString()), MyStaticMibScalarInstance((1, 3, 6, 5, 1), (0,), rfc1902.OctetString()) ) # --- end of Managed Object Instance initialization ---- # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Run Twisted main loop reactor.run() pysnmp-4.4.12/examples/v3arch/twisted/agent/cmdrsp/multiple-interfaces.py000066400000000000000000000035521354244100700265400ustar00rootroot00000000000000""" Listen on multiple network interfaces +++++++++++++++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv2c * with SNMP community "public" * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 and 127.0.0.2:161 interfaces * using Twisted framework for network transport Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v2c -c public 127.0.0.1 .1.3.6 | $ snmpwalk -v2c -c public 127.0.0.2 .1.3.6 """# from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.twisted.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 at 127.0.0.1:161 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161)) ) # UDP over IPv4 at 127.0.0.2:161 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTwistedTransport().openServerMode(('127.0.0.2', 161)) ) # SNMPv2c setup # SecurityName <-> CommunityName mapping. config.addV1System(snmpEngine, 'my-area', 'public') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, 'my-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Run Twisted main loop reactor.run() pysnmp-4.4.12/examples/v3arch/twisted/agent/cmdrsp/multiple-snmp-communities.py000066400000000000000000000036131354244100700277220ustar00rootroot00000000000000""" Multiple SNMP communities +++++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT queries with the following options: * SNMPv1 * with SNMP community "public" (read access) or "private" (write access) * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 * using Twisted fraework for network transport The following Net-SNMP commands will GET/SET a value at this Agent: | $ snmpget -v1 -c public 127.0.0.1 SNMPv2-MIB::sysLocation.0 | $ snmpset -v1 -c private 127.0.0.1 SNMPv2-MIB::sysLocation.0 s "far away" """# from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.twisted.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv1 setup # SecurityName <-> CommunityName mapping. # Here we configure two distinct CommunityName's to control read and write # operations. config.addV1System(snmpEngine, 'my-read-area', 'public') config.addV1System(snmpEngine, 'my-write-area', 'private') # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 1, 'my-read-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 1, 'my-write-area', 'noAuthNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Run Twisted main loop reactor.run() pysnmp-4.4.12/examples/v3arch/twisted/agent/cmdrsp/multiple-usm-users.py000066400000000000000000000047761354244100700263710ustar00rootroot00000000000000""" Multiple SNMP USM users +++++++++++++++++++++++ Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: * SNMPv3 * with USM user: * 'usr-md5-des', auth: MD5, priv DES or * 'usr-sha-none', auth: SHA, no privacy * 'usr-sha-aes128', auth: SHA, priv AES * allow access to SNMPv2-MIB objects (1.3.6.1.2.1) * over IPv4/UDP, listening at 127.0.0.1:161 * using Twisted framework for network transport Either of the following Net-SNMP commands will walk this Agent: | $ snmpwalk -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 localhost .1.3.6 | $ snmpwalk -v3 -u usr-sha-none -l authNoPriv -a SHA -A authkey1 localhost .1.3.6 | $ snmpwalk -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 localhost .1.3.6 """# from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.twisted.dgram import udp # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 161)) ) # SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-sha-none, auth: SHA, priv NONE config.addV3User( snmpEngine, 'usr-sha-none', config.usmHMACSHAAuthProtocol, 'authkey1' ) # user: usr-sha-none, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-none', 'authNoPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, 'usr-sha-aes128', 'authPriv', (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Run Twisted main loop reactor.run() pysnmp-4.4.12/examples/v3arch/twisted/manager/000077500000000000000000000000001354244100700212315ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/twisted/manager/ntfrcv/000077500000000000000000000000001354244100700225335ustar00rootroot00000000000000pysnmp-4.4.12/examples/v3arch/twisted/manager/ntfrcv/multiple-interfaces.py000066400000000000000000000040251354244100700270620ustar00rootroot00000000000000""" Serving multiple network interfaces +++++++++++++++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv1/SNMPv2c * with SNMP community "public" * listen on two local network interfaces: * IPv4/UDP, listening at 127.0.0.1:162 * IPv4/UDP, listening at 127.0.0.1:2162 * using Twisted framework for network transport * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v2c -c public 127.0.0.1:162 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test | $ snmpinform -v2c -c public 127.0.0.1:2162 123 1.3.6.1.6.3.1.1.5.1 """# from twisted.internet import reactor from pysnmp.entity import engine, config 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() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 2162)) ) # SNMPv1/2c setup # SecurityName <-> CommunityName mapping config.addV1System(snmpEngine, 'my-area', 'public') # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", Context "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run Twisted main loop reactor.run() pysnmp-4.4.12/examples/v3arch/twisted/manager/ntfrcv/multiple-usm-users.py000066400000000000000000000070751354244100700267120ustar00rootroot00000000000000""" Multiple SNMP USM users +++++++++++++++++++++++ Receive SNMP TRAP/INFORM messages with the following options: * SNMPv3 * with USM users: * 'usr-md5-des', auth: MD5, priv DES, ContextEngineId: 8000000001020304 * 'usr-md5-none', auth: MD5, priv NONE, ContextEngineId: 8000000001020304 * 'usr-sha-aes128', auth: SHA, priv AES, ContextEngineId: 8000000001020304 * over IPv4/UDP, listening at 127.0.0.1:162 * using Twisted framework for network transport * print received data on stdout Either of the following Net-SNMP commands will send notifications to this receiver: | $ snmptrap -v3 -u usr-md5-des -l authPriv -A authkey1 -X privkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 | $ snmptrap -v3 -u usr-md5-none -l authNoPriv -A authkey1 -e 8000000001020304 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 | $ snmpinform -v3 -u usr-sha-aes128 -l authPriv -a SHA -A authkey1 -x AES -X privkey1 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 """# from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.carrier.twisted.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv from pysnmp.proto import rfc1902 # Create SNMP engine with autogenernated engineID and pre-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openServerMode(('127.0.0.1', 162)) ) # -- begin of SNMPv3/USM setup # user: usr-md5-des, auth: MD5, priv DES config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) # user: usr-md5-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1', securityEngineId=rfc1902.OctetString(hexValue='8000000001020304') ) # user: usr-md5-none, auth: MD5, priv NONE config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) # user: usr-md5-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1', securityEngineId=rfc1902.OctetString(hexValue='8000000001020304') ) # user: usr-sha-aes128, auth: SHA, priv AES config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1' ) # user: usr-sha-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, 'usr-sha-aes128', config.usmHMACSHAAuthProtocol, 'authkey1', config.usmAesCfb128Protocol, 'privkey1', securityEngineId=rfc1902.OctetString(hexValue='8000000001020304') ) # -- end of SNMPv3/USM setup # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification from ContextEngineId "%s", ContextName "%s"' % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run Twisted main loop reactor.run() pysnmp-4.4.12/pysnmp/000077500000000000000000000000001354244100700144565ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/__init__.py000066400000000000000000000002611354244100700165660ustar00rootroot00000000000000# http://www.python.org/dev/peps/pep-0396/ __version__ = '4.4.12' # backward compatibility version = tuple([int(x) for x in __version__.split('.')]) majorVersionId = version[0] pysnmp-4.4.12/pysnmp/cache.py000066400000000000000000000023511354244100700160740ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Limited-size dictionary-like class to use for caches # class Cache(object): 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] += 1 return self.__cache[k] def __len__(self): return self.__size def __setitem__(self, k, v): if self.__size >= self.__maxSize: usageKeys = sorted(self.__usage, key=lambda x, d=self.__usage: d[x]) for _k in usageKeys[:self.__chopSize]: del self.__cache[_k] del self.__usage[_k] self.__size -= self.__chopSize if k not in self.__cache: 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 -= 1 pysnmp-4.4.12/pysnmp/carrier/000077500000000000000000000000001354244100700161055ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/__init__.py000066400000000000000000000000731354244100700202160ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asyncio/000077500000000000000000000000001354244100700175525ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/asyncio/__init__.py000066400000000000000000000000741354244100700216640ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asyncio/base.py000066400000000000000000000034761354244100700210500ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Copyright (C) 2014, Zebra Technologies # Authors: Matt Hooks # Zachary Lorusso # # 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. # # 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 COPYRIGHT HOLDERS AND 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. # from pysnmp.carrier.asyncio.dispatch import AsyncioDispatcher from pysnmp.carrier.base import AbstractTransport class AbstractAsyncioTransport(AbstractTransport): protoTransportDispatcher = AsyncioDispatcher """Base Asyncio Transport, to be used with AsyncioDispatcher""" pysnmp-4.4.12/pysnmp/carrier/asyncio/dgram/000077500000000000000000000000001354244100700206445ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/asyncio/dgram/__init__.py000066400000000000000000000000741354244100700227560ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asyncio/dgram/base.py000066400000000000000000000131071354244100700221320ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Copyright (C) 2014, Zebra Technologies # Authors: Matt Hooks # Zachary Lorusso # # 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. # # 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 COPYRIGHT HOLDERS AND 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. # import sys import platform import traceback from pysnmp.carrier.asyncio.base import AbstractAsyncioTransport from pysnmp.carrier import error from pysnmp import debug try: import asyncio except ImportError: import trollius as asyncio IS_PYTHON_344_PLUS = platform.python_version_tuple() >= ('3', '4', '4') class DgramAsyncioProtocol(asyncio.DatagramProtocol, AbstractAsyncioTransport): """Base Asyncio datagram Transport, to be used with AsyncioDispatcher""" sockFamily = None addressType = lambda x: x transport = None def __init__(self, sock=None, sockMap=None, loop=None): self._writeQ = [] self._lport = None if loop is None: loop = asyncio.get_event_loop() self.loop = loop def datagram_received(self, datagram, transportAddress): if self._cbFun is None: raise error.CarrierError('Unable to call cbFun') else: self.loop.call_soon(self._cbFun, self, transportAddress, datagram) def connection_made(self, transport): self.transport = transport debug.logger & debug.flagIO and debug.logger('connection_made: invoked') while self._writeQ: outgoingMessage, transportAddress = self._writeQ.pop(0) debug.logger & debug.flagIO and debug.logger('connection_made: transportAddress %r outgoingMessage %s' % (transportAddress, debug.hexdump(outgoingMessage))) try: self.transport.sendto(outgoingMessage, self.normalizeAddress(transportAddress)) except Exception: raise error.CarrierError(';'.join(traceback.format_exception(*sys.exc_info()))) def connection_lost(self, exc): debug.logger & debug.flagIO and debug.logger('connection_lost: invoked') # AbstractAsyncioTransport API def openClientMode(self, iface=None): try: c = self.loop.create_datagram_endpoint( lambda: self, local_addr=iface, family=self.sockFamily ) # Avoid deprecation warning for asyncio.async() if IS_PYTHON_344_PLUS: self._lport = asyncio.ensure_future(c) else: # pragma: no cover self._lport = getattr(asyncio, 'async')(c) except Exception: raise error.CarrierError(';'.join(traceback.format_exception(*sys.exc_info()))) return self def openServerMode(self, iface): try: c = self.loop.create_datagram_endpoint( lambda: self, local_addr=iface, family=self.sockFamily ) # Avoid deprecation warning for asyncio.async() if IS_PYTHON_344_PLUS: self._lport = asyncio.ensure_future(c) else: # pragma: no cover self._lport = getattr(asyncio, 'async')(c) except Exception: raise error.CarrierError(';'.join(traceback.format_exception(*sys.exc_info()))) return self def closeTransport(self): if self._lport is not None: self._lport.cancel() if self.transport is not None: self.transport.close() AbstractAsyncioTransport.closeTransport(self) def sendMessage(self, outgoingMessage, transportAddress): debug.logger & debug.flagIO and debug.logger('sendMessage: %s transportAddress %r outgoingMessage %s' % ( (self.transport is None and "queuing" or "sending"), transportAddress, debug.hexdump(outgoingMessage) )) if self.transport is None: self._writeQ.append((outgoingMessage, transportAddress)) else: try: self.transport.sendto(outgoingMessage, self.normalizeAddress(transportAddress)) except Exception: raise error.CarrierError(';'.join(traceback.format_exception(*sys.exc_info()))) def normalizeAddress(self, transportAddress): if not isinstance(transportAddress, self.addressType): transportAddress = self.addressType(transportAddress) return transportAddress pysnmp-4.4.12/pysnmp/carrier/asyncio/dgram/udp.py000066400000000000000000000037071354244100700220150ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Copyright (C) 2014, Zebra Technologies # Authors: Matt Hooks # Zachary Lorusso # # 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. # # 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 COPYRIGHT HOLDERS AND 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. # import socket from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncio.dgram.base import DgramAsyncioProtocol domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) class UdpTransportAddress(tuple, AbstractTransportAddress): pass class UdpAsyncioTransport(DgramAsyncioProtocol): sockFamily = socket.AF_INET addressType = UdpTransportAddress UdpTransport = UdpAsyncioTransport pysnmp-4.4.12/pysnmp/carrier/asyncio/dgram/udp6.py000066400000000000000000000021121354244100700220700ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncio.dgram.base import DgramAsyncioProtocol domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2) class Udp6TransportAddress(tuple, AbstractTransportAddress): pass class Udp6AsyncioTransport(DgramAsyncioProtocol): sockFamily = socket.has_ipv6 and socket.AF_INET6 or None addressType = Udp6TransportAddress def normalizeAddress(self, transportAddress): if '%' in transportAddress[0]: # strip zone ID return self.addressType((transportAddress[0].split('%')[0], transportAddress[1], 0, # flowinfo 0)) # scopeid else: return self.addressType((transportAddress[0], transportAddress[1], 0, 0)) Udp6Transport = Udp6AsyncioTransport pysnmp-4.4.12/pysnmp/carrier/asyncio/dispatch.py000066400000000000000000000100241354244100700217200ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Copyright (C) 2014, Zebra Technologies # Authors: Matt Hooks # Zachary Lorusso # # 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. # # 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 COPYRIGHT HOLDERS AND 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. # import sys import platform import traceback from pysnmp.carrier.base import AbstractTransportDispatcher from pysnmp.error import PySnmpError try: import asyncio except ImportError: import trollius as asyncio IS_PYTHON_344_PLUS = platform.python_version_tuple() >= ('3', '4', '4') class AsyncioDispatcher(AbstractTransportDispatcher): """AsyncioDispatcher based on asyncio event loop""" def __init__(self, *args, **kwargs): AbstractTransportDispatcher.__init__(self) self.__transportCount = 0 if 'timeout' in kwargs: self.setTimerResolution(kwargs['timeout']) self.loopingcall = None self.loop = kwargs.pop('loop', asyncio.get_event_loop()) @asyncio.coroutine def handle_timeout(self): while True: yield asyncio.From(asyncio.sleep(self.getTimerResolution())) self.handleTimerTick(self.loop.time()) def runDispatcher(self, timeout=0.0): if not self.loop.is_running(): try: self.loop.run_forever() except KeyboardInterrupt: raise except Exception: raise PySnmpError(';'.join(traceback.format_exception(*sys.exc_info()))) def registerTransport(self, tDomain, transport): if self.loopingcall is None and self.getTimerResolution() > 0: # Avoid deprecation warning for asyncio.async() if IS_PYTHON_344_PLUS: self.loopingcall = asyncio.ensure_future(self.handle_timeout()) else: # pragma: no cover self.loopingcall = getattr(asyncio, 'async')(self.handle_timeout()) AbstractTransportDispatcher.registerTransport( self, tDomain, transport ) self.__transportCount += 1 def unregisterTransport(self, tDomain): t = AbstractTransportDispatcher.getTransport(self, tDomain) if t is not None: AbstractTransportDispatcher.unregisterTransport(self, tDomain) self.__transportCount -= 1 # The last transport has been removed, stop the timeout if self.__transportCount == 0 and not self.loopingcall.done(): self.loopingcall.cancel() self.loopingcall = None # Trollius or Tulip? if not hasattr(asyncio, "From"): exec ("""\ @asyncio.coroutine def handle_timeout(self): while True: yield from asyncio.sleep(self.getTimerResolution()) self.handleTimerTick(self.loop.time()) AsyncioDispatcher.handle_timeout = handle_timeout\ """) pysnmp-4.4.12/pysnmp/carrier/asyncore/000077500000000000000000000000001354244100700177305ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/asyncore/__init__.py000066400000000000000000000000731354244100700220410ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asyncore/base.py000066400000000000000000000064171354244100700212240ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket import sys import asyncore from pysnmp.carrier import error from pysnmp.carrier.base import AbstractTransport from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp import debug class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): protoTransportDispatcher = AsyncoreDispatcher sockFamily = sockType = None retryCount = 0 retryInterval = 0 bufferSize = 131070 # noinspection PyUnusedLocal def __init__(self, sock=None, sockMap=None): asyncore.dispatcher.__init__(self) 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]) try: for b in socket.SO_RCVBUF, socket.SO_SNDBUF: bsize = sock.getsockopt(socket.SOL_SOCKET, b) if bsize < self.bufferSize: sock.setsockopt(socket.SOL_SOCKET, b, self.bufferSize) debug.logger & debug.flagIO and debug.logger('%s: socket %d buffer size increased from %d to %d for buffer %d' % (self.__class__.__name__, sock.fileno(), bsize, self.bufferSize, b)) except Exception: debug.logger & debug.flagIO and debug.logger('%s: socket buffer size option mangling failure for buffer: %s' % (self.__class__.__name__, sys.exc_info()[1])) # The socket map is managed by the AsyncoreDispatcher on # which this transport is registered. Here we just prepare # socket and postpone transport registration at dispatcher # till AsyncoreDispatcher invokes registerSocket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) self.set_socket(sock) def __hash__(self): return hash(self.socket) # The following two methods are part of base class so here we overwrite # them to separate socket management from dispatcher registration tasks. # These two are just for dispatcher registration. def add_channel(self, map=None): if map is not None: map[self._fileno] = self self.connected = True def del_channel(self, map=None): if map is not None and self._fileno in map: del map[self._fileno] self.connected = False def registerSocket(self, sockMap=None): self.add_channel(sockMap) def unregisterSocket(self, sockMap=None): self.del_channel(sockMap) def closeTransport(self): AbstractTransport.closeTransport(self) self.close() # asyncore API def handle_close(self): raise error.CarrierError('Transport unexpectedly closed') def handle_error(self): raise pysnmp-4.4.12/pysnmp/carrier/asyncore/dgram/000077500000000000000000000000001354244100700210225ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/asyncore/dgram/__init__.py000066400000000000000000000000731354244100700231330ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asyncore/dgram/base.py000066400000000000000000000164001354244100700223070ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket import errno import sys from pysnmp.carrier.asyncore.base import AbstractSocketTransport from pysnmp.carrier import sockfix, sockmsg, error from pysnmp import debug # Ignore these socket errors sockErrors = {errno.ESHUTDOWN: True, errno.ENOTCONN: True, errno.ECONNRESET: False, errno.ECONNREFUSED: False, errno.EAGAIN: False, errno.EWOULDBLOCK: False} if hasattr(errno, 'EBADFD'): # bad FD may happen upon FD closure on n-1 select() event sockErrors[errno.EBADFD] = True class DgramSocketTransport(AbstractSocketTransport): sockType = socket.SOCK_DGRAM retryCount = 3 retryInterval = 1 addressType = lambda x: x def __init__(self, sock=None, sockMap=None): self.__outQueue = [] self._sendto = lambda s, b, a: s.sendto(b, a) def __recvfrom(s, sz): d, a = s.recvfrom(sz) return d, self.addressType(a) self._recvfrom = __recvfrom AbstractSocketTransport.__init__(self, sock, sockMap) def openClientMode(self, iface=None): if iface is not None: try: self.socket.bind(iface) except socket.error: raise error.CarrierError( 'bind() for %s failed: %s' % (iface is None and "" or iface, sys.exc_info()[1])) return self def openServerMode(self, iface): try: self.socket.bind(iface) except socket.error: raise error.CarrierError('bind() for %s failed: %s' % (iface, sys.exc_info()[1],)) return self def enableBroadcast(self, flag=1): try: self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, flag ) except socket.error: raise error.CarrierError('setsockopt() for SO_BROADCAST failed: %s' % (sys.exc_info()[1],)) debug.logger & debug.flagIO and debug.logger('enableBroadcast: %s option SO_BROADCAST on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno())) return self def enablePktInfo(self, flag=1): if (not hasattr(self.socket, 'sendmsg') or not hasattr(self.socket, 'recvmsg')): raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version') try: if self.socket.family == socket.AF_INET: self.socket.setsockopt(socket.SOL_IP, socket.IP_PKTINFO, flag) if self.socket.family == socket.AF_INET6: self.socket.setsockopt(socket.SOL_IPV6, socket.IPV6_RECVPKTINFO, flag) except socket.error: raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", sys.exc_info()[1])) self._sendto = sockmsg.getSendTo(self.addressType) self._recvfrom = sockmsg.getRecvFrom(self.addressType) debug.logger & debug.flagIO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno())) return self def enableTransparent(self, flag=1): try: if self.socket.family == socket.AF_INET: self.socket.setsockopt( socket.SOL_IP, socket.IP_TRANSPARENT, flag ) if self.socket.family == socket.AF_INET6: self.socket.setsockopt( socket.SOL_IPV6, socket.IPV6_TRANSPARENT, flag ) except socket.error: raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % sys.exc_info()[1]) except OSError: raise error.CarrierError('IP_TRANSPARENT socket option requires superusre previleges') debug.logger & debug.flagIO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno())) return self def sendMessage(self, outgoingMessage, transportAddress): self.__outQueue.append( (outgoingMessage, self.normalizeAddress(transportAddress)) ) debug.logger & debug.flagIO and debug.logger('sendMessage: outgoingMessage queued (%d octets) %s' % (len(outgoingMessage), debug.hexdump(outgoingMessage))) def normalizeAddress(self, transportAddress): if not isinstance(transportAddress, self.addressType): transportAddress = self.addressType(transportAddress) if not transportAddress.getLocalAddress(): transportAddress.setLocalAddress(self.getLocalAddress()) return transportAddress def getLocalAddress(self): # one evil OS does not seem to support getsockname() for DGRAM sockets try: return self.socket.getsockname() except Exception: return '0.0.0.0', 0 # asyncore API def handle_connect(self): pass def writable(self): return self.__outQueue def handle_write(self): outgoingMessage, transportAddress = self.__outQueue.pop(0) debug.logger & debug.flagIO and debug.logger('handle_write: transportAddress %r -> %r outgoingMessage (%d octets) %s' % (transportAddress.getLocalAddress(), transportAddress, len(outgoingMessage), debug.hexdump(outgoingMessage))) if not transportAddress: debug.logger & debug.flagIO and debug.logger('handle_write: missing dst address, loosing outgoing msg') return try: self._sendto( self.socket, 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 error.CarrierError('sendto() failed for %s: %s' % (transportAddress, sys.exc_info()[1])) def readable(self): return 1 def handle_read(self): try: incomingMessage, transportAddress = self._recvfrom(self.socket, 65535) transportAddress = self.normalizeAddress(transportAddress) debug.logger & debug.flagIO and debug.logger( 'handle_read: transportAddress %r -> %r incomingMessage (%d octets) %s' % (transportAddress, transportAddress.getLocalAddress(), len(incomingMessage), debug.hexdump(incomingMessage))) 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 error.CarrierError('recvfrom() failed: %s' % (sys.exc_info()[1],)) def handle_close(self): pass # no datagram connection pysnmp-4.4.12/pysnmp/carrier/asyncore/dgram/udp.py000066400000000000000000000011051354244100700221610ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from socket import AF_INET from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) class UdpTransportAddress(tuple, AbstractTransportAddress): pass class UdpSocketTransport(DgramSocketTransport): sockFamily = AF_INET addressType = UdpTransportAddress UdpTransport = UdpSocketTransport pysnmp-4.4.12/pysnmp/carrier/asyncore/dgram/udp6.py000066400000000000000000000025521354244100700222560ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.carrier import sockfix from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport import socket domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2) class Udp6TransportAddress(tuple, AbstractTransportAddress): pass class Udp6SocketTransport(DgramSocketTransport): sockFamily = socket.has_ipv6 and socket.AF_INET6 or None addressType = Udp6TransportAddress def normalizeAddress(self, transportAddress): if '%' in transportAddress[0]: # strip zone ID ta = self.addressType((transportAddress[0].split('%')[0], transportAddress[1], 0, # flowinfo 0)) # scopeid else: ta = self.addressType((transportAddress[0], transportAddress[1], 0, 0)) if (isinstance(transportAddress, self.addressType) and transportAddress.getLocalAddress()): return ta.setLocalAddress(transportAddress.getLocalAddress()) else: return ta.setLocalAddress(self.getLocalAddress()) Udp6Transport = Udp6SocketTransport pysnmp-4.4.12/pysnmp/carrier/asyncore/dgram/unix.py000066400000000000000000000031221354244100700223550ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import os import random try: from socket import AF_UNIX except ImportError: AF_UNIX = None from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.asyncore.dgram.base import DgramSocketTransport domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) random.seed() class UnixTransportAddress(str, AbstractTransportAddress): pass class UnixSocketTransport(DgramSocketTransport): sockFamily = AF_UNIX addressType = UnixTransportAddress _iface = '' def openClientMode(self, iface=None): if iface is None: # UNIX domain sockets must be explicitly bound iface = '' while len(iface) < 8: iface += chr(random.randrange(65, 91)) iface += chr(random.randrange(97, 123)) iface = os.path.sep + 'tmp' + os.path.sep + 'pysnmp' + iface if os.path.exists(iface): os.remove(iface) DgramSocketTransport.openClientMode(self, iface) self._iface = iface return self def openServerMode(self, iface): DgramSocketTransport.openServerMode(self, iface) self._iface = iface return self def closeTransport(self): DgramSocketTransport.closeTransport(self) try: os.remove(self._iface) except OSError: pass UnixTransport = UnixSocketTransport # Compatibility stub UnixDgramSocketTransport = UnixSocketTransport pysnmp-4.4.12/pysnmp/carrier/asyncore/dispatch.py000066400000000000000000000033031354244100700221000ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from time import time from sys import exc_info from traceback import format_exception from asyncore import socket_map from asyncore import loop from pysnmp.carrier.base import AbstractTransportDispatcher from pysnmp.error import PySnmpError class AsyncoreDispatcher(AbstractTransportDispatcher): def __init__(self): self.__sockMap = {} # use own map for MT safety self.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(): try: loop(timeout or self.getTimerResolution(), use_poll=True, map=self.__sockMap, count=1) except KeyboardInterrupt: raise except: raise PySnmpError('poll error: %s' % ';'.join(format_exception(*exc_info()))) self.handleTimerTick(time()) pysnmp-4.4.12/pysnmp/carrier/asynsock/000077500000000000000000000000001354244100700177375ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/asynsock/__init__.py000066400000000000000000000000731354244100700220500ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asynsock/dgram/000077500000000000000000000000001354244100700210315ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/asynsock/dgram/__init__.py000066400000000000000000000000731354244100700231420ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/asynsock/dgram/udp.py000066400000000000000000000003151354244100700221720ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.carrier.asyncore.dgram.udp import * pysnmp-4.4.12/pysnmp/carrier/asynsock/dgram/udp6.py000066400000000000000000000003161354244100700222610ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.carrier.asyncore.dgram.udp6 import * pysnmp-4.4.12/pysnmp/carrier/asynsock/dgram/unix.py000066400000000000000000000003161354244100700223660ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.carrier.asyncore.dgram.unix import * pysnmp-4.4.12/pysnmp/carrier/asynsock/dispatch.py000066400000000000000000000003651354244100700221140ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.carrier.asyncore.dispatch import * AsynsockDispatcher = AsyncoreDispatcher pysnmp-4.4.12/pysnmp/carrier/base.py000066400000000000000000000202411354244100700173700ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.carrier import error class TimerCallable(object): def __init__(self, cbFun, callInterval): self.__cbFun = cbFun self.__nextCall = 0 if sys.version_info > (2, 6): self.__callInterval = callInterval else: self.interval = callInterval def __call__(self, timeNow): if self.__nextCall <= timeNow: self.__cbFun(timeNow) self.__nextCall = timeNow + self.interval 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 if sys.version_info > (2, 6): @property def interval(self): return self.__callInterval @interval.setter def interval(self, callInterval): self.__callInterval = callInterval class AbstractTransportDispatcher(object): def __init__(self): self.__transports = {} self.__transportDomainMap = {} self.__jobs = {} self.__recvCallables = {} self.__timerCallables = [] self.__ticks = 0 self.__timerResolution = 0.5 self.__timerDelta = self.__timerResolution * 0.05 self.__nextTime = 0 self.__routingCbFun = None def _cbFun(self, incomingTransport, transportAddress, incomingMessage): if incomingTransport in self.__transportDomainMap: transportDomain = self.__transportDomainMap[incomingTransport] else: raise error.CarrierError( 'Unregistered transport %s' % (incomingTransport,) ) if self.__routingCbFun: recvId = self.__routingCbFun( transportDomain, transportAddress, incomingMessage ) else: recvId = None if recvId in self.__recvCallables: self.__recvCallables[recvId]( self, transportDomain, transportAddress, incomingMessage ) else: raise error.CarrierError( 'No callback for "%r" found - loosing incoming event' % (recvId,) ) # Dispatcher API def registerRoutingCbFun(self, routingCbFun): if self.__routingCbFun: raise error.CarrierError( 'Data routing callback already registered' ) self.__routingCbFun = routingCbFun def unregisterRoutingCbFun(self): if self.__routingCbFun: self.__routingCbFun = None def registerRecvCbFun(self, recvCb, recvId=None): if recvId in self.__recvCallables: raise error.CarrierError( 'Receive callback %r already registered' % (recvId is None and '' or recvId,) ) self.__recvCallables[recvId] = recvCb def unregisterRecvCbFun(self, recvId=None): if recvId in self.__recvCallables: del self.__recvCallables[recvId] 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: self.__timerCallables.remove(timerCbFun) else: self.__timerCallables = [] 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 self.__transportDomainMap[transport] = tDomain def unregisterTransport(self, tDomain): if tDomain not in self.__transports: raise error.CarrierError( 'Transport %s not registered' % (tDomain,) ) self.__transports[tDomain].unregisterCbFun() del self.__transportDomainMap[self.__transports[tDomain]] del self.__transports[tDomain] 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') for timerCallable in self.__timerCallables: if timerCallable.interval == self.__timerResolution: # Update periodics for default resolutions timerCallable.interval = timerResolution self.__timerResolution = timerResolution self.__timerDelta = timerResolution * 0.05 def getTimerTicks(self): return self.__ticks def handleTimerTick(self, timeNow): if self.__nextTime == 0: # initial initialization self.__nextTime = timeNow + self.__timerResolution - self.__timerDelta if self.__nextTime >= timeNow: return self.__ticks += 1 self.__nextTime = timeNow + self.__timerResolution - self.__timerDelta for timerCallable in self.__timerCallables: timerCallable(timeNow) def jobStarted(self, jobId, count=1): if jobId in self.__jobs: self.__jobs[jobId] += count else: self.__jobs[jobId] = count def jobFinished(self, jobId, count=1): self.__jobs[jobId] -= count if self.__jobs[jobId] == 0: del self.__jobs[jobId] def jobsArePending(self): return bool(self.__jobs) 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.__transports.clear() self.unregisterRecvCbFun() self.unregisterTimerCbFun() class AbstractTransportAddress(object): _localAddress = None def setLocalAddress(self, s): self._localAddress = s return self def getLocalAddress(self): return self._localAddress def clone(self, localAddress=None): return self.__class__(self).setLocalAddress(localAddress is None and self.getLocalAddress() or localAddress) class AbstractTransport(object): protoTransportDispatcher = None addressType = AbstractTransportAddress _cbFun = None @classmethod def isCompatibleWithDispatcher(cls, transportDispatcher): return isinstance(transportDispatcher, cls.protoTransportDispatcher) def registerCbFun(self, cbFun): if self._cbFun: raise error.CarrierError( 'Callback function %s already registered at %s' % (self._cbFun, self) ) self._cbFun = cbFun def unregisterCbFun(self): self._cbFun = None def closeTransport(self): self.unregisterCbFun() # Public API def openClientMode(self, iface=None): raise error.CarrierError('Method not implemented') def openServerMode(self, iface): raise error.CarrierError('Method not implemented') def sendMessage(self, outgoingMessage, transportAddress): raise error.CarrierError('Method not implemented') pysnmp-4.4.12/pysnmp/carrier/error.py000066400000000000000000000003501354244100700176060ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp import error class CarrierError(error.PySnmpError): pass pysnmp-4.4.12/pysnmp/carrier/sockfix.py000066400000000000000000000012411354244100700201230ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket from pysnmp import debug SYMBOLS = { 'IP_PKTINFO': 8, 'IP_TRANSPARENT': 19, 'SOL_IPV6': 41, 'IPV6_RECVPKTINFO': 49, 'IPV6_PKTINFO': 50, 'IPV6_TRANSPARENT': 75 } for symbol, value in SYMBOLS.items(): if not hasattr(socket, symbol): setattr(socket, symbol, value) debug.logger & debug.flagIO and debug.logger( 'WARNING: the socket module on this platform misses option %s. ' 'Assuming its value is %d.' % (symbol, value) ) pysnmp-4.4.12/pysnmp/carrier/sockmsg.py000066400000000000000000000101601354244100700201230ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # The following routines act like sendto()/recvfrom() calls but additionally # support local address retrieval (what can be useful when listening on # 0.0.0.0 or [::]) and source address spoofing (for transparent proxying). # # These routines are based on POSIX sendmsg()/recvmsg() calls which were made # available since Python 3.3. Therefore this module is only Python 3.x # compatible. # # Parts of the code below is taken from: # http://carnivore.it/2012/10/12/python3.3_sendmsg_and_recvmsg # import sys from pysnmp import debug if sys.version_info[:2] < (3, 3): # noinspection PyUnusedLocal def getRecvFrom(addressType): raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version') def getSendTo(addressType): raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version') else: import ctypes import ipaddress import socket from pysnmp.carrier import sockfix from pysnmp.carrier import error uint32_t = ctypes.c_uint32 in_addr_t = uint32_t class in_addr(ctypes.Structure): _fields_ = [('s_addr', in_addr_t)] class in6_addr_U(ctypes.Union): _fields_ = [ ('__u6_addr8', ctypes.c_uint8 * 16), ('__u6_addr16', ctypes.c_uint16 * 8), ('__u6_addr32', ctypes.c_uint32 * 4), ] class in6_addr(ctypes.Structure): _fields_ = [ ('__in6_u', in6_addr_U), ] class in_pktinfo(ctypes.Structure): _fields_ = [ ('ipi_ifindex', ctypes.c_int), ('ipi_spec_dst', in_addr), ('ipi_addr', in_addr), ] class in6_pktinfo(ctypes.Structure): _fields_ = [ ('ipi6_addr', in6_addr), ('ipi6_ifindex', ctypes.c_uint), ] def getRecvFrom(addressType): def recvfrom(s, sz): _to = None data, ancdata, msg_flags, _from = s.recvmsg(sz, socket.CMSG_LEN(sz)) for anc in ancdata: if anc[0] == socket.SOL_IP and anc[1] == socket.IP_PKTINFO: addr = in_pktinfo.from_buffer_copy(anc[2]) addr = ipaddress.IPv4Address(memoryview(addr.ipi_addr).tobytes()) _to = (str(addr), s.getsockname()[1]) break elif anc[0] == socket.SOL_IPV6 and anc[1] == socket.IPV6_PKTINFO: addr = in6_pktinfo.from_buffer_copy(anc[2]) addr = ipaddress.ip_address(memoryview(addr.ipi6_addr).tobytes()) _to = (str(addr), s.getsockname()[1]) break debug.logger & debug.flagIO and debug.logger( 'recvfrom: received %d octets from %s to %s; ' 'iov blob %r' % (len(data), _from, _to, ancdata)) return data, addressType(_from).setLocalAddress(_to) return recvfrom def getSendTo(addressType): def sendto(s, _data, _to): ancdata = [] if type(_to) == addressType: addr = ipaddress.ip_address(_to.getLocalAddress()[0]) else: addr = ipaddress.ip_address(s.getsockname()[0]) if type(addr) == ipaddress.IPv4Address: _f = in_pktinfo() _f.ipi_spec_dst = in_addr.from_buffer_copy(addr.packed) ancdata = [(socket.SOL_IP, socket.IP_PKTINFO, memoryview(_f).tobytes())] elif s.family == socket.AF_INET6 and type(addr) == ipaddress.IPv6Address: _f = in6_pktinfo() _f.ipi6_addr = in6_addr.from_buffer_copy(addr.packed) ancdata = [(socket.SOL_IPV6, socket.IPV6_PKTINFO, memoryview(_f).tobytes())] debug.logger & debug.flagIO and debug.logger( 'sendto: sending %d octets to %s; address %r; ' 'iov blob %r' % (len(_data), _to, addr, ancdata)) return s.sendmsg([_data], ancdata, 0, _to) return sendto pysnmp-4.4.12/pysnmp/carrier/twisted/000077500000000000000000000000001354244100700175705ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/twisted/__init__.py000066400000000000000000000000731354244100700217010ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/twisted/base.py000066400000000000000000000014331354244100700210550ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # 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 BSD 2-Clause License as shipped with pysnmp. # # Description: twisted DatagramProtocol UDP transport # from pysnmp.carrier.twisted.dispatch import TwistedDispatcher from pysnmp.carrier.base import AbstractTransport class AbstractTwistedTransport(AbstractTransport): protoTransportDispatcher = TwistedDispatcher def __init__(self, sock=None, sockMap=None): self._writeQ = [] AbstractTransport.__init__(self) pysnmp-4.4.12/pysnmp/carrier/twisted/dgram/000077500000000000000000000000001354244100700206625ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/carrier/twisted/dgram/__init__.py000066400000000000000000000000731354244100700227730ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/carrier/twisted/dgram/base.py000066400000000000000000000042761354244100700221570ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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, transportAddress): 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, transportAddress, 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 %s' % (transportAddress, debug.hexdump(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') def sendMessage(self, outgoingMessage, transportAddress): debug.logger & debug.flagIO and debug.logger('startProtocol: %s transportAddress %r outgoingMessage %s' % ((self.transport is None and "queuing" or "sending"), transportAddress, debug.hexdump(outgoingMessage))) 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],)) pysnmp-4.4.12/pysnmp/carrier/twisted/dgram/udp.py000066400000000000000000000025721354244100700220320ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from twisted.internet import reactor from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport from pysnmp.carrier import error domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) class UdpTransportAddress(tuple, AbstractTransportAddress): pass class UdpTwistedTransport(DgramTwistedTransport): addressType = UdpTransportAddress _lport = None # AbstractTwistedTransport API def openClientMode(self, iface=None): if iface is None: iface = ('', 0) try: self._lport = reactor.listenUDP(iface[1], self, iface[0]) except Exception: raise error.CarrierError(sys.exc_info()[1]) return self def openServerMode(self, iface): try: self._lport = reactor.listenUDP(iface[1], self, iface[0]) except Exception: raise error.CarrierError(sys.exc_info()[1]) return self def closeTransport(self): if self._lport is not None: d = self._lport.stopListening() if d: d.addCallback(lambda x: None) DgramTwistedTransport.closeTransport(self) UdpTransport = UdpTwistedTransport pysnmp-4.4.12/pysnmp/carrier/twisted/dgram/unix.py000066400000000000000000000025031354244100700222170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from twisted.internet import reactor from pysnmp.carrier.base import AbstractTransportAddress from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport from pysnmp.carrier import error domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) class UnixTransportAddress(str, AbstractTransportAddress): pass class UnixTwistedTransport(DgramTwistedTransport): addressType = UnixTransportAddress _lport = None # 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): try: self._lport = reactor.listenUNIXDatagram(iface, self) except Exception: raise error.CarrierError(sys.exc_info()[1]) return self def closeTransport(self): if self._lport is not None: d = self._lport.stopListening() if d: d.addCallback(lambda x: None) DgramTwistedTransport.closeTransport(self) UnixTransport = UnixTwistedTransport pysnmp-4.4.12/pysnmp/carrier/twisted/dispatch.py000066400000000000000000000042611354244100700217440ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # 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 BSD 2-Clause License as shipped with pysnmp. # # Description: Transport dispatcher based on twisted.internet.reactor # import sys, time, traceback from twisted.internet import reactor, task from pysnmp.carrier.base import AbstractTransportDispatcher from pysnmp.error import PySnmpError class TwistedDispatcher(AbstractTransportDispatcher): """TransportDispatcher based on twisted.internet.reactor""" def __init__(self, *args, **kwargs): AbstractTransportDispatcher.__init__(self) self.__transportCount = 0 if 'timeout' in kwargs: self.setTimerResolution(kwargs['timeout']) self.loopingcall = task.LoopingCall( lambda self=self: self.handleTimerTick(time.time()) ) def runDispatcher(self, timeout=0.0): if not reactor.running: try: reactor.run() except KeyboardInterrupt: raise except: raise PySnmpError('reactor error: %s' % ';'.join(traceback.format_exception(*sys.exc_info()))) # 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 += 1 def unregisterTransport(self, tDomain): t = AbstractTransportDispatcher.getTransport(self, tDomain) if t is not None: AbstractTransportDispatcher.unregisterTransport(self, tDomain) self.__transportCount -= 1 # The last transport has been removed, stop the timeout if self.__transportCount == 0 and self.loopingcall.running: self.loopingcall.stop() pysnmp-4.4.12/pysnmp/debug.py000066400000000000000000000065361354244100700161300ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import logging from pyasn1.compat.octets import octs2ints from pysnmp import error from pysnmp import __version__ flagNone = 0x0000 flagIO = 0x0001 flagDsp = 0x0002 flagMP = 0x0004 flagSM = 0x0008 flagBld = 0x0010 flagMIB = 0x0020 flagIns = 0x0040 flagACL = 0x0080 flagPrx = 0x0100 flagApp = 0x0200 flagAll = 0xffff flagMap = {'io': flagIO, 'dsp': flagDsp, 'msgproc': flagMP, 'secmod': flagSM, 'mibbuild': flagBld, 'mibview': flagMIB, 'mibinstrum': flagIns, 'acl': flagACL, 'proxy': flagPrx, 'app': flagApp, 'all': flagAll} class Printer(object): def __init__(self, logger=None, handler=None, formatter=None): if logger is None: logger = logging.getLogger('pysnmp') logger.setLevel(logging.DEBUG) if handler is None: handler = logging.StreamHandler() if formatter is None: formatter = logging.Formatter('%(asctime)s %(name)s: %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) logger.addHandler(handler) self.__logger = logger def __call__(self, msg): self.__logger.debug(msg) def __str__(self): return '' if hasattr(logging, 'NullHandler'): NullHandler = logging.NullHandler else: # Python 2.6 and older class NullHandler(logging.Handler): def emit(self, record): pass class Debug(object): defaultPrinter = None def __init__(self, *flags, **options): self._flags = flagNone if options.get('printer') is not None: self._printer = options.get('printer') elif self.defaultPrinter is not None: self._printer = self.defaultPrinter else: if 'loggerName' in options: # route our logs to parent logger self._printer = Printer( logger=logging.getLogger(options['loggerName']), handler=NullHandler() ) else: self._printer = Printer() self('running pysnmp version %s' % __version__) for f in flags: inverse = f and f[0] in ('!', '~') if inverse: f = f[1:] try: if inverse: self._flags &= ~flagMap[f] else: self._flags |= flagMap[f] except KeyError: raise error.PySnmpError('bad debug flag %s' % f) self('debug category \'%s\' %s' % (f, inverse and 'disabled' or 'enabled')) def __str__(self): return 'logger %s, flags %x' % (self._printer, self._flags) def __call__(self, msg): self._printer(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 def hexdump(octets): return ' '.join( ['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x) for n, x in zip(range(len(octets)), octs2ints(octets))]) pysnmp-4.4.12/pysnmp/entity/000077500000000000000000000000001354244100700157725ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/entity/__init__.py000066400000000000000000000000731354244100700201030ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/entity/config.py000066400000000000000000001042411354244100700176130ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.compat.octets import null from pysnmp.carrier.asyncore.dgram import udp, udp6, unix 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.rfc7860.auth import hmacsha2 from pysnmp.proto.secmod.eso.priv import des3, aes192, aes256 from pysnmp.proto import rfc1902 from pysnmp.proto import rfc1905 from pysnmp import error from pysnmp import debug # A shortcut to popular constants # Transports snmpUDPDomain = udp.snmpUDPDomain snmpUDP6Domain = udp6.snmpUDP6Domain snmpLocalDomain = unix.snmpLocalDomain # Auth protocol usmHMACMD5AuthProtocol = hmacmd5.HmacMd5.serviceID usmHMACSHAAuthProtocol = hmacsha.HmacSha.serviceID usmHMAC128SHA224AuthProtocol = hmacsha2.HmacSha2.sha224ServiceID usmHMAC192SHA256AuthProtocol = hmacsha2.HmacSha2.sha256ServiceID usmHMAC256SHA384AuthProtocol = hmacsha2.HmacSha2.sha384ServiceID usmHMAC384SHA512AuthProtocol = hmacsha2.HmacSha2.sha512ServiceID usmNoAuthProtocol = noauth.NoAuth.serviceID """No authentication service""" # Privacy protocol usmDESPrivProtocol = des.Des.serviceID usm3DESEDEPrivProtocol = des3.Des3.serviceID usmAesCfb128Protocol = aes.Aes.serviceID usmAesBlumenthalCfb192Protocol = aes192.AesBlumenthal192.serviceID # semi-standard but not widely used usmAesBlumenthalCfb256Protocol = aes256.AesBlumenthal256.serviceID # semi-standard but not widely used usmAesCfb192Protocol = aes192.Aes192.serviceID # non-standard but used by many vendors usmAesCfb256Protocol = aes256.Aes256.serviceID # non-standard but used by many vendors usmNoPrivProtocol = nopriv.NoPriv.serviceID # USM key types (PYSNMP-USM-MIB::pysnmpUsmKeyType) usmKeyTypePassphrase = 0 usmKeyTypeMaster = 1 usmKeyTypeLocalized = 2 # Auth services authServices = {hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), hmacsha2.HmacSha2.sha224ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha224ServiceID), hmacsha2.HmacSha2.sha256ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha256ServiceID), hmacsha2.HmacSha2.sha384ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha384ServiceID), hmacsha2.HmacSha2.sha512ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha512ServiceID), noauth.NoAuth.serviceID: noauth.NoAuth()} # Privacy services privServices = {des.Des.serviceID: des.Des(), des3.Des3.serviceID: des3.Des3(), aes.Aes.serviceID: aes.Aes(), aes192.AesBlumenthal192.serviceID: aes192.AesBlumenthal192(), aes256.AesBlumenthal256.serviceID: aes256.AesBlumenthal256(), aes192.Aes192.serviceID: aes192.Aes192(), # non-standard aes256.Aes256.serviceID: aes256.Aes256(), # non-standard nopriv.NoPriv.serviceID: nopriv.NoPriv()} def __cookV1SystemInfo(snmpEngine, communityIndex): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpCommunityEntry, = mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityEntry') tblIdx = snmpCommunityEntry.getInstIdFromIndices(communityIndex) return snmpCommunityEntry, tblIdx, snmpEngineID def addV1System(snmpEngine, communityIndex, communityName, contextEngineId=None, contextName=None, transportTag=None, securityName=None): (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) if contextEngineId is None: contextEngineId = snmpEngineID.syntax else: contextEngineId = snmpEngineID.syntax.clone(contextEngineId) if contextName is None: contextName = null securityName = securityName is not None and securityName or communityIndex snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (1,) + tblIdx, communityIndex), (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'), (snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo')) ) debug.logger & debug.flagSM and debug.logger( 'addV1System: added new table entry ' 'communityIndex "%s" communityName "%s" securityName "%s" ' 'contextEngineId "%s" contextName "%s" transportTag ' '"%s"' % (communityIndex, communityName, securityName, contextEngineId, contextName, transportTag)) def delV1System(snmpEngine, communityIndex): (snmpCommunityEntry, tblIdx, snmpEngineID) = __cookV1SystemInfo(snmpEngine, communityIndex) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) debug.logger & debug.flagSM and debug.logger( 'delV1System: deleted table entry by communityIndex ' '"%s"' % (communityIndex,)) def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if securityEngineId is None: securityEngineId = snmpEngineID.syntax else: securityEngineId = snmpEngineID.syntax.clone(securityEngineId) usmUserEntry, = mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') tblIdx1 = usmUserEntry.getInstIdFromIndices(securityEngineId, securityName) pysnmpUsmSecretEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) return securityEngineId, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 def addV3User(snmpEngine, userName, authProtocol=usmNoAuthProtocol, authKey=None, privProtocol=usmNoPrivProtocol, privKey=None, securityEngineId=None, securityName=None, authKeyType=usmKeyTypePassphrase, privKeyType=usmKeyTypePassphrase, # deprecated parameter contextEngineId=None): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder if securityName is None: securityName = userName if securityEngineId is None: # backward compatibility securityEngineId = contextEngineId (securityEngineId, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo( snmpEngine, securityName, securityEngineId) # Load augmenting table before creating new row in base one pysnmpUsmKeyEntry, = mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') # Load clone-from (may not be needed) zeroDotZero, = mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (2,) + tblIdx1, userName), (usmUserEntry.name + (3,) + tblIdx1, securityName), (usmUserEntry.name + (4,) + tblIdx1, zeroDotZero.name), (usmUserEntry.name + (5,) + tblIdx1, authProtocol), (usmUserEntry.name + (8,) + tblIdx1, privProtocol), (usmUserEntry.name + (13,) + tblIdx1, 'createAndGo')) ) if authProtocol not in authServices: raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,)) if privProtocol not in privServices: raise error.PySnmpError('Unknown privacy protocol %s' % (privProtocol,)) pysnmpUsmKeyType, = mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmKeyType') authKeyType = pysnmpUsmKeyType.syntax.clone(authKeyType) # Localize authentication key unless given authKey = authKey and rfc1902.OctetString(authKey) masterAuthKey = localAuthKey = authKey if authKeyType < usmKeyTypeMaster: # pass phrase is given masterAuthKey = authServices[authProtocol].hashPassphrase( authKey or null ) if authKeyType < usmKeyTypeLocalized: # pass phrase or master key is given localAuthKey = authServices[authProtocol].localizeKey( masterAuthKey, securityEngineId ) # Localize privacy key unless given privKeyType = pysnmpUsmKeyType.syntax.clone(privKeyType) privKey = privKey and rfc1902.OctetString(privKey) masterPrivKey = localPrivKey = privKey if privKeyType < usmKeyTypeMaster: # pass phrase is given masterPrivKey = privServices[privProtocol].hashPassphrase( authProtocol, privKey or null ) if privKeyType < usmKeyTypeLocalized: # pass phrase or master key is given localPrivKey = privServices[privProtocol].localizeKey( authProtocol, masterPrivKey, securityEngineId ) # Commit only the keys we have snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmKeyEntry.name + (1,) + tblIdx1, localAuthKey),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmKeyEntry.name + (2,) + tblIdx1, localPrivKey),) ) if authKeyType < usmKeyTypeLocalized: snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmKeyEntry.name + (3,) + tblIdx1, masterAuthKey),) ) if privKeyType < usmKeyTypeLocalized: snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmKeyEntry.name + (4,) + tblIdx1, masterPrivKey),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) ) # Commit plain-text pass-phrases if we have them snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo'),) ) if authKeyType < usmKeyTypeMaster: snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (1,) + tblIdx2, userName), (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey)) ) if privKeyType < usmKeyTypeMaster: snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (1,) + tblIdx2, userName), (pysnmpUsmSecretEntry.name + (3,) + tblIdx2, privKey)) ) debug.logger & debug.flagSM and debug.logger( 'addV3User: added new table entries ' 'userName "%s" securityName "%s" authProtocol %s ' 'privProtocol %s localAuthKey "%s" localPrivKey "%s" ' 'masterAuthKey "%s" masterPrivKey "%s" authKey "%s" ' 'privKey "%s" by index securityName "%s" securityEngineId ' '"%s"' % ( userName, securityName, authProtocol, privProtocol, localAuthKey and localAuthKey.prettyPrint(), localPrivKey and localPrivKey.prettyPrint(), masterAuthKey and masterAuthKey.prettyPrint(), masterPrivKey and masterPrivKey.prettyPrint(), authKey and authKey.prettyPrint(), privKey and privKey.prettyPrint(), securityName, securityEngineId.prettyPrint())) def delV3User(snmpEngine, userName, securityEngineId=None, # deprecated parameters follow contextEngineId=None): if securityEngineId is None: # backward compatibility securityEngineId = contextEngineId (securityEngineId, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2) = __cookV3UserInfo(snmpEngine, userName, securityEngineId) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) ) debug.logger & debug.flagSM and debug.logger( 'delV3User: deleted table entries by index ' 'userName "%s" securityEngineId ' '"%s"' % ( userName, securityEngineId.prettyPrint())) # Drop all derived rows varBinds = initialVarBinds = ( (usmUserEntry.name + (1,), None), # usmUserEngineID (usmUserEntry.name + (2,), None), # usmUserName (usmUserEntry.name + (4,), None) # usmUserCloneFrom ) while varBinds: varBinds = snmpEngine.msgAndPduDsp.mibInstrumController.readNextVars( varBinds ) if varBinds[0][1].isSameTypeWith(rfc1905.endOfMibView): break if varBinds[0][0][:len(initialVarBinds[0][0])] != initialVarBinds[0][0]: break elif varBinds[2][1] == tblIdx1: # cloned from this entry delV3User(snmpEngine, varBinds[1][1], varBinds[0][1]) varBinds = initialVarBinds def __cookTargetParamsInfo(snmpEngine, name): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpTargetParamsEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) return snmpTargetParamsEntry, tblIdx # mpModel: 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 def addTargetParams(snmpEngine, name, securityName, securityLevel, mpModel=3): if mpModel == 0: securityModel = 1 elif mpModel in (1, 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 + (1,) + tblIdx, name), (snmpTargetParamsEntry.name + (2,) + tblIdx, mpModel), (snmpTargetParamsEntry.name + (3,) + tblIdx, securityModel), (snmpTargetParamsEntry.name + (4,) + tblIdx, securityName), (snmpTargetParamsEntry.name + (5,) + tblIdx, securityLevel), (snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo')) ) def delTargetParams(snmpEngine, name): snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) ) def __cookTargetAddrInfo(snmpEngine, addrName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpTargetAddrEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') snmpSourceAddrEntry, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrEntry') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) return snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx def addTargetAddr(snmpEngine, addrName, transportDomain, transportAddress, params, timeout=None, retryCount=None, tagList=null, sourceAddress=None): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain: SnmpUDPAddress, = mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') transportAddress = SnmpUDPAddress(transportAddress) if sourceAddress is None: sourceAddress = ('0.0.0.0', 0) sourceAddress = SnmpUDPAddress(sourceAddress) elif transportDomain[:len(snmpUDP6Domain)] == snmpUDP6Domain: TransportAddressIPv6, = mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') transportAddress = TransportAddressIPv6(transportAddress) if sourceAddress is None: sourceAddress = ('::', 0) sourceAddress = TransportAddressIPv6(sourceAddress) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((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), (snmpTargetAddrEntry.name + (6,) + tblIdx, tagList), (snmpTargetAddrEntry.name + (7,) + tblIdx, params), (snmpSourceAddrEntry.name + (1,) + tblIdx, sourceAddress), (snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo')) ) def delTargetAddr(snmpEngine, addrName): (snmpTargetAddrEntry, snmpSourceAddrEntry, tblIdx) = __cookTargetAddrInfo(snmpEngine, addrName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) ) def addTransport(snmpEngine, transportDomain, transport): if snmpEngine.transportDispatcher: if not transport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): raise error.PySnmpError( 'Transport %r is not compatible with dispatcher %r' % (transport, snmpEngine.transportDispatcher)) else: snmpEngine.registerTransportDispatcher( transport.protoTransportDispatcher() ) # here we note that we have created transportDispatcher automatically snmpEngine.setUserContext(automaticTransportDispatcher=0) snmpEngine.transportDispatcher.registerTransport(transportDomain, transport) automaticTransportDispatcher = snmpEngine.getUserContext( 'automaticTransportDispatcher' ) if automaticTransportDispatcher is not None: snmpEngine.setUserContext( automaticTransportDispatcher=automaticTransportDispatcher + 1 ) def getTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return try: return snmpEngine.transportDispatcher.getTransport(transportDomain) except error.PySnmpError: return def delTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return transport = getTransport(snmpEngine, transportDomain) snmpEngine.transportDispatcher.unregisterTransport(transportDomain) # automatically shutdown automatically created transportDispatcher automaticTransportDispatcher = snmpEngine.getUserContext( 'automaticTransportDispatcher' ) if automaticTransportDispatcher is not None: automaticTransportDispatcher -= 1 snmpEngine.setUserContext( automaticTransportDispatcher=automaticTransportDispatcher ) if not automaticTransportDispatcher: snmpEngine.transportDispatcher.closeDispatcher() snmpEngine.unregisterTransportDispatcher() snmpEngine.delUserContext(automaticTransportDispatcher) return transport addSocketTransport = addTransport delSocketTransport = delTransport # VACM shortcuts def __cookVacmContextInfo(snmpEngine, contextName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder vacmContextEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) return vacmContextEntry, tblIdx def addContext(snmpEngine, contextName): vacmContextEntry, tblIdx = __cookVacmContextInfo(snmpEngine, contextName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmContextEntry.name + (2,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmContextEntry.name + (1,) + tblIdx, contextName), (vacmContextEntry.name + (2,) + tblIdx, 'createAndGo')) ) def delContext(snmpEngine, contextName): vacmContextEntry, tblIdx = __cookVacmContextInfo(snmpEngine, contextName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmContextEntry.name + (2,) + tblIdx, 'destroy'),) ) def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder vacmSecurityToGroupEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry') tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices(securityModel, securityName) return vacmSecurityToGroupEntry, tblIdx def addVacmGroup(snmpEngine, groupName, securityModel, securityName): (vacmSecurityToGroupEntry, tblIdx) = __cookVacmGroupInfo(snmpEngine, securityModel, securityName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), (vacmSecurityToGroupEntry.name + (3,) + tblIdx, groupName), (vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo')) ) 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): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder vacmAccessEntry, = mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry') tblIdx = vacmAccessEntry.getInstIdFromIndices(groupName, contextName, securityModel, securityLevel) return vacmAccessEntry, tblIdx def addVacmAccess(snmpEngine, groupName, contextPrefix, securityModel, securityLevel, contextMatch, readView, writeView, notifyView): vacmAccessEntry, tblIdx = __cookVacmAccessInfo( snmpEngine, groupName, contextPrefix, securityModel, securityLevel) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (1,) + tblIdx, contextPrefix), (vacmAccessEntry.name + (2,) + tblIdx, securityModel), (vacmAccessEntry.name + (3,) + tblIdx, securityLevel), (vacmAccessEntry.name + (4,) + tblIdx, contextMatch), (vacmAccessEntry.name + (5,) + tblIdx, readView), (vacmAccessEntry.name + (6,) + tblIdx, writeView), (vacmAccessEntry.name + (7,) + tblIdx, notifyView), (vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo')) ) def delVacmAccess(snmpEngine, groupName, contextPrefix, securityModel, securityLevel): vacmAccessEntry, tblIdx = __cookVacmAccessInfo( snmpEngine, groupName, contextPrefix, securityModel, securityLevel) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) ) def __cookVacmViewInfo(snmpEngine, viewName, subTree): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder vacmViewTreeFamilyEntry, = mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' ) tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName, subTree) return vacmViewTreeFamilyEntry, tblIdx def addVacmView(snmpEngine, viewName, viewType, subTree, subTreeMask): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( snmpEngine, viewName, subTree) # Allow bitmask specification in form of an OID if rfc1902.OctetString('.').asOctets() in rfc1902.OctetString(subTreeMask): subTreeMask = rfc1902.ObjectIdentifier(subTreeMask) if isinstance(subTreeMask, rfc1902.ObjectIdentifier): subTreeMask = tuple(subTreeMask) if len(subTreeMask) < len(subTree): subTreeMask += (1,) * (len(subTree) - len(subTreeMask)) subTreeMask = rfc1902.OctetString.fromBinaryString( ''.join(str(x) for x in subTreeMask)) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, subTreeMask), (vacmViewTreeFamilyEntry.name + (4,) + tblIdx, viewType), (vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo')) ) 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): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder groupName = 'v-%s-%d' % (hash(securityName), securityModel) SnmpSecurityLevel, = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') securityLevel = SnmpSecurityLevel(securityLevel) return (groupName, securityLevel, 'r' + groupName, 'w' + groupName, 'n' + groupName) def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): (groupName, securityLevel, readView, writeView, notifyView) = __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel) addContext(snmpEngine, contextName) addVacmGroup(snmpEngine, groupName, securityModel, securityName) addVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel, 'exact', 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=(), contextName=null): (groupName, securityLevel, readView, writeView, notifyView) = __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel) delContext(snmpEngine, contextName) delVacmGroup(snmpEngine, securityModel, securityName) delVacmAccess(snmpEngine, groupName, contextName, 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, contextName=null): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=contextName) def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=null): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=contextName) def addRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=null): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, subTree, contextName=contextName) def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=null): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, subTree, subTree, contextName=contextName) def addTrapUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=null): addVacmUser(snmpEngine, securityModel, securityName, securityLevel, (), (), subTree, contextName=contextName) def delTrapUser(snmpEngine, securityModel, securityName, securityLevel, subTree, contextName=null): delVacmUser(snmpEngine, securityModel, securityName, securityLevel, (), (), subTree, contextName=contextName) # Notification target setup def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, filterSubtree=None): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') tblIdx1 = snmpNotifyEntry.getInstIdFromIndices(notificationName) snmpNotifyFilterProfileEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices(paramsName) profileName = '%s-filter' % hash(notificationName) if filterSubtree: snmpNotifyFilterEntry, = 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 + (2,) + tblIdx1, transportTag), (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType), (snmpNotifyEntry.name + (5,) + tblIdx1, 'createAndGo')) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName), (snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'createAndGo')) ) if not snmpNotifyFilterEntry: return snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), (snmpNotifyFilterEntry.name + (3,) + tblIdx3, filterType), (snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo')) ) 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), "") pysnmp-4.4.12/pysnmp/entity/engine.py000066400000000000000000000200011354244100700176020ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import os import shutil import sys import tempfile from pyasn1.compat.octets import str2octs 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.entity import observer from pysnmp import debug from pysnmp import error __all__ = ['SnmpEngine'] class SnmpEngine(object): """Creates SNMP engine object. SNMP engine object is central in SNMP v3 architecture. It is an umbrella object that coordinates interactions between all parts of SNMP v3 system. See :RFC:`3412#section-2.1` (where it is termed *The Dispatcher*). With PySNMP design, `SnmpEngine` is the only stateful object, all SNMP v3 operations require an instance of SNMP engine. Users do not normally request services directly from `SnmpEngine`, but pass it around to other PySNMP interfaces. It is possible to run multiple instances of `SnmpEngine` in the application. In a multithreaded environment, each thread that works with SNMP must have its own `SnmpEngine` instance. Parameters ---------- snmpEngineID : :py:class:`~pysnmp.proto.rfc1902.OctetString` Unique and unambiguous identifier of an SNMP engine. If not given, `snmpEngineID` is autogenerated and stored on the filesystem. See :RFC:`3411#section-3.1.1` for details. Examples -------- >>> SnmpEngine() SnmpEngine(snmpEngineID=OctetString(hexValue='0x80004fb80567726f6d6d69742')) >>> """ def __init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None): self.cache = {} self.observer = observer.MetaObserver() 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.Vacm.accessModelID: void.Vacm(), rfc3415.Vacm.accessModelID: rfc3415.Vacm() } 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 += 1 origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if snmpEngineID is None: self.snmpEngineID = origSnmpEngineID.syntax else: origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) self.snmpEngineID = origSnmpEngineID.syntax debug.logger & debug.flagApp and debug.logger( 'SnmpEngine: using custom SNMP Engine ID: %s' % self.snmpEngineID.prettyPrint()) # Attempt to make some of snmp Engine settings persistent. # This should probably be generalized as a non-volatile MIB store. persistentPath = os.path.join(tempfile.gettempdir(), '__pysnmp', self.snmpEngineID.prettyPrint()) debug.logger & debug.flagApp and debug.logger('SnmpEngine: using persistent directory: %s' % persistentPath) if not os.path.exists(persistentPath): try: os.makedirs(persistentPath) except OSError: return f = os.path.join(persistentPath, 'boots') try: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(open(f).read()) except Exception: pass try: snmpEngineBoots.syntax += 1 except Exception: snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(1) try: fd, fn = tempfile.mkstemp(dir=persistentPath) os.write(fd, str2octs(snmpEngineBoots.syntax.prettyPrint())) os.close(fd) shutil.move(fn, f) except Exception: debug.logger & debug.flagApp and debug.logger( 'SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) else: debug.logger & debug.flagApp and debug.logger( 'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) def __repr__(self): return '%s(snmpEngineID=%r)' % (self.__class__.__name__, self.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, recvId=None): if self.transportDispatcher is not None and \ self.transportDispatcher is not transportDispatcher: raise error.PySnmpError( 'Transport dispatcher already registered' ) transportDispatcher.registerRecvCbFun( self.__receiveMessageCbFun, recvId ) if self.transportDispatcher is None: transportDispatcher.registerTimerCbFun( self.__receiveTimerTickCbFun ) self.transportDispatcher = transportDispatcher def unregisterTransportDispatcher(self, recvId=None): if self.transportDispatcher is None: raise error.PySnmpError( 'Transport dispatcher not registered' ) self.transportDispatcher.unregisterRecvCbFun(recvId) self.transportDispatcher.unregisterTimerCbFun() self.transportDispatcher = None def getMibBuilder(self): return self.msgAndPduDsp.mibInstrumController.mibBuilder # User app may attach opaque objects to SNMP Engine def setUserContext(self, **kwargs): self.cache.update( dict([('__%s' % k, kwargs[k]) for k in kwargs]) ) def getUserContext(self, arg): return self.cache.get('__%s' % arg) def delUserContext(self, arg): try: del self.cache['__%s' % arg] except KeyError: pass pysnmp-4.4.12/pysnmp/entity/observer.py000066400000000000000000000050061354244100700201740ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp import error class MetaObserver(object): """This is a simple facility for exposing internal SNMP Engine working details to pysnmp applications. These details are basically local scope variables at a fixed point of execution. Two modes of operations are offered: 1. Consumer: app can request an execution point context by execution point ID. 2. Provider: app can register its callback function (and context) to be invoked once execution reaches specified point. All local scope variables will be passed to the callback as in #1. It's important to realize that execution context is only guaranteed to exist to functions that are at the same or deeper level of invocation relative to execution point specified. """ def __init__(self): self.__observers = {} self.__contexts = {} self.__execpoints = {} def registerObserver(self, cbFun, *execpoints, **kwargs): if cbFun in self.__contexts: raise error.PySnmpError('duplicate observer %s' % cbFun) else: self.__contexts[cbFun] = kwargs.get('cbCtx') for execpoint in execpoints: if execpoint not in self.__observers: self.__observers[execpoint] = [] self.__observers[execpoint].append(cbFun) def unregisterObserver(self, cbFun=None): if cbFun is None: self.__observers.clear() self.__contexts.clear() else: for execpoint in dict(self.__observers): if cbFun in self.__observers[execpoint]: self.__observers[execpoint].remove(cbFun) if not self.__observers[execpoint]: del self.__observers[execpoint] def storeExecutionContext(self, snmpEngine, execpoint, variables): self.__execpoints[execpoint] = variables if execpoint in self.__observers: for cbFun in self.__observers[execpoint]: cbFun(snmpEngine, execpoint, variables, self.__contexts[cbFun]) def clearExecutionContext(self, snmpEngine, *execpoints): if execpoints: for execpoint in execpoints: del self.__execpoints[execpoint] else: self.__execpoints.clear() def getExecutionContext(self, execpoint): return self.__execpoints[execpoint] pysnmp-4.4.12/pysnmp/entity/rfc3413/000077500000000000000000000000001354244100700170575ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/entity/rfc3413/__init__.py000066400000000000000000000000731354244100700211700ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/entity/rfc3413/cmdgen.py000066400000000000000000000442421354244100700206740ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.entity.rfc3413 import config from pysnmp.proto import rfc1905, errind from pysnmp.proto.api import v2c from pysnmp.proto.proxy import rfc2576 from pysnmp import error, nextid, debug from pysnmp.proto.error import StatusInformation from pyasn1.type import univ getNextHandle = nextid.Integer(0x7fffffff) __null = univ.Null('') def getNextVarBinds(varBinds, origVarBinds=None): errorIndication = None idx = nonNulls = len(varBinds) rspVarBinds = [] while idx: idx -= 1 if varBinds[idx][1].tagSet in (rfc1905.NoSuchObject.tagSet, rfc1905.NoSuchInstance.tagSet, rfc1905.EndOfMibView.tagSet): nonNulls -= 1 elif origVarBinds is not None: if v2c.ObjectIdentifier(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 CommandGenerator(object): _null = univ.Null('') def __init__(self, **options): self.__options = options self.__pendingReqs = {} def processResponsePdu(self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, sendPduHandle, cbCtx): origSendRequestHandle, cbFun, cbCtx = cbCtx # 3.1.1 if sendPduHandle not in self.__pendingReqs: raise error.PySnmpError('Missing sendPduHandle %s' % sendPduHandle) (origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPduVersion, origPdu, origTimeout, origRetryCount, origRetries, origDiscoveryRetries) = self.__pendingReqs.pop(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)) errorIndication = statusInformation['errorIndication'] if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID): origDiscoveryRetries += 1 origRetries = 0 else: origDiscoveryRetries = 0 origRetries += 1 if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get('discoveryRetries', 4): debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) cbFun(snmpEngine, origSendRequestHandle, errorIndication, None, cbCtx) return # User-side API assumes SMIv2 if origMessageProcessingModel == 0: reqPDU = rfc2576.v2ToV1(origPdu) pduVersion = 0 else: reqPDU = origPdu pduVersion = 1 try: sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, pduVersion, reqPDU, True, origTimeout, self.processResponsePdu, (origSendRequestHandle, cbFun, cbCtx)) snmpEngine.transportDispatcher.jobStarted(id(self)) self.__pendingReqs[sendPduHandle] = ( origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPduVersion, origPdu, origTimeout, origRetryCount, origRetries, origDiscoveryRetries ) return except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % ( sendPduHandle, statusInformation)) cbFun(snmpEngine, origSendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return if (origMessageProcessingModel != messageProcessingModel or origSecurityModel != securityModel or origSecurityName != origSecurityName or origContextEngineId and origContextEngineId != contextEngineId or origContextName and origContextName != contextName or origPduVersion != pduVersion): debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) return # User-side API assumes SMIv2 if messageProcessingModel == 0: PDU = rfc2576.v1ToV2(PDU, origPdu) # 3.1.2 if v2c.apiPDU.getRequestID(PDU) != v2c.apiPDU.getRequestID(origPdu): debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendPduHandle %s, request-id/response-id mismatch' % sendPduHandle) cbFun(snmpEngine, origSendRequestHandle, 'badResponse', None, cbCtx) return cbFun(snmpEngine, origSendRequestHandle, None, PDU, cbCtx) def sendPdu(self, snmpEngine, targetName, contextEngineId, contextName, PDU, cbFun, cbCtx): (transportDomain, transportAddress, timeout, retryCount, messageProcessingModel, securityModel, securityName, securityLevel) = config.getTargetInfo(snmpEngine, targetName) # Convert timeout in seconds into timeout in timer ticks timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() SnmpEngineID, SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') # Cast possible strings into bytes if contextEngineId: contextEngineId = SnmpEngineID(contextEngineId) contextName = SnmpAdminString(contextName) origPDU = PDU # User-side API assumes SMIv2 if messageProcessingModel == 0: PDU = rfc2576.v2ToV1(PDU) pduVersion = 0 else: pduVersion = 1 sendRequestHandle = getNextHandle() # 3.1 sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, True, timeoutInTicks, self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) snmpEngine.transportDispatcher.jobStarted(id(self)) self.__pendingReqs[sendPduHandle] = ( transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, origPDU, timeoutInTicks, retryCount, 0, 0 ) debug.logger & debug.flagApp and debug.logger( 'sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry 0 of %d' % ( sendPduHandle, timeout, timeoutInTicks, retryCount)) return sendRequestHandle # backward compatibility stub CommandGeneratorBase = CommandGenerator class GetCommandGenerator(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): cbFun, cbCtx = cbCtx cbFun(snmpEngine, sendRequestHandle, errorIndication, PDU and v2c.apiPDU.getErrorStatus(PDU) or 0, PDU and v2c.apiPDU.getErrorIndex(PDU, muteErrors=True) or 0, PDU and v2c.apiPDU.getVarBinds(PDU) or (), cbCtx) def sendVarBinds(self, snmpEngine, targetName, contextEngineId, contextName, varBinds, cbFun, cbCtx=None): reqPDU = v2c.GetRequestPDU() v2c.apiPDU.setDefaults(reqPDU) v2c.apiPDU.setVarBinds(reqPDU, varBinds) return self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, self.processResponseVarBinds, (cbFun, cbCtx)) class SetCommandGenerator(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): cbFun, cbCtx = cbCtx cbFun(snmpEngine, sendRequestHandle, errorIndication, PDU and v2c.apiPDU.getErrorStatus(PDU) or 0, PDU and v2c.apiPDU.getErrorIndex(PDU, muteErrors=True) or 0, PDU and v2c.apiPDU.getVarBinds(PDU) or (), cbCtx) def sendVarBinds(self, snmpEngine, targetName, contextEngineId, contextName, varBinds, cbFun, cbCtx=None): reqPDU = v2c.SetRequestPDU() v2c.apiPDU.setDefaults(reqPDU) v2c.apiPDU.setVarBinds(reqPDU, varBinds) return self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, self.processResponseVarBinds, (cbFun, cbCtx)) class NextCommandGeneratorSingleRun(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx = cbCtx cbFun(snmpEngine, sendRequestHandle, errorIndication, PDU and v2c.apiPDU.getErrorStatus(PDU) or 0, PDU and v2c.apiPDU.getErrorIndex(PDU, muteErrors=True) or 0, PDU and v2c.apiPDU.getVarBinds(PDU) or (), cbCtx) def sendVarBinds(self, snmpEngine, targetName, contextEngineId, contextName, varBinds, cbFun, cbCtx=None): reqPDU = v2c.GetNextRequestPDU() v2c.apiPDU.setDefaults(reqPDU) v2c.apiPDU.setVarBinds(reqPDU, varBinds) return self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, self.processResponseVarBinds, (targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) class NextCommandGenerator(NextCommandGeneratorSingleRun): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx = cbCtx if errorIndication: cbFun(snmpEngine, sendRequestHandle, errorIndication, 0, 0, (), cbCtx) return varBindTable = v2c.apiPDU.getVarBindTable(reqPDU, PDU) if v2c.apiPDU.getErrorStatus(PDU): errorIndication, varBinds = None, () elif not varBindTable: errorIndication, varBinds = errind.emptyResponse, () else: errorIndication, varBinds = getNextVarBinds( varBindTable[-1], v2c.apiPDU.getVarBinds(reqPDU) ) if not cbFun(snmpEngine, sendRequestHandle, errorIndication, v2c.apiPDU.getErrorStatus(PDU), v2c.apiPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): debug.logger & debug.flagApp and debug.logger( 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) return # app says enough if not varBinds: return # no more objects available v2c.apiPDU.setRequestID(reqPDU, v2c.getNextRequestID()) v2c.apiPDU.setVarBinds(reqPDU, varBinds) try: self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, self.processResponseVarBinds, (targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) class BulkCommandGeneratorSingleRun(CommandGenerator): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): (targetName, nonRepeaters, maxRepetitions, contextEngineId, contextName, reqPDU, cbFun, cbCtx) = cbCtx cbFun(snmpEngine, sendRequestHandle, errorIndication, PDU and v2c.apiPDU.getErrorStatus(PDU) or 0, PDU and v2c.apiPDU.getErrorIndex(PDU, muteErrors=True) or 0, PDU and v2c.apiPDU.getVarBinds(PDU) or (), cbCtx) def sendVarBinds(self, snmpEngine, targetName, contextEngineId, contextName, nonRepeaters, maxRepetitions, varBinds, cbFun, cbCtx=None): reqPDU = v2c.GetBulkRequestPDU() v2c.apiBulkPDU.setDefaults(reqPDU) v2c.apiBulkPDU.setNonRepeaters(reqPDU, nonRepeaters) v2c.apiBulkPDU.setMaxRepetitions(reqPDU, maxRepetitions) v2c.apiBulkPDU.setVarBinds(reqPDU, varBinds) return self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, self.processResponseVarBinds, (targetName, nonRepeaters, maxRepetitions, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) class BulkCommandGenerator(BulkCommandGeneratorSingleRun): def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): (targetName, nonRepeaters, maxRepetitions, contextEngineId, contextName, reqPDU, cbFun, cbCtx) = cbCtx if errorIndication: cbFun(snmpEngine, sendRequestHandle, errorIndication, 0, 0, (), cbCtx) return varBindTable = v2c.apiBulkPDU.getVarBindTable(reqPDU, PDU) if v2c.apiBulkPDU.getErrorStatus(PDU): errorIndication, varBinds = None, () elif not varBindTable: errorIndication, varBinds = errind.emptyResponse, () else: errorIndication, varBinds = getNextVarBinds( varBindTable[-1], v2c.apiPDU.getVarBinds(reqPDU) ) nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(reqPDU) if nonRepeaters: varBinds = v2c.apiBulkPDU.getVarBinds(reqPDU)[:int(nonRepeaters)] + varBinds[int(nonRepeaters):] if not cbFun(snmpEngine, sendRequestHandle, errorIndication, v2c.apiBulkPDU.getErrorStatus(PDU), v2c.apiBulkPDU.getErrorIndex(PDU, muteErrors=True), varBindTable, cbCtx): debug.logger & debug.flagApp and debug.logger( 'processResponseVarBinds: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) return # app says enough if not varBinds: return # no more objects available v2c.apiBulkPDU.setRequestID(reqPDU, v2c.getNextRequestID()) v2c.apiBulkPDU.setVarBinds(reqPDU, varBinds) try: self.sendPdu(snmpEngine, targetName, contextEngineId, contextName, reqPDU, self.processResponseVarBinds, (targetName, nonRepeaters, maxRepetitions, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger( 'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % ( sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) # # Obsolete, compatibility interfaces. # def __sendReqCbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbFun, cbCtx = cbCtx return cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx) def _sendReq(self, snmpEngine, targetName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName=''): return self.sendVarBinds(snmpEngine, targetName, contextEngineId, contextName, varBinds, __sendReqCbFun, (cbFun, cbCtx)) def _sendBulkReq(self, snmpEngine, targetName, nonRepeaters, maxRepetitions, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName=''): return self.sendVarBinds(snmpEngine, targetName, contextEngineId, contextName, nonRepeaters, maxRepetitions, varBinds, __sendReqCbFun, (cbFun, cbCtx)) # install compatibility wrappers GetCommandGenerator.sendReq = _sendReq SetCommandGenerator.sendReq = _sendReq NextCommandGenerator.sendReq = _sendReq NextCommandGeneratorSingleRun.sendReq = _sendReq BulkCommandGenerator.sendReq = _sendBulkReq BulkCommandGeneratorSingleRun.sendReq = _sendBulkReq pysnmp-4.4.12/pysnmp/entity/rfc3413/cmdrsp.py000066400000000000000000000352351354244100700207310ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.proto import 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(object): 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 self.__pendingReqs = {} def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): pass def close(self, snmpEngine): snmpEngine.msgAndPduDsp.unregisterContextEngineId( self.snmpContext.contextEngineId, self.pduTypes ) self.snmpContext = self.__pendingReqs = None def sendVarBinds(self, snmpEngine, stateReference, errorStatus, errorIndex, varBinds): (messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, origPdu, maxSizeResponseScopedPDU, statusInformation) = self.__pendingReqs[stateReference] v2c.apiPDU.setErrorStatus(PDU, errorStatus) v2c.apiPDU.setErrorIndex(PDU, errorIndex) v2c.apiPDU.setVarBinds(PDU, varBinds) debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % ( stateReference, errorStatus, errorIndex, varBinds) ) self.sendPdu(snmpEngine, stateReference, PDU) # backward compatibility sendRsp = sendVarBinds def sendPdu(self, snmpEngine, stateReference, PDU): (messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, _, origPdu, maxSizeResponseScopedPDU, statusInformation) = self.__pendingReqs[stateReference] # 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( 'sendPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax += 1 _getRequestType = rfc1905.GetRequestPDU.tagSet _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 ) # 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, snmpEngine)) # SNMPv2 SMI exceptions except pysnmp.smi.error.GenError: errorIndication = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger( 'processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) if 'oid' in errorIndication: # Request REPORT generation statusInformation['oid'] = errorIndication['oid'] statusInformation['val'] = errorIndication['val'] # Handle PDU-level SMI errors except pysnmp.smi.error.TooBigError: errorStatus, errorIndex = 'tooBig', 0 # rfc1905: 4.2.1.3 varBinds = [] # this should never bubble up, SNMP exception objects should be passed as values except pysnmp.smi.error.NoSuchNameError: errorStatus, errorIndex = 'noSuchName', sys.exc_info()[1]['idx'] + 1 except pysnmp.smi.error.BadValueError: errorStatus, errorIndex = 'badValue', sys.exc_info()[1]['idx'] + 1 except pysnmp.smi.error.ReadOnlyError: errorStatus, errorIndex = 'readOnly', sys.exc_info()[1]['idx'] + 1 except pysnmp.smi.error.GenError: errorStatus, errorIndex = 'genErr', sys.exc_info()[1]['idx'] + 1 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.WrongLengthError: errorStatus, errorIndex = 'wrongLength', sys.exc_info()[1]['idx'] + 1 except pysnmp.smi.error.WrongEncodingError: errorStatus, errorIndex = 'wrongEncoding', 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 = 'commitFailed', sys.exc_info()[1]['idx'] + 1 except pysnmp.smi.error.UndoFailedError: errorStatus, errorIndex = 'undoFailed', 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 except pysnmp.error.PySnmpError: self.releaseStateInformation(stateReference) return else: # successful request processor must release state info return self.sendVarBinds(snmpEngine, stateReference, errorStatus, errorIndex, varBinds) self.releaseStateInformation(stateReference) def __verifyAccess(self, name, syntax, idx, viewType, acCtx): snmpEngine = acCtx execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request') (securityModel, securityName, securityLevel, contextName, pduType) = (execCtx['securityModel'], execCtx['securityName'], execCtx['securityLevel'], execCtx['contextName'], execCtx['pdu'].getTagSet()) 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 += 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.sendVarBinds(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 True: rspVarBinds = mgmtFun(varBinds, (acFun, acCtx)) try: self.sendVarBinds(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 -= 1 if len(rspVarBinds): self.sendVarBinds(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.sendVarBinds(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 pysnmp-4.4.12/pysnmp/entity/rfc3413/config.py000066400000000000000000000237411354244100700207050ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.smi.error import SmiError, NoSuchInstanceError from pysnmp.entity import config def getTargetAddr(snmpEngine, snmpTargetAddrName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpTargetAddrEntry, = mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetAddrEntry' ) cache = snmpEngine.getUserContext('getTargetAddr') if cache is None: cache = {'id': -1} snmpEngine.setUserContext(getTargetAddr=cache) if cache['id'] != snmpTargetAddrEntry.branchVersionId: cache['nameToTargetMap'] = {} nameToTargetMap = cache['nameToTargetMap'] if snmpTargetAddrName not in nameToTargetMap: (snmpTargetAddrTDomain, snmpTargetAddrTAddress, snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetAddrParams) = mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetAddrTDomain', 'snmpTargetAddrTAddress', 'snmpTargetAddrTimeout', 'snmpTargetAddrRetryCount', 'snmpTargetAddrParams' ) snmpSourceAddrTAddress, = mibBuilder.importSymbols('PYSNMP-SOURCE-MIB', 'snmpSourceAddrTAddress') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(snmpTargetAddrName) try: snmpTargetAddrTDomain = snmpTargetAddrTDomain.getNode( snmpTargetAddrTDomain.name + tblIdx ).syntax snmpTargetAddrTAddress = snmpTargetAddrTAddress.getNode( snmpTargetAddrTAddress.name + tblIdx ).syntax snmpTargetAddrTimeout = snmpTargetAddrTimeout.getNode( snmpTargetAddrTimeout.name + tblIdx ).syntax snmpTargetAddrRetryCount = snmpTargetAddrRetryCount.getNode( snmpTargetAddrRetryCount.name + tblIdx ).syntax snmpTargetAddrParams = snmpTargetAddrParams.getNode( snmpTargetAddrParams.name + tblIdx ).syntax snmpSourceAddrTAddress = snmpSourceAddrTAddress.getNode( snmpSourceAddrTAddress.name + tblIdx ).syntax except NoSuchInstanceError: raise SmiError('Target %s not configured to LCD' % snmpTargetAddrName) transport = snmpEngine.transportDispatcher.getTransport(snmpTargetAddrTDomain) if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain: SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') snmpTargetAddrTAddress = transport.addressType( SnmpUDPAddress(snmpTargetAddrTAddress) ).setLocalAddress(SnmpUDPAddress(snmpSourceAddrTAddress)) elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain: TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') snmpTargetAddrTAddress = transport.addressType( TransportAddressIPv6(snmpTargetAddrTAddress) ).setLocalAddress(TransportAddressIPv6(snmpSourceAddrTAddress)) elif snmpTargetAddrTDomain[:len(config.snmpLocalDomain)] == config.snmpLocalDomain: snmpTargetAddrTAddress = transport.addressType( snmpTargetAddrTAddress ) nameToTargetMap[snmpTargetAddrName] = ( snmpTargetAddrTDomain, snmpTargetAddrTAddress, snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetAddrParams ) cache['id'] = snmpTargetAddrEntry.branchVersionId return nameToTargetMap[snmpTargetAddrName] def getTargetParams(snmpEngine, paramsName): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpTargetParamsEntry, = mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetParamsEntry' ) cache = snmpEngine.getUserContext('getTargetParams') if cache is None: cache = {'id': -1} snmpEngine.setUserContext(getTargetParams=cache) if cache['id'] != snmpTargetParamsEntry.branchVersionId: cache['nameToParamsMap'] = {} nameToParamsMap = cache['nameToParamsMap'] if paramsName not in nameToParamsMap: (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) = mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetParamsMPModel', 'snmpTargetParamsSecurityModel', 'snmpTargetParamsSecurityName', 'snmpTargetParamsSecurityLevel' ) tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(paramsName) try: snmpTargetParamsMPModel = snmpTargetParamsMPModel.getNode( snmpTargetParamsMPModel.name + tblIdx ).syntax snmpTargetParamsSecurityModel = snmpTargetParamsSecurityModel.getNode( snmpTargetParamsSecurityModel.name + tblIdx ).syntax snmpTargetParamsSecurityName = snmpTargetParamsSecurityName.getNode( snmpTargetParamsSecurityName.name + tblIdx ).syntax snmpTargetParamsSecurityLevel = snmpTargetParamsSecurityLevel.getNode( snmpTargetParamsSecurityLevel.name + tblIdx ).syntax except NoSuchInstanceError: raise SmiError('Parameters %s not configured at LCD' % paramsName) nameToParamsMap[paramsName] = (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) cache['id'] = snmpTargetParamsEntry.branchVersionId return nameToParamsMap[paramsName] def getTargetInfo(snmpEngine, snmpTargetAddrName): # Transport endpoint (snmpTargetAddrTDomain, snmpTargetAddrTAddress, snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetAddrParams) = getTargetAddr(snmpEngine, snmpTargetAddrName) (snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) = getTargetParams(snmpEngine, snmpTargetAddrParams) return (snmpTargetAddrTDomain, snmpTargetAddrTAddress, snmpTargetAddrTimeout, snmpTargetAddrRetryCount, snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel) def getNotificationInfo(snmpEngine, notificationTarget): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpNotifyEntry, = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') cache = snmpEngine.getUserContext('getNotificationInfo') if cache is None: cache = {'id': -1} snmpEngine.setUserContext(getNotificationInfo=cache) if cache['id'] != snmpNotifyEntry.branchVersionId: cache['targetToNotifyMap'] = {} targetToNotifyMap = cache['targetToNotifyMap'] if notificationTarget not in targetToNotifyMap: (snmpNotifyTag, snmpNotifyType) = mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyTag', 'snmpNotifyType') tblIdx = snmpNotifyEntry.getInstIdFromIndices(notificationTarget) try: snmpNotifyTag = snmpNotifyTag.getNode( snmpNotifyTag.name + tblIdx ).syntax snmpNotifyType = snmpNotifyType.getNode( snmpNotifyType.name + tblIdx ).syntax except NoSuchInstanceError: raise SmiError('Target %s not configured at LCD' % notificationTarget) targetToNotifyMap[notificationTarget] = ( snmpNotifyTag, snmpNotifyType ) cache['id'] = snmpNotifyEntry.branchVersionId return targetToNotifyMap[notificationTarget] def getTargetNames(snmpEngine, tag): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpTargetAddrEntry, = mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') cache = snmpEngine.getUserContext('getTargetNames') if cache is None: cache = {'id': -1} snmpEngine.setUserContext(getTargetNames=cache) if cache['id'] == snmpTargetAddrEntry.branchVersionId: tagToTargetsMap = cache['tagToTargetsMap'] else: cache['tagToTargetsMap'] = {} tagToTargetsMap = cache['tagToTargetsMap'] (SnmpTagValue, snmpTargetAddrName, snmpTargetAddrTagList) = mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrName', 'snmpTargetAddrTagList' ) mibNode = snmpTargetAddrTagList while True: try: mibNode = snmpTargetAddrTagList.getNextNode(mibNode.name) except NoSuchInstanceError: break idx = mibNode.name[len(snmpTargetAddrTagList.name):] _snmpTargetAddrName = snmpTargetAddrName.getNode(snmpTargetAddrName.name + idx).syntax for _tag in mibNode.syntax.asOctets().split(): _tag = SnmpTagValue(_tag) if _tag not in tagToTargetsMap: tagToTargetsMap[_tag] = [] tagToTargetsMap[_tag].append(_snmpTargetAddrName) cache['id'] = snmpTargetAddrEntry.branchVersionId if tag not in tagToTargetsMap: raise SmiError('Transport tag %s not configured at LCD' % tag) return tagToTargetsMap[tag] # convert cmdrsp/cmdgen into this api pysnmp-4.4.12/pysnmp/entity/rfc3413/context.py000066400000000000000000000051131354244100700211150ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import univ from pyasn1.compat.octets import null from pysnmp import error from pysnmp import debug class SnmpContext(object): def __init__(self, snmpEngine, contextEngineId=None): snmpEngineId, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if contextEngineId is None: # Default to local snmpEngineId self.contextEngineId = snmpEngineId.syntax else: self.contextEngineId = snmpEngineId.syntax.clone(contextEngineId) debug.logger & debug.flagIns and debug.logger('SnmpContext: contextEngineId \"%r\"' % (self.contextEngineId,)) self.contextNames = { null: snmpEngine.msgAndPduDsp.mibInstrumController # Default name } def registerContextName(self, contextName, mibInstrum=None): contextName = univ.OctetString(contextName).asOctets() if contextName in self.contextNames: raise error.PySnmpError( 'Duplicate contextName %s' % contextName ) debug.logger & debug.flagIns and debug.logger( 'registerContextName: registered contextName %r, mibInstrum %r' % (contextName, mibInstrum)) 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 %r' % contextName) del self.contextNames[contextName] def getMibInstrum(self, contextName=null): contextName = univ.OctetString(contextName).asOctets() if contextName not in self.contextNames: debug.logger & debug.flagIns and debug.logger('getMibInstrum: contextName %r not registered' % contextName) raise error.PySnmpError( 'Missing contextName %s' % contextName ) else: debug.logger & debug.flagIns and debug.logger( 'getMibInstrum: contextName %r, mibInstum %r' % (contextName, self.contextNames[contextName])) return self.contextNames[contextName] pysnmp-4.4.12/pysnmp/entity/rfc3413/mibvar.py000066400000000000000000000054401354244100700207140ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # THESE FUNCTIONS ARE OBSOLETE AND MUST NOT BE USED! # USE pysnmp.entity.rfc3413.oneliner.mibvar INSTEAD # 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 registered that defines %s object, closest known parent is %s (%s::%s)' % ( univ.ObjectIdentifier(oid), univ.ObjectIdentifier(mibNode.name), modName, symName) ) # Value def cloneFromMibValue(mibView, modName, symName, value): mibNode, = mibView.mibBuilder.importSymbols( modName, symName ) if hasattr(mibNode, 'syntax'): # scalar return mibNode.syntax.clone(value) else: return # identifier pysnmp-4.4.12/pysnmp/entity/rfc3413/ntforg.py000066400000000000000000000424671354244100700207450ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pyasn1.compat.octets import null from pysnmp.entity.rfc3413 import config from pysnmp.proto.proxy import rfc2576 from pysnmp.proto import rfc3411 from pysnmp.proto.api import v2c from pysnmp.proto import errind, error from pysnmp.smi import view, rfc1902 from pysnmp import nextid from pysnmp import debug getNextHandle = nextid.Integer(0x7fffffff) class NotificationOriginator(object): acmID = 3 # default MIB access control method to use def __init__(self, **options): self.__pendingReqs = {} self.__pendingNotifications = {} self.snmpContext = options.pop('snmpContext', None) # this is deprecated self.__options = options def processResponsePdu(self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, sendPduHandle, cbInfo): sendRequestHandle, cbFun, cbCtx = cbInfo # 3.3.6d if sendPduHandle not in self.__pendingReqs: raise error.ProtocolError('Missing sendPduHandle %s' % sendPduHandle) (origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPdu, origTimeout, origRetryCount, origRetries, origDiscoveryRetries) = self.__pendingReqs.pop(sendPduHandle) snmpEngine.transportDispatcher.jobFinished(id(self)) if statusInformation: debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s statusInformation %s' % ( sendRequestHandle, sendPduHandle, statusInformation)) errorIndication = statusInformation['errorIndication'] if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID): origDiscoveryRetries += 1 origRetries = 0 else: origDiscoveryRetries = 0 origRetries += 1 if origRetries > origRetryCount or origDiscoveryRetries > self.__options.get('discoveryRetries', 4): debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s retry count %d exceeded' % ( sendRequestHandle, sendPduHandle, origRetries)) cbFun(snmpEngine, sendRequestHandle, errorIndication, None, cbCtx) return # Convert timeout in seconds into timeout in timer ticks timeoutInTicks = float(origTimeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() # User-side API assumes SMIv2 if messageProcessingModel == 0: reqPDU = rfc2576.v2ToV1(origPdu) pduVersion = 0 else: reqPDU = origPdu pduVersion = 1 # 3.3.6a try: sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, pduVersion, reqPDU, True, timeoutInTicks, self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % ( sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, statusInformation['errorIndication'], None, cbCtx) return snmpEngine.transportDispatcher.jobStarted(id(self)) debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendRequestHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % ( sendRequestHandle, sendPduHandle, origTimeout, origRetries, origRetryCount)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPdu, origTimeout, origRetryCount, origRetries, origDiscoveryRetries ) return # 3.3.6c # User-side API assumes SMIv2 if messageProcessingModel == 0: PDU = rfc2576.v1ToV2(PDU, origPdu) cbFun(snmpEngine, sendRequestHandle, None, PDU, cbCtx) def sendPdu(self, snmpEngine, targetName, contextEngineId, contextName, pdu, cbFun=None, cbCtx=None): (transportDomain, transportAddress, timeout, retryCount, params) = config.getTargetAddr(snmpEngine, targetName) (messageProcessingModel, securityModel, securityName, securityLevel) = config.getTargetParams(snmpEngine, params) # User-side API assumes SMIv2 if messageProcessingModel == 0: reqPDU = rfc2576.v2ToV1(pdu) pduVersion = 0 else: reqPDU = pdu pduVersion = 1 # 3.3.5 if reqPDU.tagSet in rfc3411.confirmedClassPDUs: # Convert timeout in seconds into timeout in timer ticks timeoutInTicks = float(timeout) / 100 / snmpEngine.transportDispatcher.getTimerResolution() sendRequestHandle = getNextHandle() # 3.3.6a sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, reqPDU, True, timeoutInTicks, self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) debug.logger & debug.flagApp and debug.logger( 'sendPdu: sendPduHandle %s, timeout %d' % (sendPduHandle, timeout)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pdu, timeout, retryCount, 0, 0 ) snmpEngine.transportDispatcher.jobStarted(id(self)) else: snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, reqPDU, False ) sendRequestHandle = None debug.logger & debug.flagApp and debug.logger('sendPdu: message sent') return sendRequestHandle def processResponseVarBinds(self, snmpEngine, sendRequestHandle, errorIndication, pdu, cbCtx): notificationHandle, cbFun, cbCtx = cbCtx self.__pendingNotifications[notificationHandle].remove(sendRequestHandle) debug.logger & debug.flagApp and debug.logger( 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s, errorIndication %s, pending requests %s' % ( notificationHandle, sendRequestHandle, errorIndication, self.__pendingNotifications[notificationHandle])) if not self.__pendingNotifications[notificationHandle]: debug.logger & debug.flagApp and debug.logger( 'processResponseVarBinds: notificationHandle %s, sendRequestHandle %s -- completed' % ( notificationHandle, sendRequestHandle)) del self.__pendingNotifications[notificationHandle] cbFun(snmpEngine, sendRequestHandle, errorIndication, pdu and v2c.apiPDU.getErrorStatus(pdu) or 0, pdu and v2c.apiPDU.getErrorIndex(pdu, muteErrors=True) or 0, pdu and v2c.apiPDU.getVarBinds(pdu) or (), cbCtx) # # Higher-level API to Notification Originator. Supports multiple # targets, automatic var-binding formation and is fully LCD-driven. # def sendVarBinds(self, snmpEngine, notificationTarget, contextEngineId, contextName, varBinds=(), cbFun=None, cbCtx=None): debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: notificationTarget %s, contextEngineId %s, contextName "%s", varBinds %s' % ( notificationTarget, contextEngineId or '', contextName, varBinds)) if contextName: __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-FRAMEWORK-MIB', 'SnmpAdminString') contextName = __SnmpAdminString(contextName) # 3.3 (notifyTag, notifyType) = config.getNotificationInfo(snmpEngine, notificationTarget) notificationHandle = getNextHandle() debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: notificationHandle %s, notifyTag %s, notifyType %s' % ( notificationHandle, notifyTag, notifyType)) varBinds = [(v2c.ObjectIdentifier(x), y) for x, y in varBinds] # 3.3.2 & 3.3.3 snmpTrapOID, sysUpTime = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpTrapOID', 'sysUpTime') for idx in range(len(varBinds)): if idx and varBinds[idx][0] == sysUpTime.getName(): if varBinds[0][0] == sysUpTime.getName(): varBinds[0] = varBinds[idx] else: varBinds.insert(0, varBinds[idx]) del varBinds[idx] if varBinds[0][0] != sysUpTime.getName(): varBinds.insert(0, (v2c.ObjectIdentifier(sysUpTime.getName()), sysUpTime.getSyntax().clone())) if len(varBinds) < 2 or varBinds[1][0] != snmpTrapOID.getName(): varBinds.insert(1, (v2c.ObjectIdentifier(snmpTrapOID.getName()), snmpTrapOID.getSyntax())) sendRequestHandle = -1 debug.logger & debug.flagApp and debug.logger('sendVarBinds: final varBinds %s' % (varBinds,)) for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): (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) debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: notificationHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % ( notificationHandle, notifyTag, transportDomain, transportAddress, securityModel, securityName, securityLevel)) for varName, varVal in varBinds: if varName in (sysUpTime.name, snmpTrapOID.name): continue try: snmpEngine.accessControlModel[self.acmID].isAccessAllowed( snmpEngine, securityModel, securityName, securityLevel, 'notify', contextName, varName ) debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: ACL succeeded for OID %s securityName %s' % (varName, securityName)) except error.StatusInformation: debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: ACL denied access for OID %s securityName %s, droppping notification' % ( varName, securityName)) return # 3.3.4 if notifyType == 1: pdu = v2c.SNMPv2TrapPDU() elif notifyType == 2: pdu = v2c.InformRequestPDU() else: raise error.ProtocolError('Unknown notify-type %r', notifyType) v2c.apiPDU.setDefaults(pdu) v2c.apiPDU.setVarBinds(pdu, varBinds) # 3.3.5 try: sendRequestHandle = self.sendPdu( snmpEngine, targetAddrName, contextEngineId, contextName, pdu, self.processResponseVarBinds, (notificationHandle, cbFun, cbCtx) ) except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % ( sendRequestHandle, statusInformation)) if notificationHandle not in self.__pendingNotifications or \ not self.__pendingNotifications[notificationHandle]: if notificationHandle in self.__pendingNotifications: del self.__pendingNotifications[notificationHandle] if cbFun: cbFun(snmpEngine, notificationHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return notificationHandle debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, timeout %d' % ( notificationHandle, sendRequestHandle, timeout)) if notifyType == 2: if notificationHandle not in self.__pendingNotifications: self.__pendingNotifications[notificationHandle] = set() self.__pendingNotifications[notificationHandle].add(sendRequestHandle) debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: notificationHandle %s, sendRequestHandle %s, notification(s) sent' % ( notificationHandle, sendRequestHandle)) return notificationHandle # # Obsolete, compatibility interfaces. # def _sendNotificationCbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbFun, cbCtx = cbCtx try: # we need to pass response PDU information to user for INFORMs cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx) except TypeError: # a backward compatible way of calling user function cbFun(sendRequestHandle, errorIndication, cbCtx) def _sendNotification(self, snmpEngine, notificationTarget, notificationName, additionalVarBinds=(), cbFun=None, cbCtx=None, contextName=null, instanceIndex=None): if self.snmpContext is None: raise error.ProtocolError('SNMP context not specified') # # Here we first expand trap OID into associated OBJECTS # and then look them up at context-specific MIB # mibViewController = snmpEngine.getUserContext('mibViewController') if not mibViewController: mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) snmpEngine.setUserContext(mibViewController=mibViewController) # Support the following syntax: # '1.2.3.4' # (1,2,3,4) # ('MIB', 'symbol') if isinstance(notificationName, (tuple, list)) and \ notificationName and isinstance(notificationName[0], str): notificationName = rfc1902.ObjectIdentity(*notificationName) else: notificationName = rfc1902.ObjectIdentity(notificationName) varBinds = rfc1902.NotificationType(notificationName, instanceIndex=instanceIndex) varBinds.resolveWithMib(mibViewController) mibInstrumController = self.snmpContext.getMibInstrum(contextName) varBinds = varBinds[:1] + mibInstrumController.readVars(varBinds[1:]) return self.sendVarBinds(snmpEngine, notificationTarget, self.snmpContext.contextEngineId, contextName, varBinds + list(additionalVarBinds), _sendNotificationCbFun, (cbFun, cbCtx)) # install compatibility wrapper NotificationOriginator.sendNotification = _sendNotification # XXX # move/group/implement config setting/retrieval at a stand-alone module pysnmp-4.4.12/pysnmp/entity/rfc3413/ntfrcv.py000066400000000000000000000107071354244100700207400ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys 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(object): 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.__snmpTrapCommunity = '' self.__cbFunVer = 0 self.__cbFun = cbFun self.__cbCtx = cbCtx def storeSnmpTrapCommunity(snmpEngine, execpoint, variables, cbCtx): self.__snmpTrapCommunity = variables.get('communityName', '') snmpEngine.observer.registerObserver(storeSnmpTrapCommunity, 'rfc2576.processIncomingMsg') def close(self, snmpEngine): snmpEngine.msgAndPduDsp.unregisterContextEngineId( null, self.pduTypes ) self.__cbFun = self.__cbCtx = None 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, snmpTrapCommunity=self.__snmpTrapCommunity) 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 += 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) pysnmp-4.4.12/pysnmp/entity/rfc3413/oneliner/000077500000000000000000000000001354244100700206725ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/entity/rfc3413/oneliner/__init__.py000066400000000000000000000000731354244100700230030ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/entity/rfc3413/oneliner/cmdgen.py000066400000000000000000000234551354244100700225120ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # All code in this file belongs to obsolete, compatibility wrappers. # Never use interfaces below for new applications! # from pysnmp.hlapi.asyncore import * from pysnmp.hlapi.asyncore import sync from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.lcd import * from pyasn1.compat.octets import null from pyasn1.type import univ __all__ = ['AsynCommandGenerator', 'CommandGenerator', 'MibVariable'] MibVariable = ObjectIdentity class AsynCommandGenerator(object): _null = univ.Null('') vbProcessor = CommandGeneratorVarBinds() lcd = CommandGeneratorLcdConfigurator() def __init__(self, snmpEngine=None): if snmpEngine is None: self.snmpEngine = SnmpEngine() else: self.snmpEngine = snmpEngine self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine) def __del__(self): self.lcd.unconfigure(self.snmpEngine) def cfgCmdGen(self, authData, transportTarget): return self.lcd.configure(self.snmpEngine, authData, transportTarget) def uncfgCmdGen(self, authData=None): return self.lcd.unconfigure(self.snmpEngine, authData) # compatibility stub def makeReadVarBinds(self, varNames): return self.makeVarBinds([(x, self._null) for x in varNames]) def makeVarBinds(self, varBinds): return self.vbProcessor.makeVarBinds(self.snmpEngine, varBinds) def unmakeVarBinds(self, varBinds, lookupNames, lookupValues): return self.vbProcessor.unmakeVarBinds( self.snmpEngine, varBinds, lookupNames or lookupValues ) def getCmd(self, authData, transportTarget, varNames, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbInfo): cbFun, cbCtx = cbInfo cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName return getCmd( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId, contextName), *[(x, self._null) for x in varNames], **dict(cbFun=__cbFun, cbCtx=cbInfo, lookupMib=lookupNames or lookupValues) ) asyncGetCmd = getCmd def setCmd(self, authData, transportTarget, varBinds, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbInfo): cbFun, cbCtx = cbInfo cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName return setCmd( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId, contextName), *varBinds, **dict(cbFun=__cbFun, cbCtx=cbInfo, lookupMib=lookupNames or lookupValues) ) asyncSetCmd = setCmd def nextCmd(self, authData, transportTarget, varNames, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbInfo): cbFun, cbCtx = cbInfo return cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName return nextCmd( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId, contextName), *[(x, self._null) for x in varNames], **dict(cbFun=__cbFun, cbCtx=cbInfo, lookupMib=lookupNames or lookupValues) ) asyncNextCmd = nextCmd def bulkCmd(self, authData, transportTarget, nonRepeaters, maxRepetitions, varNames, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbInfo): cbFun, cbCtx = cbInfo return cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName return bulkCmd( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId, contextName), nonRepeaters, maxRepetitions, *[(x, self._null) for x in varNames], **dict(cbFun=__cbFun, cbCtx=cbInfo, lookupMib=lookupNames or lookupValues) ) asyncBulkCmd = bulkCmd class CommandGenerator(object): _null = univ.Null('') def __init__(self, snmpEngine=None, asynCmdGen=None): # compatibility attributes self.snmpEngine = snmpEngine or SnmpEngine() def getCmd(self, authData, transportTarget, *varNames, **kwargs): if 'lookupNames' not in kwargs: kwargs['lookupNames'] = False if 'lookupValues' not in kwargs: kwargs['lookupValues'] = False errorIndication, errorStatus, errorIndex, varBinds = None, 0, 0, [] for (errorIndication, errorStatus, errorIndex, varBinds) in sync.getCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), *[(x, self._null) for x in varNames], **kwargs): break return errorIndication, errorStatus, errorIndex, varBinds def setCmd(self, authData, transportTarget, *varBinds, **kwargs): if 'lookupNames' not in kwargs: kwargs['lookupNames'] = False if 'lookupValues' not in kwargs: kwargs['lookupValues'] = False errorIndication, errorStatus, errorIndex, rspVarBinds = None, 0, 0, [] for (errorIndication, errorStatus, errorIndex, rspVarBinds) in sync.setCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), *varBinds, **kwargs): break return errorIndication, errorStatus, errorIndex, rspVarBinds def nextCmd(self, authData, transportTarget, *varNames, **kwargs): if 'lookupNames' not in kwargs: kwargs['lookupNames'] = False if 'lookupValues' not in kwargs: kwargs['lookupValues'] = False if 'lexicographicMode' not in kwargs: kwargs['lexicographicMode'] = False errorIndication, errorStatus, errorIndex = None, 0, 0 varBindTable = [] for (errorIndication, errorStatus, errorIndex, varBinds) in sync.nextCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), *[(x, self._null) for x in varNames], **kwargs): if errorIndication or errorStatus: return errorIndication, errorStatus, errorIndex, varBinds varBindTable.append(varBinds) return errorIndication, errorStatus, errorIndex, varBindTable def bulkCmd(self, authData, transportTarget, nonRepeaters, maxRepetitions, *varNames, **kwargs): if 'lookupNames' not in kwargs: kwargs['lookupNames'] = False if 'lookupValues' not in kwargs: kwargs['lookupValues'] = False if 'lexicographicMode' not in kwargs: kwargs['lexicographicMode'] = False errorIndication, errorStatus, errorIndex = None, 0, 0 varBindTable = [] for (errorIndication, errorStatus, errorIndex, varBinds) in sync.bulkCmd(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), nonRepeaters, maxRepetitions, *[(x, self._null) for x in varNames], **kwargs): if errorIndication or errorStatus: return errorIndication, errorStatus, errorIndex, varBinds varBindTable.append(varBinds) return errorIndication, errorStatus, errorIndex, varBindTable pysnmp-4.4.12/pysnmp/entity/rfc3413/oneliner/ntforg.py000066400000000000000000000150111354244100700225410ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # All code in this file belongs to obsolete, compatibility wrappers. # Never use interfaces below for new applications! # from pysnmp.hlapi.asyncore import * from pysnmp.hlapi.asyncore import sync from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.lcd import * from pyasn1.compat.octets import null from pysnmp.entity import config from pysnmp.entity.rfc3413 import context __all__ = ['AsynNotificationOriginator', 'NotificationOriginator', 'MibVariable'] MibVariable = ObjectIdentity class ErrorIndicationReturn(object): def __init__(self, *vars): self.__vars = vars def __getitem__(self, i): return self.__vars[i] def __nonzero__(self): return bool(self) def __bool__(self): return bool(self.__vars[0]) def __str__(self): return str(self.__vars[0]) class AsynNotificationOriginator(object): vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() def __init__(self, snmpEngine=None, snmpContext=None): if snmpEngine is None: self.snmpEngine = snmpEngine = SnmpEngine() else: self.snmpEngine = snmpEngine if snmpContext is None: self.snmpContext = context.SnmpContext(self.snmpEngine) config.addContext( self.snmpEngine, '' # this is leaky ) else: self.snmpContext = snmpContext self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine) def __del__(self): self.uncfgNtfOrg() def cfgNtfOrg(self, authData, transportTarget, notifyType): return self.lcd.configure( self.snmpEngine, authData, transportTarget, notifyType ) def uncfgNtfOrg(self, authData=None): return self.lcd.unconfigure(self.snmpEngine, authData) def makeVarBinds(self, varBinds): return self.vbProcessor.makeVarBinds( self.snmpEngine, varBinds ) def unmakeVarBinds(self, varBinds, lookupNames, lookupValues): return self.vbProcessor.unmakeVarBinds( self.snmpEngine, varBinds, lookupNames or lookupValues ) def sendNotification(self, authData, transportTarget, notifyType, notificationType, varBinds=(), # legacy, use NotificationType instead cbInfo=(None, None), lookupNames=False, lookupValues=False, contextEngineId=None, # XXX ordering incompatibility contextName=null): def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbFun, cbCtx = cbCtx try: # we need to pass response PDU information to user for INFORMs return cbFun and cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx ) except TypeError: # a backward compatible way of calling user function return cbFun( sendRequestHandle, errorIndication, cbCtx ) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName if not isinstance(notificationType, (ObjectIdentity, ObjectType, NotificationType)): if isinstance(notificationType[0], tuple): # legacy notificationType = ObjectIdentity(notificationType[0][0], notificationType[0][1], *notificationType[1:]) else: notificationType = ObjectIdentity(notificationType) if not isinstance(notificationType, NotificationType): notificationType = NotificationType(notificationType) return sendNotification( self.snmpEngine, authData, transportTarget, ContextData(contextEngineId or self.snmpContext.contextEngineId, contextName), notifyType, notificationType.addVarBinds(*varBinds), __cbFun, cbInfo, lookupNames or lookupValues ) asyncSendNotification = sendNotification class NotificationOriginator(object): vbProcessor = NotificationOriginatorVarBinds() def __init__(self, snmpEngine=None, snmpContext=None, asynNtfOrg=None): # compatibility attributes self.snmpEngine = snmpEngine or SnmpEngine() self.mibViewController = self.vbProcessor.getMibViewController(self.snmpEngine) # the varBinds parameter is legacy, use NotificationType instead def sendNotification(self, authData, transportTarget, notifyType, notificationType, *varBinds, **kwargs): if 'lookupNames' not in kwargs: kwargs['lookupNames'] = False if 'lookupValues' not in kwargs: kwargs['lookupValues'] = False if not isinstance(notificationType, (ObjectIdentity, ObjectType, NotificationType)): if isinstance(notificationType[0], tuple): # legacy notificationType = ObjectIdentity(notificationType[0][0], notificationType[0][1], *notificationType[1:]) else: notificationType = ObjectIdentity(notificationType) if not isinstance(notificationType, NotificationType): notificationType = NotificationType(notificationType) for (errorIndication, errorStatus, errorIndex, rspVarBinds) in sync.sendNotification(self.snmpEngine, authData, transportTarget, ContextData(kwargs.get('contextEngineId'), kwargs.get('contextName', null)), notifyType, notificationType.addVarBinds(*varBinds), **kwargs): if notifyType == 'inform': return errorIndication, errorStatus, errorIndex, rspVarBinds else: break pysnmp-4.4.12/pysnmp/error.py000066400000000000000000000007701354244100700161650ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys class PySnmpError(Exception): def __init__(self, *args): msg = args and str(args[0]) or '' self.cause = sys.exc_info() if self.cause[0]: msg += 'caused by %s: %s' % (self.cause[0], self.cause[1]) if msg: args = (msg,) + args[1:] Exception.__init__(self, *args) pysnmp-4.4.12/pysnmp/hlapi/000077500000000000000000000000001354244100700155535ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/hlapi/__init__.py000066400000000000000000000063661354244100700176770ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.rfc1902 import * from pysnmp.proto.rfc1905 import NoSuchInstance, NoSuchObject, EndOfMibView from pysnmp.smi.rfc1902 import * from pysnmp.hlapi import auth from pysnmp.hlapi.context import * from pysnmp.entity.engine import * # default is synchronous asyncore-based API from pysnmp.hlapi.asyncore.sync import * CommunityData = auth.CommunityData UsmUserData = auth.UsmUserData usmNoAuthProtocol = auth.usmNoAuthProtocol """No Authentication Protocol""" usmHMACMD5AuthProtocol = auth.usmHMACMD5AuthProtocol """The HMAC-MD5-96 Digest Authentication Protocol (:RFC:`3414#section-6`)""" usmHMACSHAAuthProtocol = auth.usmHMACSHAAuthProtocol """The HMAC-SHA-96 Digest Authentication Protocol AKA SHA-1 (:RFC:`3414#section-7`)""" usmHMAC128SHA224AuthProtocol = auth.usmHMAC128SHA224AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmHMAC192SHA256AuthProtocol = auth.usmHMAC192SHA256AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmHMAC256SHA384AuthProtocol = auth.usmHMAC256SHA384AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmHMAC384SHA512AuthProtocol = auth.usmHMAC384SHA512AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmNoPrivProtocol = auth.usmNoPrivProtocol """No Privacy Protocol""" usmDESPrivProtocol = auth.usmDESPrivProtocol """The CBC-DES Symmetric Encryption Protocol (:RFC:`3414#section-8`)""" usm3DESEDEPrivProtocol = auth.usm3DESEDEPrivProtocol """The 3DES-EDE Symmetric Encryption Protocol (`draft-reeder-snmpv3-usm-3desede-00 `_)""" usmAesCfb128Protocol = auth.usmAesCfb128Protocol """The CFB128-AES-128 Symmetric Encryption Protocol (:RFC:`3826#section-3`)""" usmAesCfb192Protocol = auth.usmAesCfb192Protocol """The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_) with Reeder key localization""" usmAesCfb256Protocol = auth.usmAesCfb256Protocol """The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_) with Reeder key localization""" usmAesBlumenthalCfb192Protocol = auth.usmAesBlumenthalCfb192Protocol """The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_)""" usmAesBlumenthalCfb256Protocol = auth.usmAesBlumenthalCfb256Protocol """The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_)""" usmKeyTypePassphrase = auth.usmKeyTypePassphrase """USM key material type - plain-text pass phrase (:RFC:`3414#section-2.6`)""" usmKeyTypeMaster = auth.usmKeyTypeMaster """USM key material type - hashed pass-phrase AKA master key (:RFC:`3414#section-2.6`)""" usmKeyTypeLocalized = auth.usmKeyTypeLocalized """USM key material type - hashed pass-phrase hashed with Context SNMP Engine ID (:RFC:`3414#section-2.6`)""" pysnmp-4.4.12/pysnmp/hlapi/asyncio/000077500000000000000000000000001354244100700172205ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/hlapi/asyncio/__init__.py000066400000000000000000000007101354244100700213270ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.entity.engine import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.asyncio.transport import * from pysnmp.hlapi.asyncio.cmdgen import * from pysnmp.hlapi.asyncio.ntforg import * pysnmp-4.4.12/pysnmp/hlapi/asyncio/cmdgen.py000066400000000000000000000462321354244100700210360ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Copyright (C) 2014, Zebra Technologies # Authors: Matt Hooks # Zachary Lorusso # Modified by Ilya Etingof # # 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. # # 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 COPYRIGHT HOLDERS AND 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. # import sys from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.asyncio.transport import * from pysnmp.entity.rfc3413 import cmdgen try: import asyncio except ImportError: import trollius as asyncio __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'isEndOfMib'] vbProcessor = CommandGeneratorVarBinds() lcd = CommandGeneratorLcdConfigurator() isEndOfMib = lambda x: not cmdgen.getNextVarBinds(x)[1] @asyncio.coroutine def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform SNMP GET query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> import asyncio >>> from pysnmp.hlapi.asyncio import * >>> >>> @asyncio.coroutine ... def run(): ... errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( ... SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)) ... ) ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> asyncio.get_event_loop().run_until_complete(run()) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, future = cbCtx if future.cancelled(): return try: varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib) except Exception: ex = sys.exc_info()[1] future.set_exception(ex) else: future.set_result( (errorIndication, errorStatus, errorIndex, varBindsUnmade) ) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) future = asyncio.Future() cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), future) ) return future @asyncio.coroutine def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform SNMP SET query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP SET request is send (:RFC:`1905#section-4.2.5`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> import asyncio >>> from pysnmp.hlapi.asyncio import * >>> >>> @asyncio.coroutine ... def run(): ... errorIndication, errorStatus, errorIndex, varBinds = yield from setCmd( ... SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386') ... ) ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> asyncio.get_event_loop().run_until_complete(run()) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('Linux i386'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, future = cbCtx if future.cancelled(): return try: varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib) except Exception: ex = sys.exc_info()[1] future.set_exception(ex) else: future.set_result( (errorIndication, errorStatus, errorIndex, varBindsUnmade) ) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) future = asyncio.Future() cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), future) ) return future @asyncio.coroutine def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform SNMP GETNEXT query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of sequences (e.g. 2-D array) of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing a table of MIB variables returned in SNMP response. Inner sequences represent table rows and ordered exactly the same as `varBinds` in request. Response to GETNEXT always contain a single row. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> import asyncio >>> from pysnmp.hlapi.asyncio import * >>> >>> @asyncio.coroutine ... def run(): ... errorIndication, errorStatus, errorIndex, varBinds = yield from nextCmd( ... SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')) ... ) ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> asyncio.get_event_loop().run_until_complete(run()) (None, 0, 0, [[ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), DisplayString('Linux i386'))]]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, future = cbCtx if future.cancelled(): return try: varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable] except Exception: ex = sys.exc_info()[1] future.set_exception(ex) else: future.set_result( (errorIndication, errorStatus, errorIndex, varBindsUnmade) ) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) future = asyncio.Future() cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), future) ) return future @asyncio.coroutine def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): """Creates a generator to perform SNMP GETBULK query. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP GETBULK request is send (:RFC:`1905#section-4.2.3`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. nonRepeaters : int One MIB variable is requested in response for the first `nonRepeaters` MIB variables in request. maxRepetitions : int `maxRepetitions` MIB variables are requested in response for each of the remaining MIB variables in the request (e.g. excluding `nonRepeaters`). Remote SNMP engine may choose lesser value than requested. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBindTable : tuple A sequence of sequences (e.g. 2-D array) of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing a table of MIB variables returned in SNMP response, with up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``. For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``, ``varBindTable[i][j]`` represents: - For non-repeaters (``j < nonRepeaters``), the first lexicographic successor of ``varBinds[j]``, regardless the value of ``i``, or an :py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the :py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor exists; - For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic successor of ``varBinds[j]``, or an :py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the :py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor exists. See :rfc:`3416#section-4.2.3` for details on the underlying ``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as specific conditions under which the server may truncate the response, causing ``varBindTable`` to have less than ``maxRepetitions`` rows. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> import asyncio >>> from pysnmp.hlapi.asyncio import * >>> >>> @asyncio.coroutine ... def run(): ... errorIndication, errorStatus, errorIndex, varBinds = yield from bulkCmd( ... SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... 0, 2, ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')) ... ) ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> asyncio.get_event_loop().run_until_complete(run()) (None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))], [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.2.0')), ObjectIdentifier('1.3.6.1.4.1.424242.1.1'))]]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, future = cbCtx if future.cancelled(): return try: varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable] except Exception: ex = sys.exc_info()[1] future.set_exception(ex) else: future.set_result( (errorIndication, errorStatus, errorIndex, varBindsUnmade) ) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) future = asyncio.Future() cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, nonRepeaters, maxRepetitions, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), future) ) return future pysnmp-4.4.12/pysnmp/hlapi/asyncio/ntforg.py000066400000000000000000000126071354244100700210770ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # Copyright (C) 2014, Zebra Technologies # Authors: Matt Hooks # Zachary Lorusso # import sys from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.asyncio.transport import * from pysnmp.entity.rfc3413 import ntforg try: import asyncio except ImportError: import trollius as asyncio __all__ = ['sendNotification'] vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() @asyncio.coroutine def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): """Creates a generator to send SNMP notification. When iterator gets advanced by :py:mod:`asyncio` main loop, SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4.2.6`). The iterator yields :py:class:`asyncio.Future` which gets done whenever response arrives or error occurs. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncio.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncio.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. notifyType : str Indicates type of notification to be sent. Recognized literal values are *trap* or *inform*. varBinds: tuple Single :py:class:`~pysnmp.smi.rfc1902.NotificationType` class instance representing a minimum sequence of MIB variables required for particular notification type. Alternatively, a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects could be passed instead. In the latter case it is up to the user to ensure proper Notification PDU contents. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- The `sendNotification` generator will be exhausted immidiately unless an instance of :py:class:`~pysnmp.smi.rfc1902.NotificationType` class or a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` `varBinds` are send back into running generator (supported since Python 2.6). Examples -------- >>> import asyncio >>> from pysnmp.hlapi.asyncio import * >>> >>> @asyncio.coroutine ... def run(): ... errorIndication, errorStatus, errorIndex, varBinds = yield from sendNotification( ... SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'trap', ... NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))) ... print(errorIndication, errorStatus, errorIndex, varBinds) ... >>> asyncio.get_event_loop().run_until_complete(run()) (None, 0, 0, []) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, future = cbCtx if future.cancelled(): return try: varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib) except Exception: ex = sys.exc_info()[1] future.set_exception(ex) else: future.set_result( (errorIndication, errorStatus, errorIndex, varBindsUnmade) ) notifyName = lcd.configure( snmpEngine, authData, transportTarget, notifyType, contextData.contextName) future = asyncio.Future() ntforg.NotificationOriginator().sendVarBinds( snmpEngine, notifyName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), future) ) if notifyType == 'trap': def __trapFun(future): if future.cancelled(): return future.set_result((None, 0, 0, [])) loop = asyncio.get_event_loop() loop.call_soon(__trapFun, future) return future pysnmp-4.4.12/pysnmp/hlapi/asyncio/transport.py000066400000000000000000000115471354244100700216360ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket import sys from pysnmp.carrier.asyncio.dgram import udp, udp6 from pysnmp.hlapi.transport import AbstractTransportTarget from pysnmp.error import PySnmpError __all__ = ['Udp6TransportTarget', 'UdpTransportTarget'] class UdpTransportTarget(AbstractTransportTarget): """Creates UDP/IPv4 configuration entry and initialize socket API if needed. This object can be used for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`1906#section-3` for more information on the UDP transport mapping. Parameters ---------- transportAddr : tuple Indicates remote address in Python :py:mod:`socket` module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv4 address in quad-dotted form, port is an integer. timeout : int Response timeout in seconds. retries : int Maximum number of request retries, 0 retries means just a single request. tagList : str Arbitrary string that contains a list of tag values which are used to select target addresses for a particular operation (:RFC:`3413#section-4.1.4`). Examples -------- >>> from pysnmp.hlapi.asyncio import UdpTransportTarget >>> UdpTransportTarget(('demo.snmplabs.com', 161)) UdpTransportTarget(('195.218.195.228', 161), timeout=1, retries=5, tagList='') >>> """ transportDomain = udp.domainName protoTransport = udp.UdpAsyncioTransport def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], transportAddr[1], socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) class Udp6TransportTarget(AbstractTransportTarget): """Creates UDP/IPv6 configuration entry and initialize socket API if needed. This object can be used by :py:class:`~pysnmp.hlapi.asyncio.AsyncCommandGenerator` or :py:class:`~pysnmp.hlapi.asyncio.AsyncNotificationOriginator` and their derevatives for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`1906#section-3`, :RFC:`2851#section-4` for more information on the UDP and IPv6 transport mapping. Parameters ---------- transportAddr : tuple Indicates remote address in Python :py:mod:`socket` module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv6 address in one of three conventional forms (:RFC:`1924#section-3`), port is an integer. timeout : int Response timeout in seconds. retries : int Maximum number of request retries, 0 retries means just a single request. tagList : str Arbitrary string that contains a list of tag values which are used to select target addresses for a particular operation (:RFC:`3413#section-4.1.4`). Examples -------- >>> from pysnmp.hlapi.asyncio import Udp6TransportTarget >>> Udp6TransportTarget(('google.com', 161)) Udp6TransportTarget(('2a00:1450:4014:80a::100e', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 161)) Udp6TransportTarget(('fedc:ba98:7654:3210:fedc:ba98:7654:3210', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('1080:0:0:0:8:800:200C:417A', 161)) Udp6TransportTarget(('1080::8:800:200c:417a', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('::0', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('::', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList='') >>> """ transportDomain = udp6.domainName protoTransport = udp6.Udp6AsyncioTransport def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], transportAddr[1], socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: raise PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) pysnmp-4.4.12/pysnmp/hlapi/asyncore/000077500000000000000000000000001354244100700173765ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/hlapi/asyncore/__init__.py000066400000000000000000000007131354244100700215100ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.asyncore.transport import * from pysnmp.hlapi.asyncore.cmdgen import * from pysnmp.hlapi.asyncore.ntforg import * from pysnmp.entity.engine import * pysnmp-4.4.12/pysnmp/hlapi/asyncore/cmdgen.py000066400000000000000000000474331354244100700212200ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.entity.rfc3413 import cmdgen from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.asyncore.transport import * __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'isEndOfMib'] vbProcessor = CommandGeneratorVarBinds() lcd = CommandGeneratorLcdConfigurator() isEndOfMib = lambda x: not cmdgen.getNextVarBinds(x)[1] def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GET query. Based on passed parameters, prepares SNMP GET packet (:RFC:`1905#section-4.2.1`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `cbFun` (callable) - user-supplied callable that is invoked to pass SNMP response data or error to user at a later point of time. Default is `None`. * `cbCtx` (object) - user-supplied object passing additional parameters to/from `cbFun`. Default is `None`. Notes ----- User-supplied `cbFun` callable must have the following call signature: * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`): Class instance representing SNMP engine. * sendRequestHandle (int): Unique request identifier. Can be used for matching multiple ongoing requests with received responses. * errorIndication (str): True value indicates SNMP engine error. * errorStatus (str): True value indicates SNMP PDU error. * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple): A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response in exactly the same order as `varBinds` in request. * `cbCtx` : Original user-supplied object. Returns ------- sendRequestHandle : int Unique request identifier. Can be used for matching received responses with ongoing requests. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> from pysnmp.hlapi.asyncore import * >>> def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> snmpEngine = SnmpEngine() >>> getCmd(snmpEngine, ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)), ... cbFun=cbFun) >>> snmpEngine.transportDispatcher.runDispatcher() (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, cbFun, cbCtx = cbCtx if cbFun: return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, vbProcessor.unmakeVarBinds( snmpEngine, varBinds, lookupMib ), cbCtx) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) return cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), options.get('cbFun'), options.get('cbCtx')) ) def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP SET query. Based on passed parameters, prepares SNMP SET packet (:RFC:`1905#section-4.2.5`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `cbFun` (callable) - user-supplied callable that is invoked to pass SNMP response data or error to user at a later point of time. Default is `None`. * `cbCtx` (object) - user-supplied object passing additional parameters to/from `cbFun`. Default is `None`. Notes ----- User-supplied `cbFun` callable must have the following call signature: * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`): Class instance representing SNMP engine. * sendRequestHandle (int): Unique request identifier. Can be used for matching multiple ongoing requests with received responses. * errorIndication (str): True value indicates SNMP engine error. * errorStatus (str): True value indicates SNMP PDU error. * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple): A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response in exactly the same order as `varBinds` in request. * `cbCtx` : Original user-supplied object. Returns ------- sendRequestHandle : int Unique request identifier. Can be used for matching received responses with ongoing requests. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> from pysnmp.hlapi.asyncore import * >>> def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> snmpEngine = SnmpEngine() >>> setCmd(snmpEngine, ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysContact', 0), 'info@snmplabs.com'), ... cbFun=cbFun) >>> snmpEngine.transportDispatcher.runDispatcher() (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.4.0')), DisplayString('info@snmplabs.com'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, cbFun, cbCtx = cbCtx return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, vbProcessor.unmakeVarBinds( snmpEngine, varBinds, lookupMib ), cbCtx) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) return cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), options.get('cbFun'), options.get('cbCtx')) ) def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.2`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `cbFun` (callable) - user-supplied callable that is invoked to pass SNMP response data or error to user at a later point of time. Default is `None`. * `cbCtx` (object) - user-supplied object passing additional parameters to/from `cbFun`. Default is `None`. Notes ----- User-supplied `cbFun` callable must have the following call signature: * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`): Class instance representing SNMP engine. * sendRequestHandle (int): Unique request identifier. Can be used for matching multiple ongoing requests with received responses. * errorIndication (str): True value indicates SNMP engine error. * errorStatus (str): True value indicates SNMP PDU error. * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple): A sequence of sequences (e.g. 2-D array) of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing a table of MIB variables returned in SNMP response. Inner sequences represent table rows and ordered exactly the same as `varBinds` in request. Response to GETNEXT always contain a single row. * `cbCtx` : Original user-supplied object. Returns ------- sendRequestHandle : int Unique request identifier. Can be used for matching received responses with ongoing requests. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> from pysnmp.hlapi.asyncore import * >>> def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> snmpEngine = SnmpEngine() >>> nextCmd(snmpEngine, ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')), ... cbFun=cbFun) >>> snmpEngine.transportDispatcher.runDispatcher() (None, 0, 0, [ [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))] ]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, cbFun, cbCtx = cbCtx return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable], cbCtx) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) return cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), options.get('cbFun'), options.get('cbCtx')) ) def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): """Performs SNMP GETBULK query. Based on passed parameters, prepares SNMP GETBULK packet (:RFC:`1905#section-4.2.3`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. nonRepeaters : int One MIB variable is requested in response for the first `nonRepeaters` MIB variables in request. maxRepetitions : int `maxRepetitions` MIB variables are requested in response for each of the remaining MIB variables in the request (e.g. excluding `nonRepeaters`). Remote SNMP engine may choose lesser value than requested. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `cbFun` (callable) - user-supplied callable that is invoked to pass SNMP response data or error to user at a later point of time. Default is `None`. * `cbCtx` (object) - user-supplied object passing additional parameters to/from `cbFun`. Default is `None`. Notes ----- User-supplied `cbFun` callable must have the following call signature: * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`): Class instance representing SNMP engine. * sendRequestHandle (int): Unique request identifier. Can be used for matching multiple ongoing requests with received responses. * errorIndication (str): True value indicates SNMP engine error. * errorStatus (str): True value indicates SNMP PDU error. * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]` * varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing a table of MIB variables returned in SNMP response, with up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``. For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``, ``varBindTable[i][j]`` represents: - For non-repeaters (``j < nonRepeaters``), the first lexicographic successor of ``varBinds[j]``, regardless the value of ``i``, or an :py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the :py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor exists; - For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic successor of ``varBinds[j]``, or an :py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the :py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor exists. See :rfc:`3416#section-4.2.3` for details on the underlying ``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as specific conditions under which the server may truncate the response, causing ``varBindTable`` to have less than ``maxRepetitions`` rows. * `cbCtx` : Original user-supplied object. Returns ------- sendRequestHandle : int Unique request identifier. Can be used for matching received responses with ongoing requests. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> from pysnmp.hlapi.asyncore import * >>> def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): ... print(errorIndication, errorStatus, errorIndex, varBinds) >>> >>> snmpEngine = SnmpEngine() >>> bulkCmd(snmpEngine, ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... 0, 2, ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')), ... cbFun=cbFun) >>> snmpEngine.transportDispatcher.runDispatcher() (None, 0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))], [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.2.0')), ObjectIdentifier('1.3.6.1.4.1.424242.1.1'))]]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, cbFun, cbCtx = cbCtx return cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable], cbCtx) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) return cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, nonRepeaters, maxRepetitions, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), options.get('cbFun'), options.get('cbCtx')) ) pysnmp-4.4.12/pysnmp/hlapi/asyncore/ntforg.py000066400000000000000000000121051354244100700212460ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.smi.rfc1902 import * from pysnmp.entity.rfc3413 import ntforg from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.asyncore.transport import * __all__ = ['sendNotification'] vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, cbFun=None, cbCtx=None, lookupMib=False): """Send SNMP notification. Based on passed parameters, prepares SNMP TRAP or INFORM notification (:RFC:`1905#section-4.2.6`) and schedules its transmission by I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. notifyType : str Indicates type of notification to be sent. Recognized literal values are *trap* or *inform*. varBinds : tuple Single :py:class:`~pysnmp.smi.rfc1902.NotificationType` class instance representing a minimum sequence of MIB variables required for particular notification type. Alternatively, a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects could be passed instead. In the latter case it is up to the user to ensure proper Notification PDU contents. Other Parameters ---------------- cbFun : callable user-supplied callable that is invoked to pass SNMP response to *INFORM* notification or error to user at a later point of time. The `cbFun` callable is never invoked for *TRAP* notifications. cbCtx : object user-supplied object passing additional parameters to/from `cbFun`. lookupMib : bool `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Notes ----- User-supplied `cbFun` callable must have the following call signature: * snmpEngine (:py:class:`~pysnmp.hlapi.SnmpEngine`): Class instance representing SNMP engine. * sendRequestHandle (int): Unique request identifier. Can be used for matching multiple ongoing *INFORM* notifications with received responses. * errorIndication (str): True value indicates SNMP engine error. * errorStatus (str): True value indicates SNMP PDU error. * errorIndex (int): Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple): A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response in exactly the same order as `varBinds` in request. * `cbCtx` : Original user-supplied object. Returns ------- sendRequestHandle : int Unique request identifier. Can be used for matching received responses with ongoing *INFORM* requests. Returns `None` for *TRAP* notifications. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Examples -------- >>> from pysnmp.hlapi.asyncore import * >>> >>> snmpEngine = SnmpEngine() >>> sendNotification( ... snmpEngine, ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'trap', ... NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart')), ... ) >>> snmpEngine.transportDispatcher.runDispatcher() >>> """ # noinspection PyShadowingNames def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, cbFun, cbCtx = cbCtx return cbFun and cbFun( snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, vbProcessor.unmakeVarBinds( snmpEngine, varBinds, lookupMib ), cbCtx ) notifyName = lcd.configure(snmpEngine, authData, transportTarget, notifyType, contextData.contextName) return ntforg.NotificationOriginator().sendVarBinds( snmpEngine, notifyName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (lookupMib, cbFun, cbCtx) ) pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/000077500000000000000000000000001354244100700203525ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/__init__.py000066400000000000000000000011551354244100700224650ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.asyncore.transport import * from pysnmp.entity.engine import * try: from pysnmp.hlapi.asyncore.sync.cmdgen import * from pysnmp.hlapi.asyncore.sync.ntforg import * except SyntaxError: from pysnmp.hlapi.asyncore.sync.compat.cmdgen import * from pysnmp.hlapi.asyncore.sync.compat.ntforg import * pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/cmdgen.py000066400000000000000000000577701354244100700222010ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from sys import version_info from pysnmp.hlapi.asyncore import cmdgen from pysnmp.hlapi.varbinds import * from pysnmp.proto.rfc1905 import endOfMibView from pysnmp.proto import errind from pyasn1.type.univ import Null __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd'] if version_info[:2] < (2, 6): __all__.append('next') # noinspection PyShadowingBuiltins def next(iter): return iter.next() def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GET queries. On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- The `getCmd` generator will be exhausted immidiately unless a new sequence of `varBinds` are send back into running generator (supported since Python 2.6). Examples -------- >>> from pysnmp.hlapi import * >>> g = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cbCtx = {} while True: if varBinds: cmdgen.getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] varBinds = cbCtx['varBinds'] else: errorIndication = errorStatus = errorIndex = None varBinds = [] varBinds = (yield errorIndication, errorStatus, errorIndex, varBinds) if not varBinds: break def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP SET queries. On each iteration, new SNMP SET request is send (:RFC:`1905#section-4.2.5`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- The `setCmd` generator will be exhausted immidiately unless a new sequence of `varBinds` are send back into running generator (supported since Python 2.6). Examples -------- >>> from pysnmp.hlapi import * >>> g = setCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('Linux i386'))]) >>> """ # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cbCtx = {} while True: if varBinds: cmdgen.setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] varBinds = cbCtx['varBinds'] else: errorIndication = errorStatus = errorIndex = None varBinds = [] varBinds = (yield errorIndication, errorStatus, errorIndex, varBinds) if not varBinds: break def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GETNEXT queries. On each iteration, new SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Default is `True`. * `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`), otherwise (if `False`) stop iteration when all response MIB variables leave the scope of initial MIB variables in `varBinds`. Default is `True`. * `ignoreNonIncreasingOid` - continue iteration even if response MIB variables (OIDs) are not greater then request MIB variables. Be aware that setting it to `True` may cause infinite loop between SNMP management and agent applications. Default is `False`. * `maxRows` - stop iteration once this generator instance processed `maxRows` of SNMP conceptual table. Default is `0` (no limit). * `maxCalls` - stop iteration once this generator instance processed `maxCalls` responses. Default is 0 (no limit). Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- The `nextCmd` generator will be exhausted on any of the following conditions: * SNMP engine error occurs thus `errorIndication` is `True` * SNMP PDU `errorStatus` is reported as `True` * SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values (also known as *SNMP exception values*) are reported for all MIB variables in `varBinds` * *lexicographicMode* option is `True` and SNMP agent reports end-of-mib or *lexicographicMode* is `False` and all response MIB variables leave the scope of `varBinds` At any moment a new sequence of `varBinds` could be send back into running generator (supported since Python 2.6). Examples -------- >>> from pysnmp.hlapi import * >>> g = nextCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] ) (None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) """ # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBindTable'] = varBindTable lexicographicMode = options.get('lexicographicMode', True) ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False) maxRows = options.get('maxRows', 0) maxCalls = options.get('maxCalls', 0) cbCtx = {} vbProcessor = CommandGeneratorVarBinds() initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] totalRows = totalCalls = 0 while True: previousVarBinds = varBinds if varBinds: cmdgen.nextCmd(snmpEngine, authData, transportTarget, contextData, *[(x[0], Null('')) for x in varBinds], **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] if ignoreNonIncreasingOid and errorIndication and isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: yield (errorIndication, errorStatus, errorIndex, varBinds) return elif errorStatus: if errorStatus == 2: # Hide SNMPv1 noSuchName error which leaks in here # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) yield (errorIndication, errorStatus, errorIndex, varBinds) return else: stopFlag = True varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0] for col, varBind in enumerate(varBinds): name, val = varBind if isinstance(val, Null): varBinds[col] = previousVarBinds[col][0], endOfMibView if not lexicographicMode and not initialVars[col].isPrefixOf(name): varBinds[col] = previousVarBinds[col][0], endOfMibView if stopFlag and varBinds[col][1] is not endOfMibView: stopFlag = False if stopFlag: return totalRows += 1 totalCalls += 1 else: errorIndication = errorStatus = errorIndex = None varBinds = [] initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBinds) if initialVarBinds: varBinds = initialVarBinds initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] if maxRows and totalRows >= maxRows: return if maxCalls and totalCalls >= maxCalls: return def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): """Creates a generator to perform one or more SNMP GETBULK queries. On each iteration, new SNMP GETBULK request is send (:RFC:`1905#section-4.2.3`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. nonRepeaters : int One MIB variable is requested in response for the first `nonRepeaters` MIB variables in request. maxRepetitions : int `maxRepetitions` MIB variables are requested in response for each of the remaining MIB variables in the request (e.g. excluding `nonRepeaters`). Remote SNMP engine may choose lesser value than requested. \*varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Default is `True`. * `lexicographicMode` - walk SNMP agent's MIB till the end (if `True`), otherwise (if `False`) stop iteration when all response MIB variables leave the scope of initial MIB variables in `varBinds`. Default is `True`. * `ignoreNonIncreasingOid` - continue iteration even if response MIB variables (OIDs) are not greater then request MIB variables. Be aware that setting it to `True` may cause infinite loop between SNMP management and agent applications. Default is `False`. * `maxRows` - stop iteration once this generator instance processed `maxRows` of SNMP conceptual table. Default is `0` (no limit). * `maxCalls` - stop iteration once this generator instance processed `maxCalls` responses. Default is 0 (no limit). Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to \*varBinds[errorIndex-1] varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- The `bulkCmd` generator will be exhausted on any of the following conditions: * SNMP engine error occurs thus `errorIndication` is `True` * SNMP PDU `errorStatus` is reported as `True` * SNMP :py:class:`~pysnmp.proto.rfc1905.EndOfMibView` values (also known as *SNMP exception values*) are reported for all MIB variables in `varBinds` * *lexicographicMode* option is `True` and SNMP agent reports end-of-mib or *lexicographicMode* is `False` and all response MIB variables leave the scope of `varBinds` At any moment a new sequence of `varBinds` could be send back into running generator (supported since Python 2.6). Setting `maxRepetitions` value to 15..50 might significantly improve system performance, as many MIB variables get packed into a single response message at once. Examples -------- >>> from pysnmp.hlapi import * >>> g = bulkCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... 0, 25, ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> g.send( [ ObjectType(ObjectIdentity('IF-MIB', 'ifInOctets')) ] ) (None, 0, 0, [(ObjectName('1.3.6.1.2.1.2.2.1.10.1'), Counter32(284817787))]) """ # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBindTable'] = varBindTable lexicographicMode = options.get('lexicographicMode', True) ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False) maxRows = options.get('maxRows', 0) maxCalls = options.get('maxCalls', 0) cbCtx = {} vbProcessor = CommandGeneratorVarBinds() initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] nullVarBinds = [False] * len(initialVars) totalRows = totalCalls = 0 stopFlag = False while not stopFlag: if maxRows and totalRows < maxRows: maxRepetitions = min(maxRepetitions, maxRows - totalRows) previousVarBinds = varBinds cmdgen.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *[(x[0], Null('')) for x in varBinds], **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] varBindTable = cbCtx['varBindTable'] if ignoreNonIncreasingOid and errorIndication and \ isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or []) if errorIndication != errind.requestTimedOut: return elif errorStatus: if errorStatus == 2: # Hide SNMPv1 noSuchName error which leaks in here # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or []) return else: for row in range(len(varBindTable)): stopFlag = True if len(varBindTable[row]) != len(initialVars): varBindTable = row and varBindTable[:row - 1] or [] break for col in range(len(varBindTable[row])): name, val = varBindTable[row][col] if row: previousVarBinds = varBindTable[row - 1] if nullVarBinds[col]: varBindTable[row][col] = previousVarBinds[col][0], endOfMibView continue stopFlag = False if isinstance(val, Null): varBindTable[row][col] = previousVarBinds[col][0], endOfMibView nullVarBinds[col] = True if not lexicographicMode and not initialVars[col].isPrefixOf(name): varBindTable[row][col] = previousVarBinds[col][0], endOfMibView nullVarBinds[col] = True if stopFlag: varBindTable = row and varBindTable[:row - 1] or [] break totalRows += len(varBindTable) totalCalls += 1 if maxRows and totalRows >= maxRows: if totalRows > maxRows: varBindTable = varBindTable[:-(totalRows - maxRows)] stopFlag = True if maxCalls and totalCalls >= maxCalls: stopFlag = True varBinds = varBindTable and varBindTable[-1] or [] for varBindRow in varBindTable: initialVarBinds = (yield errorIndication, errorStatus, errorIndex, varBindRow) if initialVarBinds: varBinds = initialVarBinds initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] nullVarBinds = [False] * len(initialVars) pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/compat/000077500000000000000000000000001354244100700216355ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/compat/__init__.py000066400000000000000000000000731354244100700237460ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/compat/cmdgen.py000066400000000000000000000217711354244100700234540ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # This is a Python 2.6- version of the same file at level up # from pysnmp.hlapi.asyncore import cmdgen from pysnmp.hlapi.varbinds import * from pysnmp.proto.rfc1905 import endOfMibView from pysnmp.proto import errind from pyasn1.type.univ import Null __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'next'] # noinspection PyShadowingBuiltins def next(iter): return iter.next() def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cbCtx = {} if varBinds: cmdgen.getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] varBinds = cbCtx['varBinds'] else: errorIndication = errorStatus = errorIndex = None varBinds = [] yield errorIndication, errorStatus, errorIndex, varBinds def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cbCtx = {} while True: cmdgen.setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() yield (cbCtx['errorIndication'], cbCtx['errorStatus'], cbCtx['errorIndex'], cbCtx['varBinds']) if cbCtx['errorIndication'] != errind.requestTimedOut: break def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBindTable'] = varBindTable lexicographicMode = options.get('lexicographicMode', True) ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False) maxRows = options.get('maxRows', 0) maxCalls = options.get('maxCalls', 0) cbCtx = {} vbProcessor = CommandGeneratorVarBinds() initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] totalRows = totalCalls = 0 while True: cmdgen.nextCmd(snmpEngine, authData, transportTarget, contextData, *[(x[0], Null('')) for x in varBinds], **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] if ignoreNonIncreasingOid and errorIndication and \ isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: yield errorIndication, errorStatus, errorIndex, varBinds if errorIndication != errind.requestTimedOut: return elif errorStatus: if errorStatus == 2: # Hide SNMPv1 noSuchName error which leaks in here # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) yield errorIndication, errorStatus, errorIndex, varBinds return else: varBinds = cbCtx['varBindTable'] and cbCtx['varBindTable'][0] for idx, varBind in enumerate(varBinds): name, val = varBind if not isinstance(val, Null): if lexicographicMode or initialVars[idx].isPrefixOf(name): break else: return totalRows += 1 totalCalls += 1 yield errorIndication, errorStatus, errorIndex, varBinds if maxRows and totalRows >= maxRows or \ maxCalls and totalCalls >= maxCalls: return def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBindTable'] = varBindTable lexicographicMode = options.get('lexicographicMode', True) ignoreNonIncreasingOid = options.get('ignoreNonIncreasingOid', False) maxRows = options.get('maxRows', 0) maxCalls = options.get('maxCalls', 0) cbCtx = {} vbProcessor = CommandGeneratorVarBinds() initialVars = [x[0] for x in vbProcessor.makeVarBinds(snmpEngine, varBinds)] nullVarBinds = [False] * len(initialVars) totalRows = totalCalls = 0 stopFlag = False while not stopFlag: if maxRows and totalRows < maxRows: maxRepetitions = min(maxRepetitions, maxRows - totalRows) cmdgen.bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *[(x[0], Null('')) for x in varBinds], **dict(cbFun=cbFun, cbCtx=cbCtx, lookupMib=options.get('lookupMib', True))) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx['errorIndication'] errorStatus = cbCtx['errorStatus'] errorIndex = cbCtx['errorIndex'] varBindTable = cbCtx['varBindTable'] if ignoreNonIncreasingOid and errorIndication and \ isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or []) if errorIndication != errind.requestTimedOut: return elif errorStatus: if errorStatus == 2: # Hide SNMPv1 noSuchName error which leaks in here # from SNMPv1 Agent through internal pysnmp proxy. errorStatus = errorStatus.clone(0) errorIndex = errorIndex.clone(0) yield (errorIndication, errorStatus, errorIndex, varBindTable and varBindTable[0] or []) return else: for i in range(len(varBindTable)): stopFlag = True if len(varBindTable[i]) != len(initialVars): varBindTable = i and varBindTable[:i - 1] or [] break for j in range(len(varBindTable[i])): name, val = varBindTable[i][j] if nullVarBinds[j]: varBindTable[i][j] = name, endOfMibView continue stopFlag = False if isinstance(val, Null): nullVarBinds[j] = True elif not lexicographicMode and \ not initialVars[j].isPrefixOf(name): varBindTable[i][j] = name, endOfMibView nullVarBinds[j] = True if stopFlag: varBindTable = i and varBindTable[:i - 1] or [] break totalRows += len(varBindTable) totalCalls += 1 if maxRows and totalRows >= maxRows: if totalRows > maxRows: varBindTable = varBindTable[:-(totalRows - maxRows)] stopFlag = True if maxCalls and totalCalls >= maxCalls: stopFlag = True for varBinds in varBindTable: yield errorIndication, errorStatus, errorIndex, varBinds pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/compat/ntforg.py000066400000000000000000000030411354244100700235040ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # This is a Python 2.6- version of the same file at level up # from pysnmp.hlapi.asyncore import ntforg __all__ = ['sendNotification', 'next'] # noinspection PyShadowingBuiltins def next(iter): return iter.next() # # Synchronous one-liner SNMP Notification Originator application # def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cbCtx = {} if varBinds: ntforg.sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, cbFun, cbCtx, options.get('lookupMib', True)) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx.get('errorIndication') errorStatus = cbCtx.get('errorStatus') errorIndex = cbCtx.get('errorIndex') varBinds = cbCtx.get('varBinds', []) else: errorIndication = errorStatus = errorIndex = None varBinds = [] yield errorIndication, errorStatus, errorIndex, varBinds pysnmp-4.4.12/pysnmp/hlapi/asyncore/sync/ntforg.py000066400000000000000000000111341354244100700222230ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from sys import version_info from pysnmp.hlapi.asyncore import ntforg __all__ = ['sendNotification'] if version_info[:2] < (2, 6): __all__.append('next') # noinspection PyShadowingBuiltins def next(iter): return iter.next() def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): """Creates a generator to send one or more SNMP notifications. On each iteration, new SNMP TRAP or INFORM notification is send (:RFC:`1905#section-4,2,6`). The iterator blocks waiting for INFORM acknowlegement to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. notifyType : str Indicates type of notification to be sent. Recognized literal values are *trap* or *inform*. varBinds: tuple Single :py:class:`~pysnmp.smi.rfc1902.NotificationType` class instance representing a minimum sequence of MIB variables required for particular notification type. Alternatively, a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects could be passed instead. In the latter case it is up to the user to ensure proper Notification PDU contents. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Yields ------ errorIndication : str True value indicates SNMP engine error. errorStatus : str True value indicates SNMP PDU error. errorIndex : int Non-zero value refers to `varBinds[errorIndex-1]` varBinds : tuple A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- The `sendNotification` generator will be exhausted immidiately unless an instance of :py:class:`~pysnmp.smi.rfc1902.NotificationType` class or a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` `varBinds` are send back into running generator (supported since Python 2.6). Examples -------- >>> from pysnmp.hlapi import * >>> g = sendNotification(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'trap', ... NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))) >>> next(g) (None, 0, 0, []) >>> """ # noinspection PyShadowingNames def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx['errorIndication'] = errorIndication cbCtx['errorStatus'] = errorStatus cbCtx['errorIndex'] = errorIndex cbCtx['varBinds'] = varBinds cbCtx = {} while True: if varBinds: ntforg.sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, cbFun, cbCtx, lookupMib=options.get('lookupMib', True)) snmpEngine.transportDispatcher.runDispatcher() errorIndication = cbCtx.get('errorIndication') errorStatus = cbCtx.get('errorStatus') errorIndex = cbCtx.get('errorIndex') varBinds = cbCtx.get('varBinds', []) else: errorIndication = errorStatus = errorIndex = None varBinds = [] varBinds = (yield errorIndication, errorStatus, errorIndex, varBinds) if not varBinds: break pysnmp-4.4.12/pysnmp/hlapi/asyncore/transport.py000066400000000000000000000117731354244100700220150ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket import sys from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pysnmp.hlapi.transport import AbstractTransportTarget from pysnmp import error __all__ = ['UnixTransportTarget', 'Udp6TransportTarget', 'UdpTransportTarget'] class UdpTransportTarget(AbstractTransportTarget): """Creates UDP/IPv4 configuration entry and initialize socket API if needed. This object can be used for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`1906#section-3` for more information on the UDP transport mapping. Parameters ---------- transportAddr: :py:class:`tuple` Indicates remote address in Python :py:mod:`socket` module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv4 address in quad-dotted form, port is an integer. timeout: :py:class:`int` Response timeout in seconds. retries: :py:class:`int` Maximum number of request retries, 0 retries means just a single request. tagList: :py:class:`str` Arbitrary string that contains a list of space-separated tag strings used to select target addresses and/or SNMP configuration (see :RFC:`3413#section-4.1.1`, :RFC:`2576#section-5.3` and :py:class:`~pysnmp.hlapi.CommunityData` object). Examples -------- >>> from pysnmp.hlapi.asyncore import UdpTransportTarget >>> UdpTransportTarget(('demo.snmplabs.com', 161)) UdpTransportTarget(('195.218.195.228', 161), timeout=1, retries=5, tagList='') >>> """ transportDomain = udp.domainName protoTransport = udp.UdpSocketTransport def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], transportAddr[1], socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) class Udp6TransportTarget(AbstractTransportTarget): """Creates UDP/IPv6 configuration entry and initialize socket API if needed. This object can be used for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`1906#section-3`, :RFC:`2851#section-4` for more information on the UDP and IPv6 transport mapping. Parameters ---------- transportAddr : tuple Indicates remote address in Python :py:mod:`socket` module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv6 address in one of three conventional forms (:RFC:`1924#section-3`), port is an integer. timeout : int Response timeout in seconds. retries : int Maximum number of request retries, 0 retries means just a single request. tagList : str Arbitrary string that contains a list of tag values which are used to select target addresses for a particular operation (:RFC:`3413#section-4.1.4`). Examples -------- >>> from pysnmp.hlapi.asyncore import Udp6TransportTarget >>> Udp6TransportTarget(('google.com', 161)) Udp6TransportTarget(('2a00:1450:4014:80a::100e', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 161)) Udp6TransportTarget(('fedc:ba98:7654:3210:fedc:ba98:7654:3210', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('1080:0:0:0:8:800:200C:417A', 161)) Udp6TransportTarget(('1080::8:800:200c:417a', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('::0', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList='') >>> Udp6TransportTarget(('::', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList='') >>> """ transportDomain = udp6.domainName protoTransport = udp6.Udp6SocketTransport def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], transportAddr[1], socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) class UnixTransportTarget(AbstractTransportTarget): transportDomain = unix.domainName protoTransport = unix.UnixSocketTransport pysnmp-4.4.12/pysnmp/hlapi/auth.py000066400000000000000000000434251354244100700170760ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.entity import config from pysnmp import error from pyasn1.compat.octets import null __all__ = ['CommunityData', 'UsmUserData', 'usm3DESEDEPrivProtocol', 'usmAesCfb128Protocol', 'usmAesCfb192Protocol', 'usmAesCfb256Protocol', 'usmAesBlumenthalCfb192Protocol', 'usmAesBlumenthalCfb256Protocol', 'usmDESPrivProtocol', 'usmHMACMD5AuthProtocol', 'usmHMACSHAAuthProtocol', 'usmHMAC128SHA224AuthProtocol', 'usmHMAC192SHA256AuthProtocol', 'usmHMAC256SHA384AuthProtocol', 'usmHMAC384SHA512AuthProtocol', 'usmNoAuthProtocol', 'usmNoPrivProtocol'] class CommunityData(object): """Creates SNMP v1/v2c configuration entry. This object can be used by :py:class:`~pysnmp.hlapi.asyncore.AsyncCommandGenerator` or :py:class:`~pysnmp.hlapi.asyncore.AsyncNotificationOriginator` and their derivatives for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`2576#section-5.3` for more information on the *SNMP-COMMUNITY-MIB::snmpCommunityTable*. Parameters ---------- communityIndex: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` Unique index value of a row in snmpCommunityTable. If it is the only positional parameter, it is treated as a *communityName*. communityName: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` SNMP v1/v2c community string. mpModel: :py:class:`int` SNMP message processing model AKA SNMP version. Known SNMP versions are: * `0` - for SNMP v1 * `1` - for SNMP v2c (default) contextEngineId: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` Indicates the location of the context in which management information is accessed when using the community string specified by the above communityName. contextName: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` The context in which management information is accessed when using the above communityName. tag: :py:class:`str` Arbitrary string that specifies a set of transport endpoints from which a command responder application will accept management requests with given *communityName* or to which notification originator application will send notifications when targets are specified by a tag value(s). The other way to look at the *tag* feature is that it can make specific *communityName* only valid for certain targets. The other use-case is when multiple distinct SNMP peers share the same *communityName* -- binding each instance of *communityName* to transport endpoint lets you distinguish SNMP peers from each other (e.g. resolving *communityName* into proper *securityName*). For more technical information on SNMP configuration tags please refer to :RFC:`3413#section-4.1.1` and :RFC:`2576#section-5.3` (e.g. the *snmpCommunityTransportTag* object). See also: :py:class:`~pysnmp.hlapi.UdpTransportTarget` Warnings -------- If the same *communityIndex* value is supplied repeatedly with different *communityName* (or other parameters), the later call supersedes all previous calls. Make sure not to configure duplicate *communityName* values unless they have distinct *mpModel* and/or *tag* fields. This will make *communityName* based database lookup ambiguous. Examples -------- >>> from pysnmp.hlapi import CommunityData >>> CommunityData('public') CommunityData(communityIndex='s1410706889', communityName=, mpModel=1, contextEngineId=None, contextName='', tag='') >>> CommunityData('public', 'public') CommunityData(communityIndex='public', communityName=, mpModel=1, contextEngineId=None, contextName='', tag='') >>> """ mpModel = 1 # Default is SMIv2 securityModel = mpModel + 1 securityLevel = 'noAuthNoPriv' contextName = null tag = null def __init__(self, communityIndex, communityName=None, mpModel=None, contextEngineId=None, contextName=None, tag=None, securityName=None): if mpModel is not None: self.mpModel = mpModel self.securityModel = mpModel + 1 self.contextEngineId = contextEngineId if contextName is not None: self.contextName = contextName if tag is not None: self.tag = tag # a single arg is considered as a community name if communityName is None: communityName, communityIndex = communityIndex, None self.communityName = communityName # Autogenerate communityIndex if not specified if communityIndex is None: self.communityIndex = self.securityName = 's%s' % hash( (self.communityName, self.mpModel, self.contextEngineId, self.contextName, self.tag) ) else: self.communityIndex = communityIndex self.securityName = securityName is not None and securityName or communityIndex def __hash__(self): raise TypeError('%s is not hashable' % self.__class__.__name__) def __repr__(self): return '%s(communityIndex=%r, communityName=, mpModel=%r, contextEngineId=%r, contextName=%r, tag=%r, securityName=%r)' % ( self.__class__.__name__, self.communityIndex, self.mpModel, self.contextEngineId, self.contextName, self.tag, self.securityName ) def clone(self, communityIndex=None, communityName=None, mpModel=None, contextEngineId=None, contextName=None, tag=None, securityName=None): # a single arg is considered as a community name if communityName is None: communityName, communityIndex = communityIndex, None return self.__class__( communityIndex, communityName is None and self.communityName or communityName, mpModel is None and self.mpModel or mpModel, contextEngineId is None and self.contextEngineId or contextEngineId, contextName is None and self.contextName or contextName, tag is None and self.tag or tag, securityName is None and self.securityName or securityName ) usmNoAuthProtocol = config.usmNoAuthProtocol """No Authentication Protocol""" usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol """The HMAC-MD5-96 Digest Authentication Protocol (:RFC:`3414#section-6`)""" usmHMACSHAAuthProtocol = config.usmHMACSHAAuthProtocol """The HMAC-SHA-96 Digest Authentication Protocol AKA SHA-1 (:RFC:`3414#section-7`)""" usmHMAC128SHA224AuthProtocol = config.usmHMAC128SHA224AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmHMAC192SHA256AuthProtocol = config.usmHMAC192SHA256AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmHMAC256SHA384AuthProtocol = config.usmHMAC256SHA384AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmHMAC384SHA512AuthProtocol = config.usmHMAC384SHA512AuthProtocol """The HMAC-SHA-2 Digest Authentication Protocols (:RFC:`7860`)""" usmNoPrivProtocol = config.usmNoPrivProtocol """No Privacy Protocol""" usmDESPrivProtocol = config.usmDESPrivProtocol """The CBC-DES Symmetric Encryption Protocol (:RFC:`3414#section-8`)""" usm3DESEDEPrivProtocol = config.usm3DESEDEPrivProtocol """The 3DES-EDE Symmetric Encryption Protocol (`draft-reeder-snmpv3-usm-3desede-00 `_)""" usmAesCfb128Protocol = config.usmAesCfb128Protocol """The CFB128-AES-128 Symmetric Encryption Protocol (:RFC:`3826#section-3`)""" usmAesCfb192Protocol = config.usmAesCfb192Protocol """The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_) with Reeder key localization""" usmAesCfb256Protocol = config.usmAesCfb256Protocol """The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_) with Reeder key localization""" usmAesBlumenthalCfb192Protocol = config.usmAesBlumenthalCfb192Protocol """The CFB128-AES-192 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_)""" usmAesBlumenthalCfb256Protocol = config.usmAesBlumenthalCfb256Protocol """The CFB128-AES-256 Symmetric Encryption Protocol (`draft-blumenthal-aes-usm-04 `_)""" usmKeyTypePassphrase = config.usmKeyTypePassphrase """USM key material type - plain-text pass phrase (:RFC:`3414#section-2.6`)""" usmKeyTypeMaster = config.usmKeyTypeMaster """USM key material type - hashed pass-phrase AKA master key (:RFC:`3414#section-2.6`)""" usmKeyTypeLocalized = config.usmKeyTypeLocalized """USM key material type - hashed pass-phrase hashed with Context SNMP Engine ID (:RFC:`3414#section-2.6`)""" class UsmUserData(object): """Creates SNMP v3 User Security Model (USM) configuration entry. This object can be used by :py:class:`~pysnmp.hlapi.asyncore.AsyncCommandGenerator` or :py:class:`~pysnmp.hlapi.asyncore.AsyncNotificationOriginator` and their derivatives for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`3414#section-5` for more information on the *SNMP-USER-BASED-SM-MIB::usmUserTable*. Parameters ---------- userName: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` A human readable string representing the name of the SNMP USM user. Other Parameters ---------------- authKey: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` Initial value of the secret authentication key. If not set, :py:class:`~pysnmp.hlapi.usmNoAuthProtocol` is implied. If set and no *authProtocol* is specified, :py:class:`~pysnmp.hlapi.usmHMACMD5AuthProtocol` takes effect. privKey: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` Initial value of the secret encryption key. If not set, :py:class:`~pysnmp.hlapi.usmNoPrivProtocol` is implied. If set and no *privProtocol* is specified, :py:class:`~pysnmp.hlapi.usmDESPrivProtocol` takes effect. authProtocol: :py:class:`tuple`, :py:class:`~pysnmp.proto.rfc1902.ObjectIdentifier` An indication of whether messages sent on behalf of this USM user can be authenticated, and if so, the type of authentication protocol which is used. Supported authentication protocol identifiers are: * :py:class:`~pysnmp.hlapi.usmNoAuthProtocol` (default is *authKey* not given) * :py:class:`~pysnmp.hlapi.usmHMACMD5AuthProtocol` (default if *authKey* is given) * :py:class:`~pysnmp.hlapi.usmHMACSHAAuthProtocol` * :py:class:`~pysnmp.hlapi.usmHMAC128SHA224AuthProtocol` * :py:class:`~pysnmp.hlapi.usmHMAC192SHA256AuthProtocol` * :py:class:`~pysnmp.hlapi.usmHMAC256SHA384AuthProtocol` * :py:class:`~pysnmp.hlapi.usmHMAC384SHA512AuthProtocol` securityEngineId: :py:class:`~pysnmp.proto.rfc1902.OctetString` The snmpEngineID of the authoritative SNMP engine to which a dateRequest message is to be sent. Will be automatically discovered from peer if not given, unless localized keys are used. In the latter case *securityEngineId* must be specified. See :RFC:`3414#section-2.5.1` for technical explanation. securityName: :py:class:`str`, :py:class:`~pysnmp.proto.rfc1902.OctetString` Together with the snmpEngineID it identifies a row in the *SNMP-USER-BASED-SM-MIB::usmUserTable* that is to be used for securing the message. See :RFC:`3414#section-2.5.1` for technical explanation. privProtocol: :py:class:`tuple`, :py:class:`~pysnmp.proto.rfc1902.ObjectIdentifier` An indication of whether messages sent on behalf of this USM user be encrypted, and if so, the type of encryption protocol which is used. Supported encryption protocol identifiers are: * :py:class:`~pysnmp.hlapi.usmNoPrivProtocol` (default is *authKey* not given) * :py:class:`~pysnmp.hlapi.usmDESPrivProtocol` (default if *authKey* is given) * :py:class:`~pysnmp.hlapi.usm3DESEDEPrivProtocol` * :py:class:`~pysnmp.hlapi.usmAesCfb128Protocol` * :py:class:`~pysnmp.hlapi.usmAesCfb192Protocol` * :py:class:`~pysnmp.hlapi.usmAesCfb256Protocol` authKeyType: :py:class:`int` Type of `authKey` material. See :RFC:`3414#section-2.6` for technical explanation. Supported key types are: * :py:class:`~pysnmp.hlapi.usmKeyTypePassphrase` (default) * :py:class:`~pysnmp.hlapi.usmKeyTypeMaster` * :py:class:`~pysnmp.hlapi.usmKeyTypeLocalized` privKeyType: :py:class:`int` Type of `privKey` material. See :RFC:`3414#section-2.6` for technical explanation. Supported key types are: * :py:class:`~pysnmp.hlapi.usmKeyTypePassphrase` (default) * :py:class:`~pysnmp.hlapi.usmKeyTypeMaster` * :py:class:`~pysnmp.hlapi.usmKeyTypeLocalized` Notes ----- If :py:class:`~pysnmp.hlapi.usmKeyTypeLocalized` is used when running a non-authoritative SNMP engine, USM key localization mechanism is not invoked. As a consequence, local SNMP engine configuration won't get automatically populated with remote SNMP engine's *securityEngineId*. Therefore peer SNMP engine's *securityEngineId* must be added to local configuration and associated with its localized keys. Alternatively, the magic *securityEngineId* value of five zeros (*0x0000000000*) can be used to refer to the localized keys that should be used with any unknown remote SNMP engine. This feature is specific to pysnmp. Examples -------- >>> from pysnmp.hlapi import UsmUserData >>> UsmUserData('testuser', authKey='authenticationkey') UsmUserData(userName='testuser', authKey=, privKey=, authProtocol=(1,3,6,1,6,3,10,1,1,2), privProtocol=(1,3,6,1,6,3,10,1,2,1)) >>> UsmUserData('testuser', authKey='authenticationkey', privKey='encryptionkey') UsmUserData(userName='testuser', authKey=, privKey=, authProtocol=(1,3,6,1,6,3,10,1,1,2), privProtocol=(1,3,6,1,6,3,10,1,2,2)) >>> """ authKey = privKey = None authProtocol = config.usmNoAuthProtocol privProtocol = config.usmNoPrivProtocol securityLevel = 'noAuthNoPriv' securityModel = 3 mpModel = 3 contextName = null def __init__(self, userName, authKey=None, privKey=None, authProtocol=None, privProtocol=None, securityEngineId=None, securityName=None, authKeyType=usmKeyTypePassphrase, privKeyType=usmKeyTypePassphrase): self.userName = userName if securityName is None: self.securityName = userName else: self.securityName = securityName if authKey is not None: self.authKey = authKey if authProtocol is None: self.authProtocol = config.usmHMACMD5AuthProtocol else: self.authProtocol = authProtocol if self.securityLevel != 'authPriv': self.securityLevel = 'authNoPriv' if privKey is not None: self.privKey = privKey if self.authProtocol == config.usmNoAuthProtocol: raise error.PySnmpError('Privacy implies authenticity') self.securityLevel = 'authPriv' if privProtocol is None: self.privProtocol = config.usmDESPrivProtocol else: self.privProtocol = privProtocol self.securityEngineId = securityEngineId self.authKeyType = authKeyType self.privKeyType = privKeyType def __hash__(self): raise TypeError('%s is not hashable' % self.__class__.__name__) def __repr__(self): return '%s(userName=%r, authKey=, privKey=, authProtocol=%r, privProtocol=%r, securityEngineId=%r, securityName=%r, authKeyType=%r, privKeyType=%r)' % ( self.__class__.__name__, self.userName, self.authProtocol, self.privProtocol, self.securityEngineId is None and '' or self.securityEngineId, self.securityName, self.authKeyType, self.privKeyType ) def clone(self, userName=None, authKey=None, privKey=None, authProtocol=None, privProtocol=None, securityEngineId=None, securityName=None, authKeyType=None, privKeyType=None): return self.__class__( userName is None and self.userName or userName, authKey is None and self.authKey or authKey, privKey is None and self.privKey or privKey, authProtocol is None and self.authProtocol or authProtocol, privProtocol is None and self.privProtocol or privProtocol, securityEngineId is None and self.securityEngineId or securityEngineId, securityName is None and self.securityName or securityName, authKeyType is None and self.authKeyType or usmKeyTypePassphrase, privKeyType is None and self.privKeyType or usmKeyTypePassphrase ) pysnmp-4.4.12/pysnmp/hlapi/context.py000066400000000000000000000037771354244100700176270ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.compat.octets import null __all__ = ['ContextData'] class ContextData(object): """Creates UDP/IPv6 configuration entry and initialize socket API if needed. This object can be used by :py:class:`~pysnmp.hlapi.asyncore.AsyncCommandGenerator` or :py:class:`~pysnmp.hlapi.asyncore.AsyncNotificationOriginator` and their derevatives for forming SNMP PDU and also adding new entries to Local Configuration Datastore (LCD) in order to support SNMPv1/v2c with SNMPv3 interoperability. See :RFC:`3411#section-4.1` for SNMP Context details. Parameters ---------- contextEngineId : str Uniquely identifies an SNMP entity that may realize an instance of a MIB with a particular contextName (:RFC:`3411#section-3.3.2`). More frequently than not, ContextEngineID is the same as authoritative SnmpEngineID, however if SNMP Engine serves multiple SNMP Entities, their ContextEngineIDs would be distinct. Default is authoritative SNMP Engine ID. contextName : str Used to name an instance of MIB (:RFC:`3411#section-3.3.3`). Default is empty string. Examples -------- >>> from pysnmp.hlapi import ContextData >>> ContextData() ContextData(contextEngineId=None, contextName='') >>> ContextData(OctetString(hexValue='01020ABBA0')) ContextData(contextEngineId=OctetString(hexValue='01020abba0'), contextName='') >>> ContextData(contextName='mycontext') ContextData(contextEngineId=None, contextName='mycontext') """ def __init__(self, contextEngineId=None, contextName=null): self.contextEngineId = contextEngineId self.contextName = contextName def __repr__(self): return '%s(contextEngineId=%r, contextName=%r)' % ( self.__class__.__name__, self.contextEngineId, self.contextName ) pysnmp-4.4.12/pysnmp/hlapi/lcd.py000066400000000000000000000270231354244100700166730ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.entity import config from pysnmp import nextid, error from pysnmp.hlapi.auth import * from pyasn1.compat.octets import null __all__ = ['CommandGeneratorLcdConfigurator', 'NotificationOriginatorLcdConfigurator'] class AbstractLcdConfigurator(object): nextID = nextid.Integer(0xffffffff) cacheKeys = [] def _getCache(self, snmpEngine): cacheId = self.__class__.__name__ cache = snmpEngine.getUserContext(cacheId) if cache is None: cache = dict([(x, {}) for x in self.cacheKeys]) snmpEngine.setUserContext(**{cacheId: cache}) return cache def configure(self, snmpEngine, *args, **kwargs): pass def unconfigure(self, snmpEngine, *args, **kwargs): pass class CommandGeneratorLcdConfigurator(AbstractLcdConfigurator): cacheKeys = ['auth', 'parm', 'tran', 'addr'] def configure(self, snmpEngine, authData, transportTarget, contextName, **options): cache = self._getCache(snmpEngine) if isinstance(authData, CommunityData): if authData.communityIndex not in cache['auth']: config.addV1System( snmpEngine, authData.communityIndex, authData.communityName, authData.contextEngineId, authData.contextName, authData.tag, authData.securityName ) cache['auth'][authData.communityIndex] = authData elif isinstance(authData, UsmUserData): authDataKey = authData.userName, authData.securityEngineId if authDataKey not in cache['auth']: config.addV3User( snmpEngine, authData.userName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, securityEngineId=authData.securityEngineId, securityName=authData.securityName, authKeyType=authData.authKeyType, privKeyType=authData.privKeyType ) cache['auth'][authDataKey] = authData else: raise error.PySnmpError('Unsupported authentication object') paramsKey = (authData.securityName, authData.securityLevel, authData.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] cache['parm'][paramsKey] = paramsName, useCount + 1 else: paramsName = 'p%s' % self.nextID() config.addTargetParams( snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) cache['parm'][paramsKey] = paramsName, 1 if transportTarget.transportDomain in cache['tran']: transport, useCount = cache['tran'][transportTarget.transportDomain] transportTarget.verifyDispatcherCompatibility(snmpEngine) cache['tran'][transportTarget.transportDomain] = transport, useCount + 1 elif config.getTransport(snmpEngine, transportTarget.transportDomain): transportTarget.verifyDispatcherCompatibility(snmpEngine) else: transport = transportTarget.openClientMode() config.addTransport( snmpEngine, transportTarget.transportDomain, transport ) cache['tran'][transportTarget.transportDomain] = transport, 1 transportKey = (paramsName, transportTarget.transportDomain, transportTarget.transportAddr, transportTarget.timeout, transportTarget.retries, transportTarget.tagList, transportTarget.iface) if transportKey in cache['addr']: addrName, useCount = cache['addr'][transportKey] cache['addr'][transportKey] = addrName, useCount + 1 else: addrName = 'a%s' % self.nextID() config.addTargetAddr( snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, transportTarget.tagList ) cache['addr'][transportKey] = addrName, 1 return addrName, paramsName def unconfigure(self, snmpEngine, authData=None, contextName=null, **options): cache = self._getCache(snmpEngine) if authData: if isinstance(authData, CommunityData): authDataKey = authData.communityIndex elif isinstance(authData, UsmUserData): authDataKey = authData.userName, authData.securityEngineId else: raise error.PySnmpError('Unsupported authentication object') if authDataKey in cache['auth']: authDataKeys = (authDataKey,) else: raise error.PySnmpError('Unknown authData %s' % (authData,)) else: authDataKeys = list(cache['auth'].keys()) addrNames, paramsNames = set(), set() for authDataKey in authDataKeys: authDataX = cache['auth'][authDataKey] del cache['auth'][authDataKey] if isinstance(authDataX, CommunityData): config.delV1System( snmpEngine, authDataX.communityIndex ) elif isinstance(authDataX, UsmUserData): config.delV3User( snmpEngine, authDataX.userName, authDataX.securityEngineId ) else: raise error.PySnmpError('Unsupported authentication object') paramsKey = (authDataX.securityName, authDataX.securityLevel, authDataX.mpModel) if paramsKey in cache['parm']: paramsName, useCount = cache['parm'][paramsKey] useCount -= 1 if useCount: cache['parm'][paramsKey] = paramsName, useCount else: del cache['parm'][paramsKey] config.delTargetParams( snmpEngine, paramsName ) paramsNames.add(paramsName) else: raise error.PySnmpError('Unknown target %s' % (paramsKey,)) addrKeys = [x for x in cache['addr'] if x[0] == paramsName] for addrKey in addrKeys: addrName, useCount = cache['addr'][addrKey] useCount -= 1 if useCount: cache['addr'][addrKey] = addrName, useCount else: config.delTargetAddr(snmpEngine, addrName) del cache['addr'][addrKey] addrNames.add(addrKey) if addrKey[1] in cache['tran']: transport, useCount = cache['tran'][addrKey[1]] if useCount > 1: useCount -= 1 cache['tran'][addrKey[1]] = transport, useCount else: config.delTransport(snmpEngine, addrKey[1]) transport.closeTransport() del cache['tran'][addrKey[1]] return addrNames, paramsNames class NotificationOriginatorLcdConfigurator(AbstractLcdConfigurator): cacheKeys = ['auth', 'name'] _cmdGenLcdCfg = CommandGeneratorLcdConfigurator() def configure(self, snmpEngine, authData, transportTarget, notifyType, contextName, **options): cache = self._getCache(snmpEngine) notifyName = None # Create matching transport tags if not given by user. Not good! if not transportTarget.tagList: transportTarget.tagList = str( hash((authData.securityName, transportTarget.transportAddr)) ) if isinstance(authData, CommunityData) and not authData.tag: authData.tag = transportTarget.tagList.split()[0] addrName, paramsName = self._cmdGenLcdCfg.configure( snmpEngine, authData, transportTarget, contextName, **options) tagList = transportTarget.tagList.split() if not tagList: tagList = [''] for tag in tagList: notifyNameKey = paramsName, tag, notifyType if notifyNameKey in cache['name']: notifyName, paramsName, useCount = cache['name'][notifyNameKey] cache['name'][notifyNameKey] = notifyName, paramsName, useCount + 1 else: notifyName = 'n%s' % self.nextID() config.addNotificationTarget( snmpEngine, notifyName, paramsName, tag, notifyType ) cache['name'][notifyNameKey] = notifyName, paramsName, 1 authDataKey = authData.securityName, authData.securityModel, authData.securityLevel, contextName if authDataKey in cache['auth']: authDataX, subTree, useCount = cache['auth'][authDataKey] cache['auth'][authDataKey] = authDataX, subTree, useCount + 1 else: subTree = (1, 3, 6) config.addTrapUser(snmpEngine, authData.securityModel, authData.securityName, authData.securityLevel, subTree, contextName=contextName) cache['auth'][authDataKey] = authData, subTree, 1 return notifyName def unconfigure(self, snmpEngine, authData=None, contextName=null, **options): cache = self._getCache(snmpEngine) if authData: authDataKey = authData.securityName, authData.securityModel, authData.securityLevel, contextName if authDataKey in cache['auth']: authDataKeys = (authDataKey,) else: raise error.PySnmpError('Unknown authData %s' % (authData,)) else: authDataKeys = tuple(cache['auth']) addrNames, paramsNames = self._cmdGenLcdCfg.unconfigure( snmpEngine, authData, contextName, **options) notifyAndParamsNames = [(cache['name'][x], x) for x in cache['name'].keys() if x[0] in paramsNames] for (notifyName, paramsName, useCount), notifyNameKey in notifyAndParamsNames: useCount -= 1 if useCount: cache['name'][notifyNameKey] = notifyName, paramsName, useCount else: config.delNotificationTarget( snmpEngine, notifyName, paramsName ) del cache['name'][notifyNameKey] for authDataKey in authDataKeys: authDataX, subTree, useCount = cache['auth'][authDataKey] useCount -= 1 if useCount: cache['auth'][authDataKey] = authDataX, subTree, useCount else: config.delTrapUser( snmpEngine, authDataX.securityModel, authDataX.securityName, authDataX.securityLevel, subTree ) del cache['auth'][authDataKey] pysnmp-4.4.12/pysnmp/hlapi/transport.py000066400000000000000000000035631354244100700201700ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.compat.octets import null from pysnmp.carrier.base import AbstractTransport from pysnmp import error __all__ = [] class AbstractTransportTarget(object): transportDomain = None protoTransport = AbstractTransport def __init__(self, transportAddr, timeout=1, retries=5, tagList=null): self.transportAddr = self._resolveAddr(transportAddr) self.timeout = timeout self.retries = retries self.tagList = tagList self.iface = None self.transport = None def __repr__(self): return '%s(%r, timeout=%r, retries=%r, tagList=%r)' % ( self.__class__.__name__, self.transportAddr, self.timeout, self.retries, self.tagList ) def getTransportInfo(self): return self.transportDomain, self.transportAddr def setLocalAddress(self, iface): """Set source address. Parameters ---------- iface : tuple Indicates network address of a local interface from which SNMP packets will be originated. Format is the same as of `transportAddress`. Returns ------- self """ self.iface = iface return self def openClientMode(self): self.transport = self.protoTransport().openClientMode(self.iface) return self.transport def verifyDispatcherCompatibility(self, snmpEngine): if not self.protoTransport.isCompatibleWithDispatcher(snmpEngine.transportDispatcher): raise error.PySnmpError('Transport %r is not compatible with dispatcher %r' % ( self.protoTransport, snmpEngine.transportDispatcher)) def _resolveAddr(self, transportAddr): raise NotImplementedError() pysnmp-4.4.12/pysnmp/hlapi/twisted/000077500000000000000000000000001354244100700172365ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/hlapi/twisted/__init__.py000066400000000000000000000004531354244100700213510ustar00rootroot00000000000000from pysnmp.proto.rfc1902 import * from pysnmp.smi.rfc1902 import * from pysnmp.entity.engine import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.twisted.transport import * from pysnmp.hlapi.twisted.cmdgen import * from pysnmp.hlapi.twisted.ntforg import * pysnmp-4.4.12/pysnmp/hlapi/twisted/cmdgen.py000066400000000000000000000513341354244100700210530ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.twisted.transport import * from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import errind from twisted.internet.defer import Deferred from twisted.python.failure import Failure __all__ = ['getCmd', 'nextCmd', 'setCmd', 'bulkCmd', 'isEndOfMib'] vbProcessor = CommandGeneratorVarBinds() lcd = CommandGeneratorLcdConfigurator() isEndOfMib = lambda x: not cmdgen.getNextVarBinds(x)[1] def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GET query. Based on passed parameters, prepares SNMP GET packet (:RFC:`1905#section-4.2.1`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Returns ------- deferred : :class:`~twisted.internet.defer.Deferred` Twisted Deferred object representing work-in-progress. User is expected to attach his own `success` and `error` callback functions to the Deferred object though :meth:`~twisted.internet.defer.Deferred.addCallbacks` method. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- User `success` callback is called with the following tuple as its first argument: * errorStatus (str) : True value indicates SNMP PDU error. * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple) : A sequence of :class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. User `error` callback is called with `errorIndication` object wrapped in :class:`~twisted.python.failure.Failure` object. Examples -------- >>> from twisted.internet.task import react >>> from pysnmp.hlapi.twisted import * >>> >>> def success(args): ... (errorStatus, errorIndex, varBinds) = args ... print(errorStatus, errorIndex, varBind) ... >>> def failure(errorIndication): ... print(errorIndication) ... >>> def run(reactor): ... d = getCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) ... d.addCallback(success).addErrback(failure) ... return d ... >>> react(run) (0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, deferred = cbCtx if errorIndication: deferred.errback(Failure(errorIndication)) else: try: varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib) except Exception: ex = sys.exc_info()[1] deferred.errback(Failure(ex)) else: deferred.callback((errorStatus, errorIndex, varBindsUnmade)) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) deferred = Deferred() cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), deferred) ) return deferred def setCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP SET query. Based on passed parameters, prepares SNMP SET packet (:RFC:`1905#section-4.2.5`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Returns ------- deferred : :class:`~twisted.internet.defer.Deferred` Twisted Deferred object representing work-in-progress. User is expected to attach his own `success` and `error` callback functions to the Deferred object though :meth:`~twisted.internet.defer.Deferred.addCallbacks` method. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- User `success` callback is called with the following tuple as its first argument: * errorStatus (str) : True value indicates SNMP PDU error. * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple) : A sequence of :class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. User `error` callback is called with `errorIndication` object wrapped in :class:`~twisted.python.failure.Failure` object. Examples -------- >>> from twisted.internet.task import react >>> from pysnmp.hlapi.twisted import * >>> >>> def success(args): ... (errorStatus, errorIndex, varBinds) = args ... print(errorStatus, errorIndex, varBind) ... >>> def failure(errorIndication): ... print(errorIndication) ... >>> def run(reactor): ... d = setCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386') ... d.addCallback(success).addErrback(failure) ... return d ... >>> react(run) (0, 0, [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('Linux i386'))]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, deferred = cbCtx if errorIndication: deferred.errback(Failure(errorIndication)) else: try: varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib) except Exception: ex = sys.exc_info()[1] deferred.errback(Failure(ex)) else: deferred.callback((errorStatus, errorIndex, varBindsUnmade)) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) deferred = Deferred() cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), deferred) ) return deferred def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Performs SNMP GETNEXT query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.2`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. \*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `ignoreNonIncreasingOid` - continue iteration even if response MIB variables (OIDs) are not greater then request MIB variables. Be aware that setting it to `True` may cause infinite loop between SNMP management and agent applications. Default is `False`. Returns ------- deferred : :class:`~twisted.internet.defer.Deferred` Twisted Deferred object representing work-in-progress. User is expected to attach his own `success` and `error` callback functions to the Deferred object though :meth:`~twisted.internet.defer.Deferred.addCallbacks` method. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- User `success` callback is called with the following tuple as its first argument: * errorStatus (str) : True value indicates SNMP PDU error. * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple) : A sequence of sequences (e.g. 2-D array) of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing a table of MIB variables returned in SNMP response. Inner sequences represent table rows and ordered exactly the same as `varBinds` in request. Response to GETNEXT always contain a single row. User `error` callback is called with `errorIndication` object wrapped in :class:`~twisted.python.failure.Failure` object. Examples -------- >>> from twisted.internet.task import react >>> from pysnmp.hlapi.twisted import * >>> >>> def success(args): ... (errorStatus, errorIndex, varBindTable) = args ... print(errorStatus, errorIndex, varBindTable) ... >>> def failure(errorIndication): ... print(errorIndication) ... >>> def run(reactor): ... d = nextCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')) ... d.addCallback(success).addErrback(failure) ... return d ... >>> react(run) (0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))]]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, deferred = cbCtx if (options.get('ignoreNonIncreasingOid', False) and errorIndication and isinstance(errorIndication, errind.OidNotIncreasing)): errorIndication = None if errorIndication: deferred.errback(Failure(errorIndication)) else: try: varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable] except Exception: ex = sys.exc_info()[1] deferred.errback(Failure(ex)) else: deferred.callback((errorStatus, errorIndex, varBindsUnmade)) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) deferred = Deferred() cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), deferred) ) return deferred def bulkCmd(snmpEngine, authData, transportTarget, contextData, nonRepeaters, maxRepetitions, *varBinds, **options): """Performs SNMP GETBULK query. Based on passed parameters, prepares SNMP GETNEXT packet (:RFC:`1905#section-4.2.3`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :class:`~pysnmp.hlapi.CommunityData` or :class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :class:`~pysnmp.hlapi.twisted.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. nonRepeaters : int One MIB variable is requested in response for the first `nonRepeaters` MIB variables in request. maxRepetitions : int `maxRepetitions` MIB variables are requested in response for each of the remaining MIB variables in the request (e.g. excluding `nonRepeaters`). Remote SNMP engine may choose lesser value than requested. \*varBinds : :class:`~pysnmp.smi.rfc1902.ObjectType` One or more class instances representing MIB variables to place into SNMP request. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. * `ignoreNonIncreasingOid` - continue iteration even if response MIB variables (OIDs) are not greater then request MIB variables. Be aware that setting it to `True` may cause infinite loop between SNMP management and agent applications. Default is `False`. Returns ------- deferred : :class:`~twisted.internet.defer.Deferred` Twisted Deferred object representing work-in-progress. User is expected to attach his own `success` and `error` callback functions to the Deferred object though :meth:`~twisted.internet.defer.Deferred.addCallbacks` method. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- User `success` callback is called with the following tuple as its first argument: * errorStatus (str) : True value indicates SNMP PDU error. * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]` * varBindTable (tuple): A sequence of sequences (e.g. 2-D array) of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing a table of MIB variables returned in SNMP response, with up to ``maxRepetitions`` rows, i.e. ``len(varBindTable) <= maxRepetitions``. For ``0 <= i < len(varBindTable)`` and ``0 <= j < len(varBinds)``, ``varBindTable[i][j]`` represents: - For non-repeaters (``j < nonRepeaters``), the first lexicographic successor of ``varBinds[j]``, regardless the value of ``i``, or an :py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the :py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor exists; - For repeaters (``j >= nonRepeaters``), the ``i``-th lexicographic successor of ``varBinds[j]``, or an :py:class:`~pysnmp.smi.rfc1902.ObjectType` instance with the :py:obj:`~pysnmp.proto.rfc1905.endOfMibView` value if no such successor exists. See :rfc:`3416#section-4.2.3` for details on the underlying ``GetBulkRequest-PDU`` and the associated ``GetResponse-PDU``, such as specific conditions under which the server may truncate the response, causing ``varBindTable`` to have less than ``maxRepetitions`` rows. User `error` callback is called with `errorIndication` object wrapped in :class:`~twisted.python.failure.Failure` object. Examples -------- >>> from twisted.internet.task import react >>> from pysnmp.hlapi.twisted import * >>> >>> def success(args): ... (errorStatus, errorIndex, varBindTable) = args ... print(errorStatus, errorIndex, varBindTable) ... >>> def failure(errorIndication): ... print(errorIndication) ... >>> def run(reactor): ... d = bulkCmd(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 161)), ... ContextData(), ... 0, 2, ... ObjectType(ObjectIdentity('SNMPv2-MIB', 'system')) ... d.addCallback(success).addErrback(failure) ... return d ... >>> react(run) (0, 0, [[ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.1.0')), DisplayString('SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m'))], [ObjectType(ObjectIdentity(ObjectName('1.3.6.1.2.1.1.2.0')), ObjectIdentifier('1.3.6.1.4.1.424242.1.1'))]]) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupMib, deferred = cbCtx if options.get('ignoreNonIncreasingOid', False) and errorIndication and \ isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorIndication: deferred.errback(Failure(errorIndication)) else: try: varBindsUnmade = [vbProcessor.unmakeVarBinds(snmpEngine, varBindTableRow, lookupMib) for varBindTableRow in varBindTable] except Exception: ex = sys.exc_info()[1] deferred.errback(Failure(ex)) else: deferred.callback((errorStatus, errorIndex, varBindsUnmade)) addrName, paramsName = lcd.configure( snmpEngine, authData, transportTarget, contextData.contextName) deferred = Deferred() cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, addrName, contextData.contextEngineId, contextData.contextName, nonRepeaters, maxRepetitions, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), deferred) ) return deferred pysnmp-4.4.12/pysnmp/hlapi/twisted/ntforg.py000066400000000000000000000127001354244100700211070ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.smi.rfc1902 import * from pysnmp.hlapi.auth import * from pysnmp.hlapi.context import * from pysnmp.hlapi.lcd import * from pysnmp.hlapi.varbinds import * from pysnmp.hlapi.twisted.transport import * from pysnmp.entity.rfc3413 import ntforg from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.python.failure import Failure __all__ = ['sendNotification'] vbProcessor = NotificationOriginatorVarBinds() lcd = NotificationOriginatorLcdConfigurator() def sendNotification(snmpEngine, authData, transportTarget, contextData, notifyType, varBinds, **options): """Sends SNMP notification. Based on passed parameters, prepares SNMP TRAP or INFORM message (:RFC:`1905#section-4.2.6`) and schedules its transmission by :mod:`twisted` I/O framework at a later point of time. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class instance representing SNMP engine. authData : :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData` Class instance representing SNMP credentials. transportTarget : :py:class:`~pysnmp.hlapi.twisted.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.twisted.Udp6TransportTarget` Class instance representing transport type along with SNMP peer address. contextData : :py:class:`~pysnmp.hlapi.ContextData` Class instance representing SNMP ContextEngineId and ContextName values. notifyType : str Indicates type of notification to be sent. Recognized literal values are *trap* or *inform*. varBinds: tuple Single :py:class:`~pysnmp.smi.rfc1902.NotificationType` class instance representing a minimum sequence of MIB variables required for particular notification type. Alternatively, a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects could be passed instead. In the latter case it is up to the user to ensure proper Notification PDU contents. Other Parameters ---------------- \*\*options : Request options: * `lookupMib` - load MIB and resolve response MIB variables at the cost of slightly reduced performance. Default is `True`. Returns ------- deferred : :class:`~twisted.internet.defer.Deferred` Twisted Deferred object representing work-in-progress. User is expected to attach his own `success` and `error` callback functions to the Deferred object though :meth:`~twisted.internet.defer.Deferred.addCallbacks` method. Raises ------ PySnmpError Or its derivative indicating that an error occurred while performing SNMP operation. Notes ----- User `success` callback is called with the following tuple as its first argument: * errorStatus (str) : True value indicates SNMP PDU error. * errorIndex (int) : Non-zero value refers to `varBinds[errorIndex-1]` * varBinds (tuple) : A sequence of :class:`~pysnmp.smi.rfc1902.ObjectType` class instances representing MIB variables returned in SNMP response. User `error` callback is called with `errorIndication` object wrapped in :class:`~twisted.python.failure.Failure` object. Examples -------- >>> from twisted.internet.task import react >>> from pysnmp.hlapi.twisted import * >>> >>> def success(args): ... (errorStatus, errorIndex, varBinds) = args ... print(errorStatus, errorIndex, varBind) ... >>> def failure(errorIndication): ... print(errorIndication) ... >>> def run(reactor): ... d = sendNotification(SnmpEngine(), ... CommunityData('public'), ... UdpTransportTarget(('demo.snmplabs.com', 162)), ... ContextData(), ... 'trap', ... NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))) ... d.addCallback(success).addErrback(failure) ... return d ... >>> react(run) (0, 0, []) >>> """ def __cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupMib, deferred = cbCtx if errorIndication: deferred.errback(Failure(errorIndication)) else: try: varBindsUnmade = vbProcessor.unmakeVarBinds(snmpEngine, varBinds, lookupMib) except Exception: ex = sys.exc_info()[1] deferred.errback(Failure(ex)) else: deferred.callback((errorStatus, errorIndex, varBindsUnmade)) notifyName = lcd.configure(snmpEngine, authData, transportTarget, notifyType, contextData.contextName) def __trapFun(deferred): deferred.callback((0, 0, [])) deferred = Deferred() ntforg.NotificationOriginator().sendVarBinds( snmpEngine, notifyName, contextData.contextEngineId, contextData.contextName, vbProcessor.makeVarBinds(snmpEngine, varBinds), __cbFun, (options.get('lookupMib', True), deferred) ) if notifyType == 'trap': reactor.callLater(0, __trapFun, deferred) return deferred pysnmp-4.4.12/pysnmp/hlapi/twisted/transport.py000066400000000000000000000042521354244100700216470ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import socket, sys from pysnmp.carrier.twisted.dgram import udp from pysnmp.hlapi.transport import AbstractTransportTarget from pysnmp.error import PySnmpError __all__ = ['UdpTransportTarget'] class UdpTransportTarget(AbstractTransportTarget): """Creates UDP/IPv4 configuration entry and initialize socket API if needed. This object can be used for adding new entries to Local Configuration Datastore (LCD) managed by :py:class:`~pysnmp.hlapi.SnmpEngine` class instance. See :RFC:`1906#section-3` for more information on the UDP transport mapping. Parameters ---------- transportAddr : tuple Indicates remote address in Python :py:mod:`socket` module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv4 address in quad-dotted form, port is an integer. timeout : int Response timeout in seconds. retries : int Maximum number of request retries, 0 retries means just a single request. tagList : str Arbitrary string that contains a list of tag values which are used to select target addresses for a particular operation (:RFC:`3413#section-4.1.4`). Examples -------- >>> from pysnmp.hlapi.twisted import UdpTransportTarget >>> UdpTransportTarget(('demo.snmplabs.com', 161)) UdpTransportTarget(('195.218.195.228', 161), timeout=1, retries=5, tagList='') >>> """ transportDomain = udp.domainName protoTransport = udp.UdpTwistedTransport def _resolveAddr(self, transportAddr): try: return socket.getaddrinfo(transportAddr[0], transportAddr[1], socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror: raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) pysnmp-4.4.12/pysnmp/hlapi/varbinds.py000066400000000000000000000055551354244100700177470ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.smi import view from pysnmp.smi.rfc1902 import * __all__ = ['CommandGeneratorVarBinds', 'NotificationOriginatorVarBinds'] class AbstractVarBinds(object): @staticmethod def getMibViewController(snmpEngine): mibViewController = snmpEngine.getUserContext('mibViewController') if not mibViewController: mibViewController = view.MibViewController( snmpEngine.getMibBuilder() ) snmpEngine.setUserContext(mibViewController=mibViewController) return mibViewController class CommandGeneratorVarBinds(AbstractVarBinds): def makeVarBinds(self, snmpEngine, varBinds): mibViewController = self.getMibViewController(snmpEngine) __varBinds = [] for varBind in varBinds: if isinstance(varBind, ObjectType): pass elif isinstance(varBind[0], ObjectIdentity): varBind = ObjectType(*varBind) elif isinstance(varBind[0][0], tuple): # legacy varBind = ObjectType(ObjectIdentity(varBind[0][0][0], varBind[0][0][1], *varBind[0][1:]), varBind[1]) else: varBind = ObjectType(ObjectIdentity(varBind[0]), varBind[1]) __varBinds.append(varBind.resolveWithMib(mibViewController, ignoreErrors=False)) return __varBinds def unmakeVarBinds(self, snmpEngine, varBinds, lookupMib=True): if lookupMib: mibViewController = self.getMibViewController(snmpEngine) varBinds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib( mibViewController) for x in varBinds] return varBinds class NotificationOriginatorVarBinds(AbstractVarBinds): def makeVarBinds(self, snmpEngine, varBinds): mibViewController = self.getMibViewController(snmpEngine) if isinstance(varBinds, NotificationType): varBinds.resolveWithMib( mibViewController, ignoreErrors=False) __varBinds = [] for varBind in varBinds: if isinstance(varBind, ObjectType): pass elif isinstance(varBind[0], ObjectIdentity): varBind = ObjectType(*varBind) else: varBind = ObjectType(ObjectIdentity(varBind[0]), varBind[1]) __varBinds.append(varBind.resolveWithMib( mibViewController, ignoreErrors=False)) return __varBinds def unmakeVarBinds(self, snmpEngine, varBinds, lookupMib=False): if lookupMib: mibViewController = self.getMibViewController(snmpEngine) varBinds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib( mibViewController) for x in varBinds] return varBinds pysnmp-4.4.12/pysnmp/nextid.py000066400000000000000000000022621354244100700163250ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import random random.seed() class Integer(object): """Return a next value in a reasonably MT-safe manner""" 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 pysnmp-4.4.12/pysnmp/proto/000077500000000000000000000000001354244100700156215ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/__init__.py000066400000000000000000000000731354244100700177320ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/acmod/000077500000000000000000000000001354244100700167045ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/acmod/__init__.py000066400000000000000000000000731354244100700210150ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/acmod/rfc3415.py000066400000000000000000000300501354244100700203430ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.smi.error import NoSuchInstanceError from pysnmp.proto import errind, error from pysnmp import debug # 3.2 class Vacm(object): """View-based Access Control Model""" accessModelID = 3 _powOfTwoSeq = (128, 64, 32, 16, 8, 4, 2, 1) def __init__(self): self._contextBranchId = -1 self._groupNameBranchId = -1 self._accessBranchId = -1 self._viewTreeBranchId = -1 self._contextMap = {} self._groupNameMap = {} self._accessMap = {} self._viewTreeMap = {} def _addAccessEntry(self, groupName, contextPrefix, securityModel, securityLevel, prefixMatch, readView, writeView, notifyView): if not groupName: return groups = self._accessMap try: views = groups[groupName] except KeyError: views = groups[groupName] = {} for viewType, viewName in ( ('read', readView), ('write', writeView), ('notify', notifyView)): try: matches = views[viewType] except KeyError: matches = views[viewType] = {} try: contexts = matches[prefixMatch] except KeyError: contexts = matches[prefixMatch] = {} try: models = contexts[contextPrefix] except KeyError: models = contexts[contextPrefix] = {} try: levels = models[securityModel] except KeyError: levels = models[securityModel] = {} levels[securityLevel] = viewName def _getFamilyViewName(self, groupName, contextName, securityModel, securityLevel, viewType): groups = self._accessMap try: views = groups[groupName] except KeyError: raise error.StatusInformation(errorIndication=errind.noGroupName) try: matches = views[viewType] except KeyError: raise error.StatusInformation(errorIndication=errind.noAccessEntry) try: # vacmAccessTable #2: exact match shortcut return matches[1][contextName][securityModel][securityLevel] except KeyError: pass # vacmAccessTable #2: fuzzy look-up candidates = [] for match, names in matches.items(): for context, models in names.items(): if match == 1 and contextName != context: continue if match == 2 and contextName[:len(context)] != context: continue for model, levels in models.items(): for level, viewName in levels.items(): # priorities: # - matching securityModel # - exact context name match # - longer partial match # - highest securityLevel rating = securityModel == model, match == 1, len(context), level candidates.append((rating, viewName)) if not candidates: raise error.StatusInformation(errorIndication=errind.notInView) candidates.sort() rating, viewName = candidates[0] return viewName def isAccessAllowed(self, snmpEngine, securityModel, securityName, securityLevel, viewType, contextName, variableName): mibInstrumController = snmpEngine.msgAndPduDsp.mibInstrumController debug.logger & debug.flagACL and debug.logger( 'isAccessAllowed: securityModel %s, securityName %s, ' 'securityLevel %s, viewType %s, contextName %s for ' 'variableName %s' % (securityModel, securityName, securityLevel, viewType, contextName, variableName)) # Rebuild contextName map if changed vacmContextName, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextName') if self._contextBranchId != vacmContextName.branchVersionId: self._contextMap.clear() nextMibNode = vacmContextName while True: try: nextMibNode = vacmContextName.getNextNode(nextMibNode.name) except NoSuchInstanceError: break self._contextMap[nextMibNode.syntax] = True self._contextBranchId = vacmContextName.branchVersionId # 3.2.1 if contextName not in self._contextMap: raise error.StatusInformation(errorIndication=errind.noSuchContext) # Rebuild groupName map if changed vacmGroupName, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmGroupName') if self._groupNameBranchId != vacmGroupName.branchVersionId: vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry') self._groupNameMap.clear() nextMibNode = vacmGroupName while True: try: nextMibNode = vacmGroupName.getNextNode(nextMibNode.name) except NoSuchInstanceError: break instId = nextMibNode.name[len(vacmGroupName.name):] indices = vacmSecurityToGroupEntry.getIndicesFromInstId(instId) self._groupNameMap[indices] = nextMibNode.syntax self._groupNameBranchId = vacmGroupName.branchVersionId # 3.2.2 indices = securityModel, securityName try: groupName = self._groupNameMap[indices] except KeyError: raise error.StatusInformation(errorIndication=errind.noGroupName) # Rebuild access map if changed vacmAccessStatus, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessStatus') if self._accessBranchId != vacmAccessStatus.branchVersionId: (vacmAccessEntry, vacmAccessContextPrefix, vacmAccessSecurityModel, vacmAccessSecurityLevel, vacmAccessContextMatch, vacmAccessReadViewName, vacmAccessWriteViewName, vacmAccessNotifyViewName) = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry', 'vacmAccessContextPrefix', 'vacmAccessSecurityModel', 'vacmAccessSecurityLevel', 'vacmAccessContextMatch', 'vacmAccessReadViewName', 'vacmAccessWriteViewName', 'vacmAccessNotifyViewName') self._accessMap.clear() nextMibNode = vacmAccessStatus while True: try: nextMibNode = vacmAccessStatus.getNextNode(nextMibNode.name) except NoSuchInstanceError: break if nextMibNode.syntax != 1: # active row continue instId = nextMibNode.name[len(vacmAccessStatus.name):] indices = vacmAccessEntry.getIndicesFromInstId(instId) vacmGroupName = indices[0] self._addAccessEntry( vacmGroupName, vacmAccessContextPrefix.getNode( vacmAccessContextPrefix.name + instId).syntax, vacmAccessSecurityModel.getNode( vacmAccessSecurityModel.name + instId).syntax, vacmAccessSecurityLevel.getNode( vacmAccessSecurityLevel.name + instId).syntax, vacmAccessContextMatch.getNode( vacmAccessContextMatch.name + instId).syntax, vacmAccessReadViewName.getNode( vacmAccessReadViewName.name + instId).syntax, vacmAccessWriteViewName.getNode( vacmAccessWriteViewName.name + instId).syntax, vacmAccessNotifyViewName.getNode( vacmAccessNotifyViewName.name + instId).syntax ) self._accessBranchId = vacmAccessStatus.branchVersionId viewName = self._getFamilyViewName( groupName, contextName, securityModel, securityLevel, viewType) # Rebuild family subtree map if changed vacmViewTreeFamilyViewName, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyViewName') if self._viewTreeBranchId != vacmViewTreeFamilyViewName.branchVersionId: (vacmViewTreeFamilySubtree, vacmViewTreeFamilyMask, vacmViewTreeFamilyType) = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilySubtree', 'vacmViewTreeFamilyMask', 'vacmViewTreeFamilyType') self._viewTreeMap.clear() powerOfTwo = [2 ** exp for exp in range(7, -1, -1)] nextMibNode = vacmViewTreeFamilyViewName while True: try: nextMibNode = vacmViewTreeFamilyViewName.getNextNode( nextMibNode.name) except NoSuchInstanceError: break if nextMibNode.syntax not in self._viewTreeMap: self._viewTreeMap[nextMibNode.syntax] = [] instId = nextMibNode.name[len(vacmViewTreeFamilyViewName.name):] subtree = vacmViewTreeFamilySubtree.getNode( vacmViewTreeFamilySubtree.name + instId).syntax mask = vacmViewTreeFamilyMask.getNode( vacmViewTreeFamilyMask.name + instId).syntax mode = vacmViewTreeFamilyType.getNode( vacmViewTreeFamilyType.name + instId).syntax mask = mask.asNumbers() maskLength = min(len(mask) * 8, len(subtree)) ignoredSubOids = [ i * 8 + j for i, octet in enumerate(mask) for j, bit in enumerate(powerOfTwo) if not (bit & octet) and i * 8 + j < maskLength ] if ignoredSubOids: pattern = list(subtree) for ignoredSubOid in ignoredSubOids: pattern[ignoredSubOid] = 0 subtree = subtree.clone(pattern) entry = subtree, ignoredSubOids, mode == 1 self._viewTreeMap[nextMibNode.syntax].append(entry) for entries in self._viewTreeMap.values(): entries.sort(key=lambda x: (len(x[0]), x[0])) self._viewTreeBranchId = vacmViewTreeFamilyViewName.branchVersionId # 3.2.5a indices = viewName try: entries = self._viewTreeMap[indices] except KeyError: return error.StatusInformation(errorIndication=errind.notInView) accessAllowed = False for entry in entries: subtree, ignoredSubOids, included = entry if ignoredSubOids: subOids = list(variableName) for ignoredSubOid in ignoredSubOids: subOids[ignoredSubOid] = 0 normalizedVariableName = subtree.clone(subOids) else: normalizedVariableName = variableName if subtree.isPrefixOf(normalizedVariableName): accessAllowed = included # 3.2.5c if not accessAllowed: raise error.StatusInformation(errorIndication=errind.notInView) pysnmp-4.4.12/pysnmp/proto/acmod/void.py000066400000000000000000000016041354244100700202200ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import errind, error from pysnmp import debug # rfc3415 3.2 # noinspection PyUnusedLocal class Vacm(object): """Void Access Control Model""" accessModelID = 0 def isAccessAllowed(self, 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) pysnmp-4.4.12/pysnmp/proto/api/000077500000000000000000000000001354244100700163725ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/api/__init__.py000066400000000000000000000005601354244100700205040ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.api import v1, v2c, verdec # Protocol versions protoVersion1 = 0 protoVersion2c = 1 protoModules = {protoVersion1: v1, protoVersion2c: v2c} decodeMessageVersion = verdec.decodeMessageVersion pysnmp-4.4.12/pysnmp/proto/api/v1.py000066400000000000000000000223221354244100700172730ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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(object): @staticmethod def setOIDVal(varBind, oidVal): oid, val = oidVal[0], oidVal[1] varBind.setComponentByPosition(0, oid) if val is None: val = null varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(), val, verifyConstraints=False, matchTags=False, matchConstraints=False, innerFlag=True) return varBind @staticmethod def getOIDVal(varBind): return varBind[0], varBind[1].getComponent(1) apiVarBind = VarBindAPI() getNextRequestID = nextid.Integer(0xffffff) class PDUAPI(object): _errorStatus = rfc1157.errorStatus.clone(0) _errorIndex = Integer(0) def setDefaults(self, pdu): pdu.setComponentByPosition( 0, getNextRequestID(), verifyConstraints=False, matchTags=False, matchConstraints=False ) pdu.setComponentByPosition( 1, self._errorStatus, verifyConstraints=False, matchTags=False, matchConstraints=False ) pdu.setComponentByPosition( 2, self._errorIndex, verifyConstraints=False, matchTags=False, matchConstraints=False ) varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) varBindList.clear() @staticmethod def getRequestID(pdu): return pdu.getComponentByPosition(0) @staticmethod def setRequestID(pdu, value): pdu.setComponentByPosition(0, value) @staticmethod def getErrorStatus(pdu): return pdu.getComponentByPosition(1) @staticmethod def setErrorStatus(pdu, value): pdu.setComponentByPosition(1, value) @staticmethod def getErrorIndex(pdu, muteErrors=False): errorIndex = pdu.getComponentByPosition(2) if errorIndex > len(pdu[3]): if muteErrors: return errorIndex.clone(len(pdu[3])) raise error.ProtocolError( 'Error index out of range: %s > %s' % (errorIndex, len(pdu[3])) ) return errorIndex @staticmethod def setErrorIndex(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) @staticmethod def getVarBindList(pdu): return pdu.getComponentByPosition(3) @staticmethod def setVarBindList(pdu, varBindList): pdu.setComponentByPosition(3, varBindList) @staticmethod def getVarBinds(pdu): return [apiVarBind.getOIDVal(varBind) for varBind in pdu.getComponentByPosition(3)] @staticmethod def setVarBinds(pdu, varBinds): varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) varBindList.clear() for idx, varBind in enumerate(varBinds): if isinstance(varBind, VarBind): varBindList.setComponentByPosition(idx, varBind) else: varBindList.setComponentByPosition(idx) apiVarBind.setOIDVal( varBindList.getComponentByPosition(idx), varBind ) 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(object): _networkAddress = None _entOid = ObjectIdentifier((1, 3, 6, 1, 4, 1, 20408)) _genericTrap = rfc1157.genericTrap.clone('coldStart') _zeroInt = univ.Integer(0) _zeroTime = TimeTicks(0) def setDefaults(self, pdu): if self._networkAddress is None: try: import socket agentAddress = IpAddress(socket.gethostbyname(socket.gethostname())) except Exception: agentAddress = IpAddress('0.0.0.0') self._networkAddress = NetworkAddress().setComponentByPosition(0, agentAddress) pdu.setComponentByPosition(0, self._entOid, verifyConstraints=False, matchTags=False, matchConstraints=False) pdu.setComponentByPosition(1, self._networkAddress, verifyConstraints=False, matchTags=False, matchConstraints=False) pdu.setComponentByPosition(2, self._genericTrap, verifyConstraints=False, matchTags=False, matchConstraints=False) pdu.setComponentByPosition(3, self._zeroInt, verifyConstraints=False, matchTags=False, matchConstraints=False) pdu.setComponentByPosition(4, self._zeroTime, verifyConstraints=False, matchTags=False, matchConstraints=False) varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5) varBindList.clear() @staticmethod def getEnterprise(pdu): return pdu.getComponentByPosition(0) @staticmethod def setEnterprise(pdu, value): pdu.setComponentByPosition(0, value) @staticmethod def getAgentAddr(pdu): return pdu.getComponentByPosition(1).getComponentByPosition(0) @staticmethod def setAgentAddr(pdu, value): pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(0, value) @staticmethod def getGenericTrap(pdu): return pdu.getComponentByPosition(2) @staticmethod def setGenericTrap(pdu, value): pdu.setComponentByPosition(2, value) @staticmethod def getSpecificTrap(pdu): return pdu.getComponentByPosition(3) @staticmethod def setSpecificTrap(pdu, value): pdu.setComponentByPosition(3, value) @staticmethod def getTimeStamp(pdu): return pdu.getComponentByPosition(4) @staticmethod def setTimeStamp(pdu, value): pdu.setComponentByPosition(4, value) @staticmethod def getVarBindList(pdu): return pdu.getComponentByPosition(5) @staticmethod def setVarBindList(pdu, varBindList): pdu.setComponentByPosition(5, varBindList) @staticmethod def getVarBinds(pdu): varBinds = [] for varBind in pdu.getComponentByPosition(5): varBinds.append(apiVarBind.getOIDVal(varBind)) return varBinds @staticmethod def setVarBinds(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 += 1 apiTrapPDU = TrapPDUAPI() class MessageAPI(object): _version = rfc1157.version.clone(0) _community = univ.OctetString('public') def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False, matchTags=False, matchConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False, matchTags=False, matchConstraints=False) return msg @staticmethod def getVersion(msg): return msg.getComponentByPosition(0) @staticmethod def setVersion(msg, value): msg.setComponentByPosition(0, value) @staticmethod def getCommunity(msg): return msg.getComponentByPosition(1) @staticmethod def setCommunity(msg, value): msg.setComponentByPosition(1, value) @staticmethod def getPDU(msg): return msg.getComponentByPosition(2).getComponent() @staticmethod def setPDU(msg, value): msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(value.getTagSet(), value, verifyConstraints=False, matchTags=False, matchConstraints=False, innerFlag=True) 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() pysnmp-4.4.12/pysnmp/proto/api/v2c.py000066400000000000000000000127341354244100700174450ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import rfc1901, rfc1902, rfc1905 from pysnmp.proto.api import v1 from pyasn1.type import univ, 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 NoSuchObject = rfc1905.NoSuchObject NoSuchInstance = rfc1905.NoSuchInstance EndOfMibView = rfc1905.EndOfMibView 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 Message = rfc1901.Message getNextRequestID = v1.getNextRequestID apiVarBind = v1.apiVarBind class PDUAPI(v1.PDUAPI): _errorStatus = rfc1905.errorStatus.clone(0) _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, matchTags=False, matchConstraints=False ) def setNoSuchInstanceError(self, pdu, errorIndex): varBindList = self.getVarBindList(pdu) varBindList[errorIndex - 1].setComponentByPosition( 1, rfc1905.noSuchInstance, verifyConstraints=False, matchTags=False, matchConstraints=False ) apiPDU = PDUAPI() class BulkPDUAPI(PDUAPI): _nonRepeaters = rfc1905.nonRepeaters.clone(0) _maxRepetitions = rfc1905.maxRepetitions.clone(10) def setDefaults(self, pdu): PDUAPI.setDefaults(self, pdu) pdu.setComponentByPosition( 0, getNextRequestID(), verifyConstraints=False, matchTags=False, matchConstraints=False ) pdu.setComponentByPosition( 1, self._nonRepeaters, verifyConstraints=False, matchTags=False, matchConstraints=False ) pdu.setComponentByPosition( 2, self._maxRepetitions, verifyConstraints=False, matchTags=False, matchConstraints=False ) varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) varBindList.clear() @staticmethod def getNonRepeaters(pdu): return pdu.getComponentByPosition(1) @staticmethod def setNonRepeaters(pdu, value): pdu.setComponentByPosition(1, value) @staticmethod def getMaxRepetitions(pdu): return pdu.getComponentByPosition(2) @staticmethod def setMaxRepetitions(pdu, value): pdu.setComponentByPosition(2, value) def getVarBindTable(self, reqPDU, rspPDU): nonRepeaters = self.getNonRepeaters(reqPDU) reqVarBinds = self.getVarBinds(reqPDU) N = min(int(nonRepeaters), len(reqVarBinds)) 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): _version = rfc1901.version.clone(1) def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False, matchTags=False, matchConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False, matchTags=False, matchConstraints=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() pysnmp-4.4.12/pysnmp/proto/api/verdec.py000066400000000000000000000016331354244100700202170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import univ from pyasn1.codec.ber import decoder, eoo from pyasn1.error import PyAsn1Error from pysnmp.proto.error import ProtocolError def decodeMessageVersion(wholeMsg): try: seq, wholeMsg = decoder.decode( wholeMsg, asn1Spec=univ.Sequence(), recursiveFlag=False, substrateFun=lambda a, b, c: (a, b[:c]) ) ver, wholeMsg = decoder.decode( wholeMsg, asn1Spec=univ.Integer(), recursiveFlag=False, substrateFun=lambda a, b, c: (a, b[:c]) ) if eoo.endOfOctets.isSameTypeWith(ver): raise ProtocolError('EOO at SNMP version component') return ver except PyAsn1Error: raise ProtocolError('Invalid BER at SNMP version component') pysnmp-4.4.12/pysnmp/proto/cache.py000066400000000000000000000022041354244100700172340ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import error class Cache(object): 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): if index in self.__cacheRepository: del self.__cacheRepository[index] pysnmp-4.4.12/pysnmp/proto/errind.py000066400000000000000000000135241354244100700174630ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # class ErrorIndication(Exception): """SNMPv3 error-indication values""" 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 SerializationError(ErrorIndication): pass serializationError = SerializationError('SNMP message serialization error') class DeserializationError(ErrorIndication): pass deserializationError = DeserializationError('SNMP message deserialization error') class ParseError(DeserializationError): pass parseError = ParseError('SNMP message deserialization error') class UnsupportedMsgProcessingModel(ErrorIndication): pass unsupportedMsgProcessingModel = UnsupportedMsgProcessingModel('Unknown SNMP message processing model ID encountered') class UnknownPDUHandler(ErrorIndication): pass unknownPDUHandler = UnknownPDUHandler('Unhandled PDU type encountered') class UnsupportedPDUtype(ErrorIndication): pass unsupportedPDUtype = UnsupportedPDUtype('Unsupported SNMP PDU type encountered') class RequestTimedOut(ErrorIndication): pass requestTimedOut = RequestTimedOut('No SNMP response received before timeout') class EmptyResponse(ErrorIndication): pass emptyResponse = EmptyResponse('Empty SNMP response message') class NonReportable(ErrorIndication): pass nonReportable = NonReportable('Report PDU generation not attempted') class DataMismatch(ErrorIndication): pass dataMismatch = DataMismatch('SNMP request/response parameters mismatched') class EngineIDMismatch(ErrorIndication): pass engineIDMismatch = EngineIDMismatch('SNMP engine ID mismatch encountered') class UnknownEngineID(ErrorIndication): pass unknownEngineID = UnknownEngineID('Unknown SNMP engine ID encountered') class TooBig(ErrorIndication): pass tooBig = TooBig('SNMP message will be too big') class LoopTerminated(ErrorIndication): pass loopTerminated = LoopTerminated('Infinite SNMP entities talk terminated') class InvalidMsg(ErrorIndication): pass invalidMsg = InvalidMsg('Invalid SNMP message header parameters encountered') # 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 # backward compatibility plug UnsupportedSecLevel = UnsupportedSecurityLevel unsupportedSecurityLevel = UnsupportedSecurityLevel('Unsupported SNMP security level') class NotInTimeWindow(ErrorIndication): pass notInTimeWindow = NotInTimeWindow('SNMP message timing parameters not in windows of trust') class UnknownUserName(ErrorIndication): pass unknownUserName = UnknownUserName('Unknown USM user') class WrongDigest(ErrorIndication): pass wrongDigest = WrongDigest('Wrong SNMP PDU digest') class ReportPduReceived(ErrorIndication): pass reportPduReceived = ReportPduReceived('Remote SNMP engine reported error') # 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('OID not increasing') pysnmp-4.4.12/pysnmp/proto/error.py000066400000000000000000000022441354244100700173260ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 pysnmp-4.4.12/pysnmp/proto/mpmod/000077500000000000000000000000001354244100700167355ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/mpmod/__init__.py000066400000000000000000000000731354244100700210460ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/mpmod/base.py000066400000000000000000000033371354244100700202270ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.mpmod import cache from pysnmp.proto import error class AbstractMessageProcessingModel(object): snmpMsgSpec = NotImplementedError 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() pysnmp-4.4.12/pysnmp/proto/mpmod/cache.py000066400000000000000000000075431354244100700203630ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import error from pysnmp import nextid class Cache(object): __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 + 600 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 + 600 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 += 1 pysnmp-4.4.12/pysnmp/proto/mpmod/rfc2576.py000066400000000000000000000476121354244100700204170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pyasn1.codec.ber import decoder, eoo 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 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): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineId = snmpEngineId.syntax # rfc3412: 7.1.1b if pdu.tagSet in rfc3411.confirmedClassPDUs: # serve unique PDU request-id msgID = self._cache.newMsgID() reqID = pdu.getComponentByPosition(0) debug.logger & debug.flagMP and debug.logger( 'prepareOutgoingMessage: PDU request-id %s replaced with unique ID %s' % (reqID, msgID)) # 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, matchTags=False, matchConstraints=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, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') # fix unique request-id right prior PDU serialization if pdu.tagSet in rfc3411.confirmedClassPDUs: # noinspection PyUnboundLocalVariable pdu.setComponentByPosition(0, msgID) # rfc3412: 7.1.9.b (securityParameters, wholeMsg) = smHandler.generateRequestMsg( snmpEngine, self.messageProcessingModelID, globalData, snmpEngineMaxMessageSize.syntax, securityModel, snmpEngineId, securityName, securityLevel, scopedPDU ) # return original request-id right after PDU serialization if pdu.tagSet in rfc3411.confirmedClassPDUs: # noinspection PyUnboundLocalVariable pdu.setComponentByPosition(0, reqID) # rfc3412: 7.1.9.c if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX rfc bug? why stateReference should be created? self._cache.pushByMsgId(int(msgID), sendPduHandle=sendPduHandle, reqID=reqID, snmpEngineId=snmpEngineId, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, transportDomain=transportDomain, transportAddress=transportAddress) communityName = msg.getComponentByPosition(1) # for observer snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareOutgoingMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, wholeMsg=wholeMsg, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, communityName=communityName, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.prepareOutgoingMessage' ) return transportDomain, transportAddress, wholeMsg # rfc3412: 7.1 def prepareResponseMessage(self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, maxSizeResponseScopedPDU, stateReference, statusInformation): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineId = snmpEngineId.syntax # rfc3412: 7.1.2.b if stateReference is None: raise error.StatusInformation(errorIndication=errind.nonReportable) cachedParams = self._cache.popByStateRef(stateReference) msgID = cachedParams['msgID'] reqID = cachedParams['reqID'] 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, matchTags=False, matchConstraints=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 ) # set original request-id right prior to PDU serialization pdu.setComponentByPosition(0, reqID) # rfc3412: 7.1.8.a (securityParameters, wholeMsg) = smHandler.generateResponseMsg( snmpEngine, self.messageProcessingModelID, globalData, maxMessageSize, securityModel, snmpEngineId, securityName, securityLevel, scopedPDU, securityStateReference ) # recover unique request-id right after PDU serialization pdu.setComponentByPosition(0, msgID) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareResponseMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=snmpEngineId, communityName=msg.getComponentByPosition(1), pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.prepareResponseMessage' ) return transportDomain, transportAddress, wholeMsg # rfc3412: 7.2.1 def prepareDataElements(self, snmpEngine, transportDomain, transportAddress, wholeMsg): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder # rfc3412: 7.2.2 msg, restOfWholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec) debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) if eoo.endOfOctets.isSameTypeWith(msg): raise error.StatusInformation(errorIndication=errind.parseError) # rfc3412: 7.2.3 msgVersion = msg.getComponentByPosition(0) # rfc2576: 5.2.1 snmpEngineMaxMessageSize, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') communityName = msg.getComponentByPosition(1) # transportDomain identifies local endpoint securityParameters = (communityName, (transportDomain, transportAddress)) messageProcessingModel = int(msg.getComponentByPosition(0)) securityModel = messageProcessingModel + 1 securityLevel = 1 # rfc3412: 7.2.4 -- 7.2.5 -> no-op try: try: smHandler = snmpEngine.securityModels[securityModel] except KeyError: 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)) except error.StatusInformation: statusInformation = sys.exc_info()[1] snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:sm-failure', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityLevel=securityLevel, securityParameters=securityParameters, statusInformation=statusInformation) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:sm-failure' ) raise # rfc3412: 7.2.6a --> no-op # rfc3412: 7.2.7 contextEngineId, contextName, pdu = scopedPDU # rfc2576: 5.2.1 pduVersion = msgVersion pduType = pdu.tagSet # rfc3412: 7.2.8, 7.2.9 -> no-op # rfc3412: 7.2.10 if pduType in rfc3411.responseClassPDUs: # get unique PDU request-id 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) # recover original PDU request-id to return to app pdu.setComponentByPosition(0, cachedReqParams['reqID']) debug.logger & debug.flagMP and debug.logger( 'prepareDataElements: unique PDU request-id %s replaced with original ID %s' % ( msgID, cachedReqParams['reqID'])) # 7.2.10b sendPduHandle = cachedReqParams['sendPduHandle'] else: sendPduHandle = None # no error by default statusInformation = None # rfc3412: 7.2.11 -> no-op # rfc3412: 7.2.12 if pduType in rfc3411.responseClassPDUs: # rfc3412: 7.2.12a -> no-op # rfc3412: 7.2.12b # noinspection PyUnboundLocalVariable if (securityModel != cachedReqParams['securityModel'] or securityName != cachedReqParams['securityName'] or securityLevel != cachedReqParams['securityLevel'] or contextEngineId != cachedReqParams['contextEngineId'] or contextName != cachedReqParams['contextName']): smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation(errorIndication=errind.dataMismatch) stateReference = None snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:response', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, communityName=communityName, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:response' ) # 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: # store original PDU request-id and replace it with a unique one reqID = pdu.getComponentByPosition(0) msgID = self._cache.newMsgID() pdu.setComponentByPosition(0, msgID) debug.logger & debug.flagMP and debug.logger( 'prepareDataElements: received PDU request-id %s replaced with unique ID %s' % (reqID, msgID)) # rfc3412: 7.2.13a snmpEngineId, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if securityEngineId != snmpEngineId.syntax: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication=errind.engineIDMismatch ) # rfc3412: 7.2.13b stateReference = self._cache.newStateReference() self._cache.pushByStateRef( stateReference, msgVersion=messageProcessingModel, msgID=msgID, reqID=reqID, contextEngineId=contextEngineId, contextName=contextName, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, msgMaxSize=snmpEngineMaxMessageSize.syntax, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress ) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:confirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, communityName=communityName, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:confirmed' ) 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: # Pass new stateReference to let app browse request details stateReference = self._cache.newStateReference() snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:unconfirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, communityName=communityName, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:unconfirmed' ) # 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 pysnmp-4.4.12/pysnmp/proto/mpmod/rfc3412.py000066400000000000000000001046171354244100700204040ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel from pysnmp.proto import rfc1905, rfc3411, api, errind, error from pyasn1.type import univ, namedtype, constraint from pyasn1.codec.ber import decoder, eoo 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))), # NOTE (etingof): constrain SNMPv3 message to only USM+ security models # because SNMPv1/v2c seems incompatible in pysnmp implementation, not sure # if it's intended by the SNMP standard at all... namedtype.NamedType('msgSecurityModel', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(3, 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): errind.unsupportedSecurityLevel, (1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0): errind.notInTimeWindow, (1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0): errind.unknownUserName, (1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0): errind.unknownEngineID, (1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0): errind.wrongDigest, (1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0): errind.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.__engineIdCache = {} self.__engineIdCacheExpQueue = {} self.__expirationTimer = 0 def getPeerEngineInfo(self, transportDomain, transportAddress): k = transportDomain, transportAddress if k in self.__engineIdCache: return (self.__engineIdCache[k]['securityEngineId'], self.__engineIdCache[k]['contextEngineId'], self.__engineIdCache[k]['contextName']) else: return None, None, None # 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.__engineIdCache: peerSnmpEngineData = self.__engineIdCache[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, matchTags=False, matchConstraints=False ) # 7.1.7 msg = self._snmpMsgSpec # 7.1.7a msg.setComponentByPosition( 0, self.messageProcessingModelID, verifyConstraints=False, matchTags=False, matchConstraints=False ) headerData = msg.setComponentByPosition(1).getComponentByPosition(1) # 7.1.7b headerData.setComponentByPosition(0, msgID, verifyConstraints=False, matchTags=False, matchConstraints=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, matchTags=False, matchConstraints=False ) # 7.1.7d msgFlags = 0 if securityLevel == 1: pass elif securityLevel == 2: msgFlags |= 0x01 elif securityLevel == 3: msgFlags |= 0x03 else: raise error.ProtocolError( 'Unknown securityLevel %s' % securityLevel ) if pdu.tagSet in rfc3411.confirmedClassPDUs: msgFlags |= 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False, matchTags=False, matchConstraints=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: debug.logger & debug.flagMP and debug.logger( 'prepareOutgoingMessage: peer SNMP engine is not known') securityEngineId = None else: securityEngineId = peerSnmpEngineData['securityEngineId'] debug.logger & debug.flagMP and debug.logger( 'prepareOutgoingMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % ( securityModel, securityEngineId, securityName, securityLevel)) # 7.1.9.b (securityParameters, wholeMsg) = smHandler.generateRequestMsg( snmpEngine, self.messageProcessingModelID, msg, snmpEngineMaxMessageSize.syntax, securityModel, securityEngineId, securityName, securityLevel, scopedPDU ) # 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) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareOutgoingMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, wholeMsg=wholeMsg, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareOutgoingMessage' ) 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 None: pduType = None else: requestID = pdu.getComponentByPosition(0) pduType = pdu.tagSet # 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: # noinspection PyUnboundLocalVariable 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, matchTags=False, matchConstraints=False ) # 7.1.7 msg = self._snmpMsgSpec # 7.1.7a msg.setComponentByPosition( 0, self.messageProcessingModelID, verifyConstraints=False, matchTags=False, matchConstraints=False ) headerData = msg.setComponentByPosition(1).getComponentByPosition(1) # 7.1.7b headerData.setComponentByPosition(0, msgID, verifyConstraints=False, matchTags=False, matchConstraints=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, matchTags=False, matchConstraints=False ) # 7.1.7d msgFlags = 0 if securityLevel == 1: pass elif securityLevel == 2: msgFlags |= 0x01 elif securityLevel == 3: msgFlags |= 0x03 else: raise error.ProtocolError('Unknown securityLevel %s' % securityLevel) if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed? msgFlags |= 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False, matchTags=False, matchConstraints=False ) # 7.1.7e headerData.setComponentByPosition( 3, securityModel, verifyConstraints=False, matchTags=False, matchConstraints=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) debug.logger & debug.flagMP and debug.logger( 'prepareResponseMessage: securityModel %r, securityEngineId %r, securityName %r, securityLevel %r' % ( securityModel, snmpEngineID, securityName, securityLevel)) # 7.1.8a try: (securityParameters, wholeMsg) = smHandler.generateResponseMsg( snmpEngine, self.messageProcessingModelID, msg, snmpEngineMaxMessageSize.syntax, securityModel, snmpEngineID, securityName, securityLevel, scopedPDU, securityStateReference ) 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) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareResponseMessage', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=snmpEngineID, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareResponseMessage' ) return transportDomain, transportAddress, wholeMsg # 7.2.1 def prepareDataElements(self, snmpEngine, transportDomain, transportAddress, wholeMsg): # 7.2.2 msg, restOfwholeMsg = decoder.decode(wholeMsg, asn1Spec=self._snmpMsgSpec) debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) if eoo.endOfOctets.isSameTypeWith(msg): raise error.StatusInformation(errorIndication=errind.parseError) # 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( '__SNMP-MPD-MIB', 'snmpUnknownSecurityModels') 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('__SNMP-MPD-MIB', 'snmpInvalidMsgs') 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) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:sm-failure', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityLevel=securityLevel, securityParameters=securityParameters, statusInformation=statusInformation) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:sm-failure' ) 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 engineIdCache k = (transportDomain, transportAddress) if k not in self.__engineIdCache: contextEngineId = scopedPDU[0] contextName = scopedPDU[1] pdus = scopedPDU[2] 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.__engineIdCache[k] = { 'securityEngineId': securityEngineId, 'contextEngineId': contextEngineId, 'contextName': contextName } expireAt = int(self.__expirationTimer + 300 / snmpEngine.transportDispatcher.getTimerResolution()) if expireAt not in self.__engineIdCacheExpQueue: self.__engineIdCacheExpQueue[expireAt] = [] self.__engineIdCacheExpQueue[expireAt].append(k) debug.logger & debug.flagMP and debug.logger( 'prepareDataElements: cache securityEngineId %r for %r %r' % ( securityEngineId, transportDomain, transportAddress)) snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # 7.2.7 XXX PDU would be parsed here? contextEngineId = scopedPDU[0] contextName = scopedPDU[1] pdu = scopedPDU[2] 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], errind.ReportPduReceived(varBinds[0][0].prettyPrint())), oid=varBinds[0][0], val=varBinds[0][1], sendPduHandle=sendPduHandle ) else: statusInformation = error.StatusInformation( sendPduHandle=sendPduHandle ) # 7.2.11b (incomplete implementation) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:internal', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:internal' ) # 7.2.11c smHandler.releaseStateInformation(securityStateReference) # 7.2.11d # no-op # 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 -> no-op # 7.2.12b # noinspection PyUnboundLocalVariable if (securityModel != cachedReqParams['securityModel'] or securityName != cachedReqParams['securityName'] or securityLevel != cachedReqParams['securityLevel'] or contextEngineId != cachedReqParams['contextEngineId'] or contextName != cachedReqParams['contextName']): smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication=errind.dataMismatch ) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:response', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:response' ) # 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) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:confirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:confirmed' ) # 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() snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:unconfirmed', dict(transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, securityEngineId=securityEngineId, pdu=pdu) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.prepareDataElements:unconfirmed' ) # 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.__engineIdCacheExpQueue: for engineKey in self.__engineIdCacheExpQueue[self.__expirationTimer]: del self.__engineIdCache[engineKey] debug.logger & debug.flagMP and debug.logger('__expireEnginesInfo: expiring %r' % (engineKey,)) del self.__engineIdCacheExpQueue[self.__expirationTimer] self.__expirationTimer += 1 def receiveTimerTick(self, snmpEngine, timeNow): self.__expireEnginesInfo() AbstractMessageProcessingModel.receiveTimerTick(self, snmpEngine, timeNow) pysnmp-4.4.12/pysnmp/proto/proxy/000077500000000000000000000000001354244100700170025ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/proxy/__init__.py000066400000000000000000000000731354244100700211130ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/proxy/rfc2576.py000066400000000000000000000232171354244100700204570ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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, snmpTrapCommunity=''): 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, int(v1.apiTrapPDU.getSpecificTrap(v1Pdu))) # 3.1.3 else: snmpTrapOIDParam = v2c.ObjectIdentifier(__v1ToV2TrapMap[genericTrap]) # 3.1.4 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(snmpTrapCommunity))) 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 not in rfc3411.notificationClassPDUs: errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu)) errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu, muteErrors=True)) if pduType in rfc3411.responseClassPDUs: # 4.1.2.2.1&2 if errorStatus == 2: # noSuchName if origV2Pdu.tagSet == v2c.GetNextRequestPDU.tagSet: v2VarBinds = [(o, rfc1905.endOfMibView) for o, v in v2VarBinds] else: v2VarBinds = [(o, rfc1905.noSuchObject) for o, v in v2VarBinds] # partial one-to-one mapping - 4.2.1 v2c.apiPDU.setErrorStatus(v2Pdu, errorStatus) v2c.apiPDU.setErrorIndex(v2Pdu, errorIndex) # 4.1.2.1 --> no-op v2c.apiPDU.setRequestID(v2Pdu, int(v1.apiPDU.getRequestID(v1Pdu))) else: v2c.apiPDU.setDefaults(v2Pdu) 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') snmpTrapOID, snmpTrapOIDParam = v2VarBinds[1] 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, v1.IpAddress(val)) # v2c.OctetString is more constrained break else: v1.apiTrapPDU.setAgentAddr(v1Pdu, v1.IpAddress('0.0.0.0')) # 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 val.tagSet in (v2c.NoSuchObject.tagSet, v2c.NoSuchInstance.tagSet, v2c.EndOfMibView.tagSet): v1.apiPDU.setErrorStatus(v1Pdu, 2) v1.apiPDU.setErrorIndex(v1Pdu, idx + 1) idx -= 1 # 4.1.2.3.1 v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu) if v2ErrorStatus: v1.apiPDU.setErrorStatus( v1Pdu, __v2ToV1ErrorMap.get(v2ErrorStatus, 5) ) v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu, muteErrors=True)) elif pduType in rfc3411.confirmedClassPDUs: v1.apiPDU.setErrorStatus(v1Pdu, 0) v1.apiPDU.setErrorIndex(v1Pdu, 0) # 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 pysnmp-4.4.12/pysnmp/proto/rfc1155.py000066400000000000000000000137151354244100700172700ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import univ, tag, constraint, namedtype from pyasn1.error import PyAsn1Error from pysnmp.smi.error import SmiError from pysnmp.proto import error __all__ = ['Opaque', 'NetworkAddress', 'ObjectName', 'TimeTicks', 'Counter', 'Gauge', 'IpAddress'] 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()) ) def clone(self, value=univ.noValue, **kwargs): """Clone this instance. If *value* is specified, use its tag as the component type selector, and itself as the component value. :param value: (Optional) the component value. :type value: :py:obj:`pyasn1.type.base.Asn1ItemBase` :return: the cloned instance. :rtype: :py:obj:`pysnmp.proto.rfc1155.NetworkAddress` :raise: :py:obj:`pysnmp.smi.error.SmiError`: if the type of *value* is not allowed for this Choice instance. """ cloned = univ.Choice.clone(self, **kwargs) if value is not univ.noValue: if isinstance(value, NetworkAddress): value = value.getComponent() elif not isinstance(value, IpAddress): # IpAddress is the only supported type, perhaps forever because # this is SNMPv1. value = IpAddress(value) try: tagSet = value.tagSet except AttributeError: raise PyAsn1Error('component value %r has no tag set' % (value,)) cloned.setComponentByType(tagSet, value) return cloned # RFC 1212, section 4.1.6: # # "(5) NetworkAddress-valued: `n+1' sub-identifiers, where `n' # depends on the kind of address being encoded (the first # sub-identifier indicates the kind of address, value 1 # indicates an IpAddress);" def cloneFromName(self, value, impliedFlag, parentRow, parentIndices): kind = value[0] clone = self.clone() if kind == 1: clone['internet'] = tuple(value[1:5]) return clone, value[5:] else: raise SmiError('unknown NetworkAddress type %r' % (kind,)) def cloneAsName(self, impliedFlag, parentRow, parentIndices): kind = self.getName() component = self.getComponent() if kind == 'internet': return (1,) + tuple(component.asNumbers()) else: raise SmiError('unknown NetworkAddress type %r' % (kind,)) 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 keep this old-style class till pyasn1 types becomes new-style # 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, **kwargs): 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()) ) pysnmp-4.4.12/pysnmp/proto/rfc1157.py000066400000000000000000000063701354244100700172710ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import univ, tag, namedtype, namedval from pysnmp.proto import rfc1155 __all__ = ['GetNextRequestPDU', 'GetResponsePDU', 'SetRequestPDU', 'TrapPDU', 'GetRequestPDU'] class VarBind(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('name', rfc1155.ObjectName()), namedtype.NamedType('value', rfc1155.ObjectSyntax()) ) class VarBindList(univ.SequenceOf): componentType = VarBind() errorStatus = univ.Integer( namedValues=namedval.NamedValues(('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5))) class _RequestBase(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', univ.Integer()), namedtype.NamedType('error-status', errorStatus), namedtype.NamedType('error-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) ) genericTrap = univ.Integer().clone( namedValues=namedval.NamedValues(('coldStart', 0), ('warmStart', 1), ('linkDown', 2), ('linkUp', 3), ('authenticationFailure', 4), ('egpNeighborLoss', 5), ('enterpriseSpecific', 6))) class TrapPDU(univ.Sequence): tagSet = univ.Sequence.tagSet.tagImplicitly( 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', genericTrap), 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()) ) version = univ.Integer(namedValues=namedval.NamedValues(('version-1', 0))) class Message(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', version), namedtype.NamedType('community', univ.OctetString()), namedtype.NamedType('data', PDUs()) ) pysnmp-4.4.12/pysnmp/proto/rfc1901.py000066400000000000000000000010601354244100700172550ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import univ, namedtype, namedval from pysnmp.proto import rfc1905 version = univ.Integer(namedValues=namedval.NamedValues(('version-2c', 1))) class Message(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('version', version), namedtype.NamedType('community', univ.OctetString()), namedtype.NamedType('data', rfc1905.PDUs()) ) pysnmp-4.4.12/pysnmp/proto/rfc1902.py000066400000000000000000000515171354244100700172720ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from sys import version_info from pyasn1.type import univ, tag, constraint, namedtype, namedval from pysnmp.proto import rfc1155, error __all__ = ['Opaque', 'TimeTicks', 'Bits', 'Integer', 'OctetString', 'IpAddress', 'Counter64', 'Unsigned32', 'Gauge32', 'Integer32', 'ObjectIdentifier', 'Counter32', 'Null'] class Null(univ.Null): """Creates an instance of SNMP Null class. :py:class:`~pysnmp.proto.rfc1902.Null` type represents the absence of value. Parameters ---------- initializer: str Python string object. Must be an empty string. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Null('') Null('') >>> """ class Integer32(univ.Integer): """Creates an instance of SNMP Integer32 class. :py:class:`~pysnmp.proto.rfc1902.Integer32` type represents integer-valued information between -2147483648 to 2147483647 inclusive (:RFC:`1902#section-7.1.1`). This type is indistinguishable from the :py:class:`~pysnmp.proto.rfc1902.Integer` type. The :py:class:`~pysnmp.proto.rfc1902.Integer32` type may be sub-typed to be more constrained than the base :py:class:`~pysnmp.proto.rfc1902.Integer32` type. Parameters ---------- initializer : int Python integer in range between -2147483648 to 2147483647 inclusive or :py:class:`~pysnmp.proto.rfc1902.Integer32`. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Integer32(1234) Integer32(1234) >>> Integer32(1) > 2 True >>> Integer32(1) + 1 Integer32(2) >>> int(Integer32(321)) 321 >>> SmallInteger = Integer32.withRange(1,3) >>> SmallInteger(1) Integer32(1) >>> DiscreetInteger = Integer32.withValues(4, 8, 1) >>> DiscreetInteger(4) Integer32(4) >>> """ subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint( -2147483648, 2147483647 ) @classmethod def withValues(cls, *values): """Creates a subclass with discreet values constraint. """ class X(cls): subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint(*values) X.__name__ = cls.__name__ return X @classmethod def withRange(cls, minimum, maximum): """Creates a subclass with value range constraint. """ class X(cls): subtypeSpec = cls.subtypeSpec + constraint.ValueRangeConstraint(minimum, maximum) X.__name__ = cls.__name__ return X class Integer(Integer32): """Creates an instance of SNMP INTEGER class. The :py:class:`~pysnmp.proto.rfc1902.Integer` type represents integer-valued information as named-number enumerations (:RFC:`1902#section-7.1.1`). This type inherits and is indistinguishable from :py:class:`~pysnmp.proto.rfc1902.Integer32` class. The :py:class:`~pysnmp.proto.rfc1902.Integer` type may be sub-typed to be more constrained than the base :py:class:`~pysnmp.proto.rfc1902.Integer` type. Parameters ---------- initializer : int Python integer in range between -2147483648 to 2147483647 inclusive or :py:class:`~pysnmp.proto.rfc1902.Integer` class instance. In case of named-numbered enumerations, initialization is also possible by enumerated literal. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Integer(1234) Integer(1234) >>> Integer(1) > 2 True >>> Integer(1) + 1 Integer(2) >>> int(Integer(321)) 321 >>> SomeState = Integer.withNamedValues(enable=1, disable=0) >>> SomeState(1) Integer('enable') >>> int(SomeState('disable')) 0 >>> """ @classmethod def withNamedValues(cls, **values): """Create a subclass with discreet named values constraint. Reduce fully duplicate enumerations along the way. """ enums = set(cls.namedValues.items()) enums.update(values.items()) class X(cls): namedValues = namedval.NamedValues(*enums) subtypeSpec = cls.subtypeSpec + constraint.SingleValueConstraint( *values.values()) X.__name__ = cls.__name__ return X class OctetString(univ.OctetString): """Creates an instance of SNMP OCTET STRING class. The :py:class:`~pysnmp.proto.rfc1902.OctetString` type represents arbitrary binary or text data (:RFC:`1902#section-7.1.2`). It may be sub-typed to be constrained in size. Parameters ---------- strValue : str Python string or :py:class:`~pysnmp.proto.rfc1902.OctetString` class instance. Other parameters ---------------- hexValue : str Python string representing octets in a hexadecimal notation (e.g. DEADBEEF). Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> OctetString('some apples') OctetString('some apples') >>> OctetString('some apples') + ' and oranges' OctetString('some apples and oranges') >>> str(OctetString('some apples')) 'some apples' >>> SomeString = OctetString.withSize(3, 12) >>> str(SomeString(hexValue='deadbeef')) '\xde\xad\xbe\xef' >>> """ subtypeSpec = univ.OctetString.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 def clone(self, *args, **kwargs): return univ.OctetString.clone(self, *args, **kwargs).setFixedLength(self.getFixedLength()) def subtype(self, *args, **kwargs): return univ.OctetString.subtype(self, *args, **kwargs).setFixedLength(self.getFixedLength()) @classmethod def withSize(cls, minimum, maximum): """Creates a subclass with value size constraint. """ class X(cls): subtypeSpec = cls.subtypeSpec + constraint.ValueSizeConstraint(minimum, maximum) X.__name__ = cls.__name__ return X class ObjectIdentifier(univ.ObjectIdentifier): """Creates an instance of SNMP OBJECT IDENTIFIER class. The :py:class:`~pysnmp.proto.rfc1902.ObjectIdentifier` type represents administratively assigned names (:RFC:`1902#section-7.1.3`). Supports sequence protocol where elements are integer sub-identifiers. Parameters ---------- initializer: tuple, str Python tuple of up to 128 integers in range between 0 to 4294967295 inclusive or Python string containing OID in "dotted" form or :py:class:`~pysnmp.proto.rfc1902.ObjectIdentifier`. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> ObjectIdentifier((1, 3, 6)) ObjectIdentifier('1.3.6') >>> ObjectIdentifier('1.3.6') ObjectIdentifier('1.3.6') >>> tuple(ObjectIdentifier('1.3.6')) (1, 3, 6) >>> str(ObjectIdentifier('1.3.6')) '1.3.6' >>> """ class IpAddress(OctetString): """Creates an instance of SNMP IpAddress class. The :py:class:`~pysnmp.proto.rfc1902.IpAddress` class represents a 32-bit internet address as an OCTET STRING of length 4, in network byte-order (:RFC:`1902#section-7.1.5`). Parameters ---------- strValue : str The same as :py:class:`~pysnmp.proto.rfc1902.OctetString`, additionally IPv4 address in dotted notation ('127.0.0.1'). Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> IpAddress('127.0.0.1') IpAddress(hexValue='7f000001') >>> str(IpAddress(hexValue='7f000001')) '\x7f\x00\x00\x01' >>> IpAddress('\x7f\x00\x00\x01') IpAddress(hexValue='7f000001') >>> """ tagSet = OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) ) subtypeSpec = 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) value = OctetString.prettyIn(self, value) if len(value) != 4: raise error.ProtocolError('Bad IP address syntax') return value def prettyOut(self, value): if value: return '.'.join( ['%d' % x for x in self.__class__(value).asNumbers()] ) else: return '' class Counter32(univ.Integer): """Creates an instance of SNMP Counter32 class. :py:class:`~pysnmp.proto.rfc1902.Counter32` type represents a non-negative integer which monotonically increases until it reaches a maximum value of 4294967295, when it wraps around and starts increasing again from zero (:RFC:`1902#section-7.1.6`). Parameters ---------- initializer : int Python integer in range between 0 to 4294967295 inclusive or any :py:class:`~pysnmp.proto.rfc1902.Integer`-based class. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Counter32(1234) Counter32(1234) >>> Counter32(1) + 1 Counter32(2) >>> int(Counter32(321)) 321 >>> """ tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01) ) subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint( 0, 4294967295 ) class Gauge32(univ.Integer): """Creates an instance of SNMP Gauge32 class. :py:class:`~pysnmp.proto.rfc1902.Gauge32` type represents a non-negative integer, which may increase or decrease, but shall never exceed a maximum value. The maximum value can not be greater than 4294967295 (:RFC:`1902#section-7.1.7`). Parameters ---------- initializer : int Python integer in range between 0 to 4294967295 inclusive or any :py:class:`~pysnmp.proto.rfc1902.Integer`-based class. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Gauge32(1234) Gauge32(1234) >>> Gauge32(1) + 1 Gauge32(2) >>> int(Gauge32(321)) 321 >>> """ tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) ) subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint( 0, 4294967295 ) class Unsigned32(univ.Integer): """Creates an instance of SNMP Unsigned32 class. :py:class:`~pysnmp.proto.rfc1902.Unsigned32` type represents integer-valued information between 0 and 4294967295 (:RFC:`1902#section-7.1.11`). Parameters ---------- initializer : int Python integer in range between 0 to 4294967295 inclusive or any :py:class:`~pysnmp.proto.rfc1902.Integer`-based class. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Unsigned32(1234) Unsigned32(1234) >>> Unsigned32(1) + 1 Unsigned32(2) >>> int(Unsigned32(321)) 321 >>> """ tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) ) subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint( 0, 4294967295 ) class TimeTicks(univ.Integer): """Creates an instance of SNMP TimeTicks class. :py:class:`~pysnmp.proto.rfc1902.TimeTicks` type represents a non-negative integer which represents the time, modulo 4294967296, in hundredths of a second between two epochs (:RFC:`1902#section-7.1.8`). Parameters ---------- initializer : int Python integer in range between 0 to 4294967295 inclusive or any :py:class:`~pysnmp.proto.rfc1902.Integer`-based class. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> TimeTicks(1234) TimeTicks(1234) >>> TimeTicks(1) + 1 TimeTicks(2) >>> int(TimeTicks(321)) 321 >>> """ tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) ) subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint( 0, 4294967295 ) class Opaque(univ.OctetString): """Creates an instance of SNMP Opaque class. The :py:class:`~pysnmp.proto.rfc1902.Opaque` type supports the capability to pass arbitrary ASN.1 syntax. A value is encoded using the ASN.1 BER into a string of octets. This, in turn, is encoded as an OCTET STRING, in effect "double-wrapping" the original ASN.1 value (:RFC:`1902#section-7.1.9`). Parameters ---------- strValue : str Python string or :py:class:`~pysnmp.proto.rfc1902.OctetString`-based class instance. Other parameters ---------------- hexValue : str Python string representing octets in a hexadecimal notation (e.g. DEADBEEF). Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Opaque('some apples') Opaque('some apples') >>> Opaque('some apples') + ' and oranges' Opaque('some apples and oranges') >>> str(Opaque('some apples')) 'some apples' >>> str(Opaque(hexValue='deadbeef')) '\xde\xad\xbe\xef' >>> """ tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) ) class Counter64(univ.Integer): """Creates an instance of SNMP Counter64 class. :py:class:`~pysnmp.proto.rfc1902.Counter64` type represents a non-negative integer which monotonically increases until it reaches a maximum value of 18446744073709551615, when it wraps around and starts increasing again from zero (:RFC:`1902#section-7.1.10`). Parameters ---------- initializer : int Python integer in range between 0 to 4294967295 inclusive or any :py:class:`~pysnmp.proto.rfc1902.Integer`-based class. Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> Counter64(1234) Counter64(1234) >>> Counter64(1) + 1 Counter64(2) >>> int(Counter64(321)) 321 >>> """ tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x06) ) subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint( 0, 18446744073709551615 ) class Bits(OctetString): """Creates an instance of SNMP BITS class. The :py:class:`~pysnmp.proto.rfc1902.Bits` type represents an enumeration of named bits. This collection is assigned non-negative, contiguous values, starting at zero. Only those named-bits so enumerated may be present in a value (:RFC:`1902#section-7.1.4`). The bits are named and identified by their position in the octet string. Position zero is the high order (or left-most) bit in the first octet of the string. Position 7 is the low order (or right-most) bit of the first octet of the string. Position 8 is the high order bit in the second octet of the string, and so on (`BITS Pseudotype `_). Parameters ---------- strValue : str, tuple Sequence of bit names or a Python string (as a raw data) or :py:class:`~pysnmp.proto.rfc1902.OctetString` class instance. Other parameters ---------------- hexValue : str Python string representing octets in a hexadecimal notation (e.g. DEADBEEF). Raises ------ PyAsn1Error : On constraint violation or bad initializer. Examples -------- >>> from pysnmp.proto.rfc1902 import * >>> SomeBits = Bits.withNamedBits(apple=0, orange=1, peach=2) >>> SomeBits(('apple', 'orange')).prettyPrint() 'apple, orange' >>> SomeBits(('apple', 'orange')) Bits(hexValue='c0') >>> SomeBits('\x80') Bits(hexValue='80') >>> SomeBits(hexValue='80') Bits(hexValue='80') >>> SomeBits(hexValue='80').prettyPrint() 'apple' >>> """ namedValues = namedval.NamedValues() def __new__(cls, *args, **kwargs): if 'namedValues' in kwargs: Bits = cls.withNamedBits(**dict(kwargs.pop('namedValues'))) return Bits(*args, **kwargs) return OctetString.__new__(cls) def prettyIn(self, bits): if not isinstance(bits, (tuple, list)): return 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] |= 0x01 << (7 - m) return OctetString.prettyIn(self, octets) def prettyOut(self, value): names = [] ints = self.__class__(value).asNumbers() for i, v in enumerate(ints): v = ints[i] j = 7 while j >= 0: if v & (0x01 << j): name = self.namedValues.getName(i * 8 + 7 - j) if name is None: name = 'UnknownBit-%s' % (i * 8 + 7 - j,) names.append(name) j -= 1 return ', '.join([str(x) for x in names]) @classmethod def withNamedBits(cls, **values): """Creates a subclass with discreet named bits constraint. Reduce fully duplicate enumerations along the way. """ enums = set(cls.namedValues.items()) enums.update(values.items()) class X(cls): namedValues = namedval.NamedValues(*enums) X.__name__ = cls.__name__ return X class ObjectName(univ.ObjectIdentifier): pass class SimpleSyntax(rfc1155.TypeCoercionHackMixIn, univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('integer-value', Integer()), namedtype.NamedType('string-value', OctetString()), namedtype.NamedType('objectID-value', univ.ObjectIdentifier()) ) class ApplicationSyntax(rfc1155.TypeCoercionHackMixIn, univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('ipAddress-value', IpAddress()), namedtype.NamedType('counter-value', Counter32()), namedtype.NamedType('timeticks-value', TimeTicks()), namedtype.NamedType('arbitrary-value', Opaque()), namedtype.NamedType('big-counter-value', Counter64()), # This conflicts with Counter32 # namedtype.NamedType('unsigned-integer-value', Unsigned32()), namedtype.NamedType('gauge32-value', Gauge32()) ) # BITS misplaced? class ObjectSyntax(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('simple', SimpleSyntax()), namedtype.NamedType('application-wide', ApplicationSyntax()) ) pysnmp-4.4.12/pysnmp/proto/rfc1905.py000066400000000000000000000130441354244100700172660ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import univ, tag, constraint, namedtype, namedval from pysnmp.proto import rfc1902 __all__ = ['unSpecified', 'EndOfMibView', 'ReportPDU', 'UnSpecified', 'BulkPDU', 'SNMPv2TrapPDU', 'GetRequestPDU', 'NoSuchObject', 'GetNextRequestPDU', 'GetBulkRequestPDU', 'NoSuchInstance', 'ResponsePDU', 'noSuchObject', 'InformRequestPDU', 'endOfMibView', 'SetRequestPDU', 'noSuchInstance'] # Value reference -- max bindings in VarBindList max_bindings = rfc1902.Integer(2147483647) # Take SNMP exception values out of BindValue structure for convenience UnSpecified = univ.Null unSpecified = UnSpecified('') class NoSuchObject(univ.Null): tagSet = univ.Null.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0x00) ) def prettyPrint(self, scope=0): return 'No Such Object currently exists at this OID' noSuchObject = NoSuchObject('') class NoSuchInstance(univ.Null): tagSet = univ.Null.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0x01) ) def prettyPrint(self, scope=0): return 'No Such Instance currently exists at this OID' noSuchInstance = NoSuchInstance('') class EndOfMibView(univ.Null): tagSet = univ.Null.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0x02) ) def prettyPrint(self, scope=0): return 'No more variables left in this MIB View' endOfMibView = EndOfMibView('') # Made a separate class for better readability class _BindValue(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('value', rfc1902.ObjectSyntax()), namedtype.NamedType('unSpecified', unSpecified), namedtype.NamedType('noSuchObject', noSuchObject), namedtype.NamedType('noSuchInstance', noSuchInstance), namedtype.NamedType('endOfMibView', endOfMibView) ) class VarBind(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('name', rfc1902.ObjectName()), namedtype.NamedType('', _BindValue()) ) class VarBindList(univ.SequenceOf): componentType = VarBind() subtypeSpec = univ.SequenceOf.subtypeSpec + constraint.ValueSizeConstraint( 0, max_bindings ) errorStatus = univ.Integer( namedValues=namedval.NamedValues( ('noError', 0), ('tooBig', 1), ('noSuchName', 2), ('badValue', 3), ('readOnly', 4), ('genErr', 5), ('noAccess', 6), ('wrongType', 7), ('wrongLength', 8), ('wrongEncoding', 9), ('wrongValue', 10), ('noCreation', 11), ('inconsistentValue', 12), ('resourceUnavailable', 13), ('commitFailed', 14), ('undoFailed', 15), ('authorizationError', 16), ('notWritable', 17), ('inconsistentName', 18)) ) # Base class for a non-bulk PDU class PDU(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', rfc1902.Integer32()), namedtype.NamedType('error-status', errorStatus), namedtype.NamedType('error-index', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings))), namedtype.NamedType('variable-bindings', VarBindList()) ) nonRepeaters = univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings)) maxRepetitions = univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings)) # Base class for bulk PDU class BulkPDU(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('request-id', rfc1902.Integer32()), namedtype.NamedType('non-repeaters', nonRepeaters), namedtype.NamedType('max-repetitions', maxRepetitions), namedtype.NamedType('variable-bindings', VarBindList()) ) class GetRequestPDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0) ) class GetNextRequestPDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1) ) class ResponsePDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 2) ) class SetRequestPDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3) ) class GetBulkRequestPDU(BulkPDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 5) ) class InformRequestPDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 6) ) class SNMPv2TrapPDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 7) ) class ReportPDU(PDU): tagSet = PDU.tagSet.tagImplicitly( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 8) ) class PDUs(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('get-request', GetRequestPDU()), namedtype.NamedType('get-next-request', GetNextRequestPDU()), namedtype.NamedType('get-bulk-request', GetBulkRequestPDU()), namedtype.NamedType('response', ResponsePDU()), namedtype.NamedType('set-request', SetRequestPDU()), namedtype.NamedType('inform-request', InformRequestPDU()), namedtype.NamedType('snmpV2-trap', SNMPv2TrapPDU()), namedtype.NamedType('report', ReportPDU()) ) pysnmp-4.4.12/pysnmp/proto/rfc3411.py000066400000000000000000000025331354244100700172610ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import rfc1157, rfc1905 readClassPDUs = { rfc1157.GetRequestPDU.tagSet: 1, rfc1157.GetNextRequestPDU.tagSet: 1, rfc1905.GetRequestPDU.tagSet: 1, rfc1905.GetNextRequestPDU.tagSet: 1, rfc1905.GetBulkRequestPDU.tagSet: 1 } writeClassPDUs = { rfc1157.SetRequestPDU.tagSet: 1, rfc1905.SetRequestPDU.tagSet: 1 } responseClassPDUs = { rfc1157.GetResponsePDU.tagSet: 1, rfc1905.ResponsePDU.tagSet: 1, rfc1905.ReportPDU.tagSet: 1 } notificationClassPDUs = { rfc1157.TrapPDU.tagSet: 1, rfc1905.SNMPv2TrapPDU.tagSet: 1, rfc1905.InformRequestPDU.tagSet: 1 } internalClassPDUs = { rfc1905.ReportPDU.tagSet: 1 } confirmedClassPDUs = { rfc1157.GetRequestPDU.tagSet: 1, rfc1157.GetNextRequestPDU.tagSet: 1, rfc1157.SetRequestPDU.tagSet: 1, rfc1905.GetRequestPDU.tagSet: 1, rfc1905.GetNextRequestPDU.tagSet: 1, rfc1905.GetBulkRequestPDU.tagSet: 1, rfc1905.SetRequestPDU.tagSet: 1, rfc1905.InformRequestPDU.tagSet: 1 } unconfirmedClassPDUs = { rfc1157.GetResponsePDU.tagSet: 1, rfc1905.ResponsePDU.tagSet: 1, rfc1157.TrapPDU.tagSet: 1, rfc1905.ReportPDU.tagSet: 1, rfc1905.SNMPv2TrapPDU.tagSet: 1 } pysnmp-4.4.12/pysnmp/proto/rfc3412.py000066400000000000000000000524401354244100700172640ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pyasn1.compat.octets import null from pyasn1.error import PyAsn1Error from pysnmp.smi import builder, instrum from pysnmp.proto import errind, error, cache from pysnmp.proto.api import verdec # XXX from pysnmp.error import PySnmpError from pysnmp import nextid, debug class MsgAndPduDispatcher(object): """SNMP engine PDU & message dispatcher. Exchanges SNMP PDU's with applications and serialized messages with transport level. """ def __init__(self, mibInstrumController=None): if mibInstrumController is None: self.mibInstrumController = instrum.MibInstrumController( builder.MibBuilder() ) else: self.mibInstrumController = mibInstrumController self.mibInstrumController.mibBuilder.loadModules( 'SNMPv2-MIB', 'SNMP-MPD-MIB', 'SNMP-COMMUNITY-MIB', 'SNMP-TARGET-MIB', 'SNMP-USER-BASED-SM-MIB' ) # Requests cache self.__cache = cache.Cache() # Registered context engine IDs self.__appsRegistration = {} # Source of sendPduHandle and cache of requesting apps self.__sendPduHandle = nextid.Integer(0xffffff) # To pass transport info to app (legacy) self.__transportInfo = {} # legacy def getTransportInfo(self, stateReference): if stateReference in self.__transportInfo: return self.__transportInfo[stateReference] else: raise error.ProtocolError( 'No data for stateReference %s' % stateReference ) # Application registration with dispatcher # 4.3.1 def registerContextEngineId(self, contextEngineId, pduTypes, processPdu): """Register application with dispatcher""" # 4.3.2 -> no-op # 4.3.3 for pduType in pduTypes: k = (contextEngineId, pduType) if k in self.__appsRegistration: raise error.ProtocolError( 'Duplicate registration %r/%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, 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 %d ticks, one tick is %s seconds' % ( snmpEngine.transportDispatcher.getTimerTicks(), snmpEngine.transportDispatcher.getTimerResolution())) debug.logger & debug.flagDsp and debug.logger( 'sendPdu: new sendPduHandle %s, timeout %s ticks, cbFun %s' % (sendPduHandle, timeout, cbFun)) origTransportDomain = transportDomain origTransportAddress = transportAddress # 4.1.1.4 & 4.1.1.5 try: (transportDomain, transportAddress, outgoingMessage) = mpHandler.prepareOutgoingMessage( snmpEngine, origTransportDomain, origTransportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, expectResponse, sendPduHandle ) debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded') except PySnmpError: if expectResponse: self.__cache.pop(sendPduHandle) self.releaseStateInformation(snmpEngine, sendPduHandle, messageProcessingModel) raise # 4.1.1.6 if snmpEngine.transportDispatcher is None: if expectResponse: self.__cache.pop(sendPduHandle) raise error.PySnmpError('Transport dispatcher not set') snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.sendPdu', dict(transportDomain=transportDomain, transportAddress=transportAddress, outgoingMessage=outgoingMessage, messageProcessingModel=messageProcessingModel, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, pdu=PDU) ) try: snmpEngine.transportDispatcher.sendMessage( outgoingMessage, transportDomain, transportAddress ) except PySnmpError: if expectResponse: self.__cache.pop(sendPduHandle) raise snmpEngine.observer.clearExecutionContext(snmpEngine, 'rfc3412.sendPdu') # Update cache with orignal req params (used for retrying) if expectResponse: self.__cache.update(sendPduHandle, transportDomain=origTransportDomain, transportAddress=origTransportAddress, 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): # 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: (transportDomain, transportAddress, 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 += 1 raise error.StatusInformation(errorIndication=errind.tooBig) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.returnResponsePdu', dict(transportDomain=transportDomain, transportAddress=transportAddress, outgoingMessage=outgoingMessage, messageProcessingModel=messageProcessingModel, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, pdu=PDU) ) # 4.1.2.4 snmpEngine.transportDispatcher.sendMessage(outgoingMessage, transportDomain, transportAddress) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.returnResponsePdu' ) # 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 += 1 # 4.2.1.2 try: restOfWholeMsg = null # XXX fix decoder non-recursive return msgVersion = verdec.decodeMessageVersion(wholeMsg) except error.ProtocolError: snmpInASNParseErrs, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax += 1 return null # n.b the whole buffer gets dropped debug.logger & debug.flagDsp and debug.logger('receiveMessage: msgVersion %s, msg decoded' % msgVersion) messageProcessingModel = msgVersion try: mpHandler = snmpEngine.messageProcessingSubsystems[int(messageProcessingModel)] except KeyError: snmpInBadVersions, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadVersions') 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, forcing a retry' % statusInformation) self.__expireRequest( statusInformation['sendPduHandle'], self.__cache.pop(statusInformation['sendPduHandle']), snmpEngine, statusInformation ) return restOfWholeMsg except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('receiveMessage: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax += 1 return restOfWholeMsg debug.logger & debug.flagDsp and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint()) # 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 += 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') # 4.2.2.1.2.c try: (destTransportDomain, destTransportAddress, outgoingMessage) = mpHandler.prepareResponseMessage( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference, statusInformation ) snmpEngine.transportDispatcher.sendMessage( outgoingMessage, destTransportDomain, destTransportAddress ) except PySnmpError: debug.logger & debug.flagDsp and debug.logger( 'receiveMessage: report failed, statusInformation %s' % sys.exc_info()[1]) else: debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded') # 4.2.2.1.2.d return restOfWholeMsg else: snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.receiveMessage:request', dict(transportDomain=transportDomain, transportAddress=transportAddress, wholeMsg=wholeMsg, messageProcessingModel=messageProcessingModel, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, pdu=PDU) ) # pass transport info to app (legacy) 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) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.receiveMessage:request' ) # legacy 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 += 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 snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3412.receiveMessage:response', dict(transportDomain=transportDomain, transportAddress=transportAddress, wholeMsg=wholeMsg, messageProcessingModel=messageProcessingModel, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, pdu=PDU) ) # 4.2.2.2.4 processResponsePdu = cachedParams['cbFun'] processResponsePdu(snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, cachedParams['sendPduHandle'], cachedParams['cbCtx']) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3412.receiveMessage:response' ) 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) self.__cache.pop(sendPduHandle) # Cache expiration stuff # noinspection PyUnusedLocal 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 True # noinspection PyUnusedLocal def receiveTimerTick(self, snmpEngine, timeNow): self.__cache.expire(self.__expireRequest, snmpEngine) pysnmp-4.4.12/pysnmp/proto/secmod/000077500000000000000000000000001354244100700170735ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/__init__.py000066400000000000000000000000731354244100700212040ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/base.py000066400000000000000000000027221354244100700203620ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.secmod import cache from pysnmp.proto import error class AbstractSecurityModel(object): 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 pysnmp-4.4.12/pysnmp/proto/secmod/cache.py000066400000000000000000000015741354244100700205170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp import nextid from pysnmp.proto import error class Cache(object): __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 pysnmp-4.4.12/pysnmp/proto/secmod/eso/000077500000000000000000000000001354244100700176615ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/eso/__init__.py000066400000000000000000000000731354244100700217720ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/eso/priv/000077500000000000000000000000001354244100700206415ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/eso/priv/__init__.py000066400000000000000000000000731354244100700227520ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/eso/priv/aes192.py000066400000000000000000000020031354244100700222120ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.secmod.eso.priv import aesbase class AesBlumenthal192(aesbase.AbstractAesBlumenthal): """AES 192 bit encryption (Internet draft) Reeder AES encryption: http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 """ serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol keySize = 24 class Aes192(aesbase.AbstractAesReeder): """AES 192 bit encryption (Internet draft) Reeder AES encryption with non-standard key localization algorithm borrowed from Reeder 3DES draft: http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00 Known to be used by many vendors including Cisco and others. """ serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 101) # cusmAESCfb192PrivProtocol (non-standard OID) keySize = 24 pysnmp-4.4.12/pysnmp/proto/secmod/eso/priv/aes256.py000066400000000000000000000017441354244100700222260ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.secmod.eso.priv import aesbase class AesBlumenthal256(aesbase.AbstractAesBlumenthal): """AES 256 bit encryption (Internet draft) http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 """ serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol keySize = 32 class Aes256(aesbase.AbstractAesReeder): """AES 256 bit encryption (Internet draft) Reeder AES encryption with non-standard key localization algorithm borrowed from Reeder 3DES draft: http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00 Known to be used by many vendors including Cisco and others. """ serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 102) # cusmAESCfb256PrivProtocol (non-standard OID) keySize = 32 pysnmp-4.4.12/pysnmp/proto/secmod/eso/priv/aesbase.py000066400000000000000000000062121354244100700226170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.secmod.rfc3826.priv import aes from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc7860.auth import hmacsha2 from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import error from math import ceil try: from hashlib import md5, sha1 except ImportError: import md5 import sha md5 = md5.new sha1 = sha.new class AbstractAesBlumenthal(aes.Aes): serviceID = () keySize = 0 # 3.1.2.1 def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo) # now extend this key if too short by repeating steps that includes the hashPassphrase step for count in range(1, int(ceil(self.keySize * 1.0 / len(localPrivKey)))): localPrivKey += localPrivKey.clone( hashAlgo(localPrivKey.asOctets()).digest()) return localPrivKey[:self.keySize] class AbstractAesReeder(aes.Aes): """AES encryption with non-standard key localization. Many vendors (including Cisco) do not use: https://tools.itef.org/pdf/draft_bluementhal-aes-usm-04.txt for key localization instead, they use the procedure for 3DES key localization specified in: https://tools.itef.org/pdf/draft_reeder_snmpv3-usm-3desede-00.pdf The difference between the two is that the Reeder draft does key extension by repeating the steps in the password to key algorithm (hash phrase, then localize with SNMPEngine ID). """ serviceID = () keySize = 0 # 2.1 of https://tools.itef.org/pdf/draft_bluementhal-aes-usm-04.txt def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo) # now extend this key if too short by repeating steps that includes the hashPassphrase step while len(localPrivKey) < self.keySize: # this is the difference between reeder and bluementhal newKey = localkey.hashPassphrase(localPrivKey, hashAlgo) localPrivKey += localkey.localizeKey(newKey, snmpEngineID, hashAlgo) return localPrivKey[:self.keySize] pysnmp-4.4.12/pysnmp/proto/secmod/eso/priv/des3.py000066400000000000000000000121661354244100700220570ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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.secmod.rfc7860.auth import hmacsha2 from pysnmp.proto import errind, error from pyasn1.type import univ from pyasn1.compat.octets import null from math import ceil try: from hashlib import md5, sha1 except ImportError: import md5 import sha md5 = md5.new sha1 = sha.new try: from Cryptodome.Cipher import DES3 except ImportError: DES3 = None random.seed() # 5.1.1 class Des3(base.AbstractEncryptionService): """Reeder 3DES-EDE for USM (Internet draft). https://tools.ietf.org/html/draft-reeder-snmpv3-usm-3desede-00 """ serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol keySize = 32 _localInt = random.randrange(0, 0xffffffff) def hashPassphrase(self, authProtocol, privKey): if authProtocol == hmacmd5.HmacMd5.serviceID: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localkey.hashPassphrase(privKey, hashAlgo) # 2.1 def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo) # now extend this key if too short by repeating steps that includes the hashPassphrase step while len(localPrivKey) < self.keySize: # this is the difference between reeder and bluementhal newKey = localkey.hashPassphrase(localPrivKey, hashAlgo) localPrivKey += localkey.localizeKey(newKey, snmpEngineID, hashAlgo) return localPrivKey[:self.keySize] # 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 += 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()) @staticmethod def __getDecryptionKey(privKey, salt): return (privKey[:24].asOctets(), univ.OctetString(map(lambda x, y: x ^ y, salt.asNumbers(), privKey[24:32].asNumbers())).asOctets()) # 5.1.1.2 def encryptData(self, encryptKey, privParameters, dataToEncrypt): if DES3 is None: raise error.StatusInformation( errorIndication=errind.encryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters des3Key, salt, iv = self.__getEncryptionKey( encryptKey, snmpEngineBoots ) des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) privParameters = univ.OctetString(salt) plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets() ciphertext = des3Obj.encrypt(plaintext) 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) ciphertext = encryptedData.asOctets() plaintext = des3Obj.decrypt(ciphertext) return plaintext pysnmp-4.4.12/pysnmp/proto/secmod/rfc2576.py000066400000000000000000000520661354244100700205540ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pyasn1.codec.ber import encoder from pyasn1.error import PyAsn1Error from pysnmp.proto.secmod import base from pysnmp.carrier.asyncore.dgram import udp, udp6, unix 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 __init__(self): self.__transportBranchId = self.__paramsBranchId = self.__communityBranchId = self.__securityBranchId = -1 base.AbstractSecurityModel.__init__(self) def _sec2com(self, snmpEngine, securityName, contextEngineId, contextName): snmpTargetParamsSecurityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetParamsSecurityName') if self.__paramsBranchId != snmpTargetParamsSecurityName.branchVersionId: snmpTargetParamsSecurityModel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetParamsSecurityModel') self.__nameToModelMap = {} nextMibNode = snmpTargetParamsSecurityName while True: try: nextMibNode = snmpTargetParamsSecurityName.getNextNode(nextMibNode.name) except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpTargetParamsSecurityName.name):] mibNode = snmpTargetParamsSecurityModel.getNode(snmpTargetParamsSecurityModel.name + instId) try: if mibNode.syntax not in self.__nameToModelMap: self.__nameToModelMap[nextMibNode.syntax] = set() self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '_sec2com: table entries %r/%r hashing failed' % ( nextMibNode.syntax, mibNode.syntax) ) continue self.__paramsBranchId = snmpTargetParamsSecurityName.branchVersionId # invalidate next map as it include this one self.__securityBranchId = -1 snmpCommunityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityName') if self.__securityBranchId != snmpCommunityName.branchVersionId: (snmpCommunitySecurityName, snmpCommunityContextEngineId, snmpCommunityContextName) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-COMMUNITY-MIB', 'snmpCommunitySecurityName', 'snmpCommunityContextEngineID', 'snmpCommunityContextName' ) self.__securityMap = {} nextMibNode = snmpCommunityName while True: try: nextMibNode = snmpCommunityName.getNextNode(nextMibNode.name) except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpCommunityName.name):] _securityName = snmpCommunitySecurityName.getNode(snmpCommunitySecurityName.name + instId).syntax _contextEngineId = snmpCommunityContextEngineId.getNode( snmpCommunityContextEngineId.name + instId).syntax _contextName = snmpCommunityContextName.getNode(snmpCommunityContextName.name + instId).syntax try: self.__securityMap[(_securityName, _contextEngineId, _contextName)] = nextMibNode.syntax except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '_sec2com: table entries %r/%r/%r hashing failed' % ( _securityName, _contextEngineId, _contextName) ) continue self.__securityBranchId = snmpCommunityName.branchVersionId debug.logger & debug.flagSM and debug.logger( '_sec2com: built securityName to communityName map, version %s: %s' % ( self.__securityBranchId, self.__securityMap)) try: return self.__securityMap[(securityName, contextEngineId, contextName)] except KeyError: raise error.StatusInformation( errorIndication=errind.unknownCommunityName ) def _com2sec(self, snmpEngine, communityName, transportInformation): snmpTargetAddrTAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetAddrTAddress') if self.__transportBranchId != snmpTargetAddrTAddress.branchVersionId: (SnmpTagValue, snmpTargetAddrTDomain, snmpTargetAddrTagList) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'SnmpTagValue', 'snmpTargetAddrTDomain', 'snmpTargetAddrTagList' ) self.__emptyTag = SnmpTagValue('') self.__transportToTagMap = {} nextMibNode = snmpTargetAddrTagList while True: 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)) elif targetAddrTDomain[:len(unix.snmpLocalDomain)] == unix.snmpLocalDomain: targetAddrTAddress = str(targetAddrTAddress) targetAddr = targetAddrTDomain, targetAddrTAddress targetAddrTagList = snmpTargetAddrTagList.getNode(snmpTargetAddrTagList.name + instId).syntax if targetAddr not in self.__transportToTagMap: self.__transportToTagMap[targetAddr] = set() try: if targetAddrTagList: self.__transportToTagMap[targetAddr].update( [SnmpTagValue(x) for x in targetAddrTagList.asOctets().split()] ) else: self.__transportToTagMap[targetAddr].add(self.__emptyTag) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '_com2sec: table entries %r/%r hashing failed' % ( targetAddr, targetAddrTagList) ) continue self.__transportBranchId = snmpTargetAddrTAddress.branchVersionId debug.logger & debug.flagSM and debug.logger('_com2sec: built transport-to-tag map version %s: %s' % ( self.__transportBranchId, self.__transportToTagMap)) snmpTargetParamsSecurityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetParamsSecurityName') if self.__paramsBranchId != snmpTargetParamsSecurityName.branchVersionId: snmpTargetParamsSecurityModel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-TARGET-MIB', 'snmpTargetParamsSecurityModel') self.__nameToModelMap = {} nextMibNode = snmpTargetParamsSecurityName while True: try: nextMibNode = snmpTargetParamsSecurityName.getNextNode(nextMibNode.name) except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpTargetParamsSecurityName.name):] mibNode = snmpTargetParamsSecurityModel.getNode(snmpTargetParamsSecurityModel.name + instId) try: if nextMibNode.syntax not in self.__nameToModelMap: self.__nameToModelMap[nextMibNode.syntax] = set() self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '_com2sec: table entries %r/%r hashing failed' % ( nextMibNode.syntax, mibNode.syntax) ) continue self.__paramsBranchId = snmpTargetParamsSecurityName.branchVersionId # invalidate next map as it include this one self.__communityBranchId = -1 debug.logger & debug.flagSM and debug.logger( '_com2sec: built securityName to securityModel map, version %s: %s' % ( self.__paramsBranchId, self.__nameToModelMap)) snmpCommunityName, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-COMMUNITY-MIB', 'snmpCommunityName') if self.__communityBranchId != snmpCommunityName.branchVersionId: (snmpCommunitySecurityName, snmpCommunityContextEngineId, snmpCommunityContextName, snmpCommunityTransportTag) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-COMMUNITY-MIB', 'snmpCommunitySecurityName', 'snmpCommunityContextEngineID', 'snmpCommunityContextName', 'snmpCommunityTransportTag' ) self.__communityToTagMap = {} self.__tagAndCommunityToSecurityMap = {} nextMibNode = snmpCommunityName while True: try: nextMibNode = snmpCommunityName.getNextNode(nextMibNode.name) except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpCommunityName.name):] securityName = snmpCommunitySecurityName.getNode(snmpCommunitySecurityName.name + instId).syntax contextEngineId = snmpCommunityContextEngineId.getNode( snmpCommunityContextEngineId.name + instId).syntax contextName = snmpCommunityContextName.getNode(snmpCommunityContextName.name + instId).syntax transportTag = snmpCommunityTransportTag.getNode(snmpCommunityTransportTag.name + instId).syntax _tagAndCommunity = transportTag, nextMibNode.syntax try: if _tagAndCommunity not in self.__tagAndCommunityToSecurityMap: self.__tagAndCommunityToSecurityMap[_tagAndCommunity] = set() self.__tagAndCommunityToSecurityMap[_tagAndCommunity].add( (securityName, contextEngineId, contextName) ) if nextMibNode.syntax not in self.__communityToTagMap: self.__communityToTagMap[nextMibNode.syntax] = set() self.__communityToTagMap[nextMibNode.syntax].add(transportTag) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '_com2sec: table entries %r/%r hashing failed' % ( _tagAndCommunity, nextMibNode.syntax) ) continue self.__communityBranchId = snmpCommunityName.branchVersionId debug.logger & debug.flagSM and debug.logger( '_com2sec: built communityName to tag map (securityModel %s), version %s: %s' % ( self.securityModelID, self.__communityBranchId, self.__communityToTagMap)) debug.logger & debug.flagSM and debug.logger( '_com2sec: built tag & community to securityName map (securityModel %s), version %s: %s' % ( self.securityModelID, self.__communityBranchId, self.__tagAndCommunityToSecurityMap)) if communityName in self.__communityToTagMap: if transportInformation in self.__transportToTagMap: tags = self.__transportToTagMap[transportInformation].intersection( self.__communityToTagMap[communityName]) elif self.__emptyTag in self.__communityToTagMap[communityName]: tags = [self.__emptyTag] else: raise error.StatusInformation(errorIndication=errind.unknownCommunityName) candidateSecurityNames = [] for x in [self.__tagAndCommunityToSecurityMap[(t, communityName)] for t in tags]: candidateSecurityNames.extend(list(x)) # 5.2.1 (row selection in snmpCommunityTable) # Picks first match but favors entries already in targets table if candidateSecurityNames: candidateSecurityNames.sort( key=lambda x, m=self.__nameToModelMap, v=self.securityModelID: ( not int(x[0] in m and v in m[x[0]]), str(x[0])) ) chosenSecurityName = candidateSecurityNames[0] # min() debug.logger & debug.flagSM and debug.logger( '_com2sec: securityName candidates for communityName \'%s\' are %s; choosing securityName \'%s\'' % ( communityName, candidateSecurityNames, chosenSecurityName[0])) return chosenSecurityName raise error.StatusInformation(errorIndication=errind.unknownCommunityName) def generateRequestMsg(self, snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineId, securityName, securityLevel, scopedPDU): msg, = globalData contextEngineId, contextName, pdu = scopedPDU # rfc2576: 5.2.3 communityName = self._sec2com(snmpEngine, securityName, contextEngineId, contextName) debug.logger & debug.flagSM and debug.logger( 'generateRequestMsg: using community %r for securityModel %r, securityName %r, contextEngineId %r contextName %r' % ( communityName, securityModel, securityName, contextEngineId, contextName)) securityParameters = communityName msg.setComponentByPosition(1, securityParameters) msg.setComponentByPosition(2) msg.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False, matchTags=False, matchConstraints=False ) debug.logger & debug.flagMP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),)) try: return securityParameters, encoder.encode(msg) except PyAsn1Error: debug.logger & debug.flagMP and debug.logger( 'generateRequestMsg: serialization failure: %s' % sys.exc_info()[1]) raise error.StatusInformation(errorIndication=errind.serializationError) 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, matchTags=False, matchConstraints=False ) debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),)) try: return communityName, encoder.encode(msg) except PyAsn1Error: debug.logger & debug.flagMP and debug.logger( 'generateResponseMsg: serialization failure: %s' % sys.exc_info()[1]) raise error.StatusInformation(errorIndication=errind.serializationError) def processIncomingMsg(self, snmpEngine, messageProcessingModel, maxMessageSize, securityParameters, securityModel, securityLevel, wholeMsg, msg): # rfc2576: 5.2.1 communityName, transportInformation = securityParameters scope = dict(communityName=communityName, transportInformation=transportInformation) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.processIncomingMsg:writable', scope ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.processIncomingMsg:writable' ) try: securityName, contextEngineId, contextName = self._com2sec( snmpEngine, scope.get('communityName', communityName), scope.get('transportInformation', transportInformation) ) except error.StatusInformation: snmpInBadCommunityNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( '__SNMPv2-MIB', 'snmpInBadCommunityNames') snmpInBadCommunityNames.syntax += 1 raise error.StatusInformation( errorIndication=errind.unknownCommunityName, communityName=communityName ) snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') securityEngineID = snmpEngineID.syntax snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.processIncomingMsg', dict(transportInformation=transportInformation, securityEngineId=securityEngineID, securityName=securityName, communityName=communityName, contextEngineId=contextEngineId, contextName=contextName) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc2576.processIncomingMsg' ) debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: looked up securityName %r securityModel %r contextEngineId %r contextName %r by communityName %r AND transportInformation %r' % ( securityName, self.securityModelID, contextEngineId, contextName, communityName, transportInformation)) stateReference = self._cache.push(communityName=communityName) scopedPDU = (contextEngineId, contextName, msg.getComponentByPosition(2).getComponent()) maxSizeResponseScopedPDU = maxMessageSize - 128 securityStateReference = stateReference debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: generated maxSizeResponseScopedPDU %s securityStateReference %s' % ( maxSizeResponseScopedPDU, securityStateReference)) return (securityEngineID, securityName, scopedPDU, maxSizeResponseScopedPDU, securityStateReference) class SnmpV2cSecurityModel(SnmpV1SecurityModel): securityModelID = 2 # XXX # contextEngineId/contextName goes to globalData pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/000077500000000000000000000000001354244100700201615ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/__init__.py000066400000000000000000000004021354244100700222660ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto.secmod.rfc3414 import service SnmpUSMSecurityModel = service.SnmpUSMSecurityModel pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/auth/000077500000000000000000000000001354244100700211225ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/auth/__init__.py000066400000000000000000000000731354244100700232330ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/auth/base.py000066400000000000000000000015271354244100700224130ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import errind, error class AbstractAuthenticationService(object): serviceID = None def hashPassphrase(self, authKey): raise error.ProtocolError(errind.noAuthentication) def localizeKey(self, authKey, snmpEngineID): raise error.ProtocolError(errind.noAuthentication) @property def digestLength(self): 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) pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py000066400000000000000000000071721354244100700230210ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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) @property def digestLength(self): return 12 # 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 --> no-op # 6.3.1.2c k1 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad) ) # 6.3.1.2d --> no-op # 6.3.1.2e k2 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__opad) ) # 6.3.1.3 # noinspection PyDeprecation,PyCallingNonCallable d1 = md5(k1.asOctets() + wholeMsg).digest() # 6.3.1.4 # noinspection PyDeprecation,PyCallingNonCallable 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 --> no-op # 6.3.2.4c k1 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad) ) # 6.3.2.4d --> no-op # 6.3.2.4e k2 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__opad) ) # 6.3.2.5a # noinspection PyDeprecation,PyCallingNonCallable d1 = md5(k1.asOctets() + authenticatedWholeMsg).digest() # 6.3.2.5b # noinspection PyDeprecation,PyCallingNonCallable 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 pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py000066400000000000000000000066111354244100700231040ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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) @property def digestLength(self): return 12 # 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 -- no-op # 7.3.1.2c k1 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad) ) # 7.3.1.2d -- no-op # 7.3.1.2e k2 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__opad) ) # 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 --> no-op # 7.3.2.4c k1 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__ipad) ) # 7.3.2.4d --> no-op # 7.3.2.4e k2 = univ.OctetString( map(lambda x, y: x ^ y, extendedAuthKey, self.__opad) ) # 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 pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/auth/noauth.py000066400000000000000000000014321354244100700227720ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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) pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/localkey.py000066400000000000000000000040571354244100700223440ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # try: from hashlib import md5, sha1 except ImportError: import md5 import sha md5 = md5.new sha1 = sha.new from pyasn1.type import univ def hashPassphrase(passphrase, hashFunc): passphrase = univ.OctetString(passphrase).asOctets() # noinspection PyDeprecation,PyCallingNonCallable hasher = hashFunc() ringBuffer = passphrase * (64 // len(passphrase) + 1) # noinspection PyTypeChecker ringBufferLen = len(ringBuffer) count = 0 mark = 0 while count < 16384: e = mark + 64 if e < ringBufferLen: hasher.update(ringBuffer[mark:e]) mark = e else: hasher.update( ringBuffer[mark:ringBufferLen] + ringBuffer[0:e - ringBufferLen] ) mark = e - ringBufferLen count += 1 digest = hasher.digest() return univ.OctetString(digest) def passwordToKey(passphrase, snmpEngineId, hashFunc): return localizeKey(hashPassphrase(passphrase, hashFunc), snmpEngineId, hashFunc) def localizeKey(passKey, snmpEngineId, hashFunc): passKey = univ.OctetString(passKey).asOctets() # noinspection PyDeprecation,PyCallingNonCallable digest = hashFunc(passKey + snmpEngineId.asOctets() + passKey).digest() return univ.OctetString(digest) # RFC3414: A.2.1 def hashPassphraseMD5(passphrase): return hashPassphrase(passphrase, md5) # RFC3414: A.2.2 def hashPassphraseSHA(passphrase): return hashPassphrase(passphrase, sha1) def passwordToKeyMD5(passphrase, snmpEngineId): return localizeKey(hashPassphraseMD5(passphrase), snmpEngineId, md5) def passwordToKeySHA(passphrase, snmpEngineId): return localizeKey(hashPassphraseMD5(passphrase), snmpEngineId, sha1) def localizeKeyMD5(passKey, snmpEngineId): return localizeKey(passKey, snmpEngineId, md5) def localizeKeySHA(passKey, snmpEngineId): return localizeKey(passKey, snmpEngineId, sha1) pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/priv/000077500000000000000000000000001354244100700211415ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/priv/__init__.py000066400000000000000000000000731354244100700232520ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/priv/base.py000066400000000000000000000013351354244100700224270ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import error class AbstractEncryptionService(object): serviceID = None keySize = 0 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') pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/priv/des.py000066400000000000000000000113541354244100700222720ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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.secmod.rfc7860.auth import hmacsha2 from pysnmp.proto import errind, error from pyasn1.type import univ from sys import version_info try: from Cryptodome.Cipher import DES except ImportError: DES = None try: from hashlib import md5, sha1 except ImportError: import md5 import sha md5 = md5.new sha1 = sha.new random.seed() # 8.2.4 class Des(base.AbstractEncryptionService): serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol keySize = 16 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: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localkey.hashPassphrase(privKey, hashAlgo) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo) return localPrivKey[:self.keySize] # 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 += 1 return (desKey.asOctets(), univ.OctetString(salt).asOctets(), univ.OctetString(map(lambda x, y: x ^ y, salt, preIV.asNumbers())).asOctets()) @staticmethod def __getDecryptionKey(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 no-op # 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()) pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/priv/nopriv.py000066400000000000000000000014441354244100700230330ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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) pysnmp-4.4.12/pysnmp/proto/secmod/rfc3414/service.py000066400000000000000000001552251354244100700222050ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import time import 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.rfc7860.auth import hmacsha2 from pysnmp.proto.secmod.eso.priv import des3, aes192, aes256 from pysnmp.smi.error import NoSuchInstanceError from pysnmp.proto import api, rfc1155, errind, error from pysnmp import debug from pyasn1.type import univ, namedtype, constraint from pyasn1.codec.ber import encoder, decoder, eoo from pyasn1.error import PyAsn1Error from pyasn1.compat.octets import null # API to rfc1905 protocol objects pMod = api.protoModules[api.protoVersion2c] # 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(), hmacsha2.HmacSha2.sha224ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha224ServiceID), hmacsha2.HmacSha2.sha256ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha256ServiceID), hmacsha2.HmacSha2.sha384ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha384ServiceID), hmacsha2.HmacSha2.sha512ServiceID: hmacsha2.HmacSha2(hmacsha2.HmacSha2.sha512ServiceID), noauth.NoAuth.serviceID: noauth.NoAuth(), } privServices = {des.Des.serviceID: des.Des(), des3.Des3.serviceID: des3.Des3(), aes.Aes.serviceID: aes.Aes(), aes192.AesBlumenthal192.serviceID: aes192.AesBlumenthal192(), aes256.AesBlumenthal256.serviceID: aes256.AesBlumenthal256(), aes192.Aes192.serviceID: aes192.Aes192(), # non-standard aes256.Aes256.serviceID: aes256.Aes256(), # non-standard nopriv.NoPriv.serviceID: nopriv.NoPriv()} # If this, normally impossible, SNMP engine ID is present in LCD, we will use # its master/localized keys when preparing SNMP message towards any unknown peer # SNMP engine wildcardSecurityEngineId = pMod.OctetString(hexValue='0000000000') def __init__(self): AbstractSecurityModel.__init__(self) self.__securityParametersSpec = UsmSecurityParameters() self.__timeline = {} self.__timelineExpQueue = {} self.__expirationTimer = 0 self.__paramsBranchId = -1 def __sec2usr(self, snmpEngine, securityName, securityEngineID=None): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder usmUserEngineID, = mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEngineID') if self.__paramsBranchId != usmUserEngineID.branchVersionId: usmUserName, usmUserSecurityName = mibBuilder.importSymbols( 'SNMP-USER-BASED-SM-MIB', 'usmUserName', 'usmUserSecurityName') self.__securityToUserMap = {} nextMibNode = usmUserEngineID while True: try: nextMibNode = usmUserEngineID.getNextNode(nextMibNode.name) except NoSuchInstanceError: self.__paramsBranchId = usmUserEngineID.branchVersionId debug.logger & debug.flagSM and debug.logger( '_sec2usr: built snmpEngineId + securityName to userName map, version %s: %r' % ( self.__paramsBranchId, self.__securityToUserMap)) break instId = nextMibNode.name[len(usmUserSecurityName.name):] __engineID = usmUserEngineID.getNode(usmUserEngineID.name + instId).syntax __userName = usmUserName.getNode(usmUserName.name + instId).syntax __securityName = usmUserSecurityName.getNode(usmUserSecurityName.name + instId).syntax k = __engineID, __securityName # first (lesser) securityName wins if k not in self.__securityToUserMap: self.__securityToUserMap[k] = __userName if securityEngineID is None: snmpEngineID, = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') securityEngineID = snmpEngineID.syntax try: userName = self.__securityToUserMap[(securityEngineID, securityName)] except KeyError: debug.logger & debug.flagSM and debug.logger( '_sec2usr: no entry exists for snmpEngineId %r, securityName %r' % (securityEngineID, securityName)) raise NoSuchInstanceError() # emulate MIB lookup debug.logger & debug.flagSM and debug.logger( '_sec2usr: using userName %r for snmpEngineId %r, securityName %r' % ( userName, securityEngineID, securityName)) return userName @staticmethod def __getUserInfo(mibInstrumController, securityEngineID, userName): usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' ) tblIdx = usmUserEntry.getInstIdFromIndices(securityEngineID, userName) # Get userName & securityName usmUserName = usmUserEntry.getNode(usmUserEntry.name + (2,) + tblIdx).syntax usmUserSecurityName = usmUserEntry.getNode(usmUserEntry.name + (3,) + tblIdx).syntax # Get protocols usmUserAuthProtocol = usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx).syntax usmUserPrivProtocol = usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx).syntax # Get keys pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' ) pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (1,) + tblIdx).syntax pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (2,) + tblIdx).syntax return (usmUserName, usmUserSecurityName, usmUserAuthProtocol, pysnmpUsmKeyAuthLocalized, usmUserPrivProtocol, pysnmpUsmKeyPrivLocalized) def __cloneUserInfo(self, mibInstrumController, securityEngineID, userName): snmpEngineID, = mibInstrumController.mibBuilder.importSymbols( '__SNMP-FRAMEWORK-MIB', 'snmpEngineID' ) # Proto entry usmUserEntry, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-USER-BASED-SM-MIB', 'usmUserEntry' ) tblIdx1 = usmUserEntry.getInstIdFromIndices( snmpEngineID.syntax, userName ) # Get proto protocols usmUserName = usmUserEntry.getNode(usmUserEntry.name + (2,) + tblIdx1) usmUserSecurityName = usmUserEntry.getNode(usmUserEntry.name + (3,) + tblIdx1) usmUserCloneFrom = usmUserEntry.getNode(usmUserEntry.name + (4,) + tblIdx1) usmUserAuthProtocol = usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx1) usmUserPrivProtocol = usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx1) # Get proto keys pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' ) pysnmpUsmKeyAuth = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (3,) + tblIdx1) pysnmpUsmKeyPriv = pysnmpUsmKeyEntry.getNode(pysnmpUsmKeyEntry.name + (4,) + tblIdx1) # Create new row from proto values tblIdx2 = usmUserEntry.getInstIdFromIndices(securityEngineID, userName) # New row mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx2, 4),) ) # Set user&securityNames usmUserEntry.getNode(usmUserEntry.name + (2,) + tblIdx2).syntax = usmUserName.syntax usmUserEntry.getNode(usmUserEntry.name + (3,) + tblIdx2).syntax = usmUserSecurityName.syntax # Store a reference to original row usmUserEntry.getNode(usmUserEntry.name + (4,) + tblIdx2).syntax = usmUserCloneFrom.syntax.clone(tblIdx1) # Set protocols usmUserEntry.getNode(usmUserEntry.name + (5,) + tblIdx2).syntax = usmUserAuthProtocol.syntax usmUserEntry.getNode(usmUserEntry.name + (8,) + tblIdx2).syntax = usmUserPrivProtocol.syntax # Localize and set keys pysnmpUsmKeyEntry, = mibInstrumController.mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry' ) pysnmpUsmKeyAuthLocalized = pysnmpUsmKeyEntry.getNode( pysnmpUsmKeyEntry.name + (1,) + tblIdx2 ) if usmUserAuthProtocol.syntax in self.authServices: localizeKey = self.authServices[usmUserAuthProtocol.syntax].localizeKey localAuthKey = localizeKey(pysnmpUsmKeyAuth.syntax, securityEngineID) else: raise error.StatusInformation( errorIndication=errind.unsupportedAuthProtocol ) if localAuthKey is not None: pysnmpUsmKeyAuthLocalized.syntax = pysnmpUsmKeyAuthLocalized.syntax.clone(localAuthKey) pysnmpUsmKeyPrivLocalized = pysnmpUsmKeyEntry.getNode( pysnmpUsmKeyEntry.name + (2,) + tblIdx2 ) if usmUserPrivProtocol.syntax in self.privServices: localizeKey = self.privServices[usmUserPrivProtocol.syntax].localizeKey localPrivKey = localizeKey(usmUserAuthProtocol.syntax, pysnmpUsmKeyPriv.syntax, securityEngineID) else: raise error.StatusInformation(errorIndication=errind.unsupportedPrivProtocol) if localPrivKey is not None: pysnmpUsmKeyPrivLocalized.syntax = pysnmpUsmKeyPrivLocalized.syntax.clone(localPrivKey) return (usmUserName.syntax, usmUserSecurityName.syntax, usmUserAuthProtocol.syntax, pysnmpUsmKeyAuthLocalized.syntax, usmUserPrivProtocol.syntax, pysnmpUsmKeyPrivLocalized.syntax) def __generateRequestOrResponseMsg(self, snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineID, securityName, securityLevel, scopedPDU, securityStateReference): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder snmpEngineID = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax msg = globalData # 3.1.1 if securityStateReference is not None: # 3.1.1a cachedSecurityData = self._cache.pop(securityStateReference) usmUserName = cachedSecurityData['msgUserName'] if 'usmUserSecurityName' in cachedSecurityData: usmUserSecurityName = cachedSecurityData['usmUserSecurityName'] else: usmUserSecurityName = usmUserName if 'usmUserAuthProtocol' in cachedSecurityData: usmUserAuthProtocol = cachedSecurityData['usmUserAuthProtocol'] else: usmUserAuthProtocol = noauth.NoAuth.serviceID if 'usmUserAuthKeyLocalized' in cachedSecurityData: usmUserAuthKeyLocalized = cachedSecurityData['usmUserAuthKeyLocalized'] else: usmUserAuthKeyLocalized = None if 'usmUserPrivProtocol' in cachedSecurityData: usmUserPrivProtocol = cachedSecurityData['usmUserPrivProtocol'] else: usmUserPrivProtocol = nopriv.NoPriv.serviceID if 'usmUserPrivKeyLocalized' in cachedSecurityData: usmUserPrivKeyLocalized = cachedSecurityData['usmUserPrivKeyLocalized'] else: usmUserPrivKeyLocalized = None securityEngineID = snmpEngineID debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: using cached USM user entry ' 'usmUserName "%s" ' 'usmUserSecurityName "%s" ' 'usmUserAuthProtocol "%s" ' 'usmUserAuthKeyLocalized "%s" ' 'usmUserPrivProtocol "%s" ' 'usmUserPrivKeyLocalized "%s" for ' 'securityEngineID "%s" and securityName "%s" found by ' 'securityStateReference "%s" ' % ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized and usmUserAuthKeyLocalized.prettyPrint(), usmUserPrivProtocol, usmUserPrivKeyLocalized and usmUserPrivKeyLocalized.prettyPrint(), securityEngineID.prettyPrint(), securityName, securityStateReference)) elif securityEngineID: # 3.1.1b try: try: (usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized) = self.__getUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, securityEngineID, self.__sec2usr(snmpEngine, securityName, securityEngineID) ) except NoSuchInstanceError: (usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized) = self.__getUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, self.wildcardSecurityEngineId, self.__sec2usr(snmpEngine, securityName, self.wildcardSecurityEngineId) ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: found USM user entry ' 'usmUserName "%s" ' 'usmUserSecurityName "%s" ' 'usmUserAuthProtocol "%s" ' 'usmUserAuthKeyLocalized "%s" ' 'usmUserPrivProtocol "%s" ' 'usmUserPrivKeyLocalized "%s" by ' 'securityEngineID "%s" and securityName "%s"' % ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized and usmUserAuthKeyLocalized.prettyPrint(), usmUserPrivProtocol, usmUserPrivKeyLocalized and usmUserPrivKeyLocalized.prettyPrint(), securityEngineID.prettyPrint(), securityName)) except NoSuchInstanceError: pysnmpUsmDiscovery, = mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery') reportUnknownName = not pysnmpUsmDiscovery.syntax if not reportUnknownName: try: (usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized) = self.__cloneUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, securityEngineID, self.__sec2usr(snmpEngine, securityName) ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: cloned USM user entry ' 'usmUserName "%s" ' 'usmUserSecurityName "%s" ' 'usmUserAuthProtocol "%s" ' 'usmUserAuthKeyLocalized "%s" ' 'usmUserPrivProtocol "%s" ' 'usmUserPrivKeyLocalized "%s" for ' 'securityEngineID "%s" and securityName "%s"' % ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized and usmUserAuthKeyLocalized.prettyPrint(), usmUserPrivProtocol, usmUserPrivKeyLocalized and usmUserPrivKeyLocalized.prettyPrint(), securityEngineID.prettyPrint(), securityName)) except NoSuchInstanceError: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: failed to clone ' 'USM user for securityEngineID "%s" securityName ' '"%s"' % (securityEngineID, securityName)) reportUnknownName = True if reportUnknownName: raise error.StatusInformation( errorIndication=errind.unknownSecurityName ) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: %s' % (sys.exc_info()[1],)) snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax += 1 raise error.StatusInformation( errorIndication=errind.invalidMsg ) else: # 4. (start SNMP engine ID discovery) securityEngineID = securityName = null securityLevel = 1 scopedPDU.setComponentByPosition( 0, null, verifyConstraints=False, matchTags=False, matchConstraints=False) headerData = msg.getComponentByPosition(1) # Clear possible auth&priv flags headerData.setComponentByPosition( 2, univ.OctetString(hexValue='04'), verifyConstraints=False, matchTags=False, matchConstraints=False ) emptyPdu = scopedPDU.getComponentByPosition(2).getComponent() # we edit the rest of the structures in-place because they # are ours for as long as this stack lasts, however PDU # is more persistent and should not be touched emptyPdu = emptyPdu.clone() pMod.apiPDU.setDefaults(emptyPdu) scopedPDU.getComponentByPosition(2).setComponentByType( emptyPdu.tagSet, emptyPdu, verifyConstraints=False, matchTags=False, matchConstraints=False) usmUserName = usmUserSecurityName = null usmUserAuthProtocol = noauth.NoAuth.serviceID usmUserPrivProtocol = nopriv.NoPriv.serviceID usmUserAuthKeyLocalized = usmUserPrivKeyLocalized = None debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: using blank USM info for peer ' 'SNMP engine ID discovery ' 'usmUserName "%s" ' 'usmUserSecurityName "%s" ' 'usmUserAuthProtocol "%s" ' 'usmUserAuthKeyLocalized "%s" ' 'usmUserPrivProtocol "%s" ' 'usmUserPrivKeyLocalized "%s" for ' 'securityEngineID "%s" and securityName "%s"' % ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized, securityEngineID and securityEngineID.prettyPrint(), securityName)) # 3.1.2 if securityLevel == 3: if (usmUserAuthProtocol == noauth.NoAuth.serviceID or usmUserPrivProtocol == nopriv.NoPriv.serviceID): raise error.StatusInformation( errorIndication=errind.unsupportedSecurityLevel ) # 3.1.3 if securityLevel == 3 or securityLevel == 2: if usmUserAuthProtocol == noauth.NoAuth.serviceID: raise error.StatusInformation( errorIndication=errind.unsupportedSecurityLevel ) securityParameters = self.__securityParametersSpec scopedPDUData = msg.setComponentByPosition(3).getComponentByPosition(3) scopedPDUData.setComponentByPosition( 0, scopedPDU, verifyConstraints=False, matchTags=False, matchConstraints=False ) # 3.1.6a if securityStateReference is None and securityLevel in (2, 3): 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) = 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()) try: dataToEncrypt = encoder.encode(scopedPDU) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: scopedPDU serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( errorIndication=errind.serializationError ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: scopedPDU encoded into %s' % debug.hexdump(dataToEncrypt)) # noinspection PyUnboundLocalVariable (encryptedData, privParameters) = privHandler.encryptData( usmUserPrivKeyLocalized, (snmpEngineBoots, snmpEngineTime, None), dataToEncrypt ) securityParameters.setComponentByPosition( 5, privParameters, verifyConstraints=False, matchTags=False, matchConstraints=False ) scopedPDUData.setComponentByPosition( 1, encryptedData, verifyConstraints=False, matchTags=False, matchConstraints=False ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: scopedPDU ciphered into %s' % debug.hexdump(encryptedData)) # 3.1.4b elif securityLevel == 1 or securityLevel == 2: securityParameters.setComponentByPosition(5, '') debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % scopedPDUData.prettyPrint()) # 3.1.5 securityParameters.setComponentByPosition( 0, securityEngineID, verifyConstraints=False, matchTags=False, matchConstraints=False ) securityParameters.setComponentByPosition( 1, snmpEngineBoots, verifyConstraints=False, matchTags=False, matchConstraints=False ) securityParameters.setComponentByPosition( 2, snmpEngineTime, verifyConstraints=False, matchTags=False, matchConstraints=False ) # 3.1.7 securityParameters.setComponentByPosition( 3, usmUserName, verifyConstraints=False, matchTags=False, matchConstraints=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' * authHandler.digestLength ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: securityParameters serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( errorIndication=errind.serializationError ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: auth outgoing msg: %s' % msg.prettyPrint()) try: wholeMsg = encoder.encode(msg) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: msg serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( errorIndication=errind.serializationError ) # noinspection PyUnboundLocalVariable authenticatedWholeMsg = authHandler.authenticateOutgoingMsg( usmUserAuthKeyLocalized, wholeMsg ) # 3.1.8b else: securityParameters.setComponentByPosition( 4, '', verifyConstraints=False, matchTags=False, matchConstraints=False ) debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False, matchTags=False, matchConstraints=False) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: secutiryParameters serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( errorIndication=errind.serializationError ) try: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: plain outgoing msg: %s' % msg.prettyPrint()) authenticatedWholeMsg = encoder.encode(msg) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger( '__generateRequestOrResponseMsg: msg serialization error: %s' % sys.exc_info()[1]) raise error.StatusInformation( errorIndication=errind.serializationError ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s outgoing msg: %s' % ( securityLevel > 1 and "authenticated" or "plain", debug.hexdump(authenticatedWholeMsg))) # 3.1.9 return msg.getComponentByPosition(2), authenticatedWholeMsg def generateRequestMsg(self, snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineID, securityName, securityLevel, scopedPDU): return self.__generateRequestOrResponseMsg(snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineID, securityName, securityLevel, scopedPDU, None) def generateResponseMsg(self, snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineID, securityName, securityLevel, scopedPDU, securityStateReference): return 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): mibBuilder = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder # 3.2.9 -- moved up here to be able to report # maxSizeResponseScopedPDU on error # (48 - maximum SNMPv3 header length) maxSizeResponseScopedPDU = int(maxMessageSize) - len(securityParameters) - 48 debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: securityParameters %s' % debug.hexdump(securityParameters)) # 3.2.1 securityParameters, rest = decoder.decode( securityParameters, asn1Spec=self.__securityParametersSpec ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),)) if eoo.endOfOctets.isSameTypeWith(securityParameters): raise error.StatusInformation(errorIndication=errind.parseError) # 3.2.2 msgAuthoritativeEngineId = securityParameters.getComponentByPosition(0) securityStateReference = self._cache.push( msgUserName=securityParameters.getComponentByPosition(3) ) debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: cache write securityStateReference %s by msgUserName %s' % ( securityStateReference, securityParameters.getComponentByPosition(3))) scopedPduData = msg.getComponentByPosition(3) # Used for error reporting contextEngineId = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax contextName = null snmpEngineID = mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax # 3.2.3 if (msgAuthoritativeEngineId != snmpEngineID and msgAuthoritativeEngineId not in self.__timeline): if (msgAuthoritativeEngineId and 4 < len(msgAuthoritativeEngineId) < 33): # 3.2.3a - cloned user when request was sent debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: non-synchronized securityEngineID %r' % (msgAuthoritativeEngineId,)) else: # 3.2.3b debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: peer requested snmpEngineID discovery') usmStatsUnknownEngineIDs, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs') usmStatsUnknownEngineIDs.syntax += 1 debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: null or malformed msgAuthoritativeEngineId') pysnmpUsmDiscoverable, = mibBuilder.importSymbols( '__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') if pysnmpUsmDiscoverable.syntax: debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: starting snmpEngineID discovery procedure') # 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 ) 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: (usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized) = self.__getUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, msgAuthoritativeEngineId, msgUserName ) debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: read user info from LCD') except NoSuchInstanceError: try: (usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized) = self.__getUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, self.wildcardSecurityEngineId, msgUserName ) debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: read wildcard user info from LCD') except NoSuchInstanceError: debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: unknown securityEngineID %r msgUserName %r' % ( msgAuthoritativeEngineId, msgUserName)) usmStatsUnknownUserNames, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') usmStatsUnknownUserNames.syntax += 1 raise error.StatusInformation( errorIndication=errind.unknownSecurityName, oid=usmStatsUnknownUserNames.name, val=usmStatsUnknownUserNames.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, msgUserName=msgUserName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax += 1 raise error.StatusInformation(errorIndication=errind.invalidMsg) else: # empty username used for engineID discovery usmUserName = usmUserSecurityName = null usmUserAuthProtocol = noauth.NoAuth.serviceID usmUserPrivProtocol = nopriv.NoPriv.serviceID usmUserAuthKeyLocalized = usmUserPrivKeyLocalized = None debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: now have usmUserName %r usmUserSecurityName %r usmUserAuthProtocol %r usmUserPrivProtocol %r for msgUserName %r' % ( usmUserName, 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), usmUserSecurityName=usmUserSecurityName, usmUserAuthProtocol=usmUserAuthProtocol, usmUserAuthKeyLocalized=usmUserAuthKeyLocalized, usmUserPrivProtocol=usmUserPrivProtocol, usmUserPrivKeyLocalized=usmUserPrivKeyLocalized ) msgAuthoritativeEngineBoots = securityParameters.getComponentByPosition(1) msgAuthoritativeEngineTime = securityParameters.getComponentByPosition(2) snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc3414.processIncomingMsg', dict(securityEngineId=msgAuthoritativeEngineId, snmpEngineBoots=msgAuthoritativeEngineBoots, snmpEngineTime=msgAuthoritativeEngineTime, userName=usmUserName, securityName=usmUserSecurityName, authProtocol=usmUserAuthProtocol, authKey=usmUserAuthKeyLocalized, privProtocol=usmUserPrivProtocol, privKey=usmUserPrivKeyLocalized) ) snmpEngine.observer.clearExecutionContext( snmpEngine, 'rfc3414.processIncomingMsg' ) # 3.2.5 if msgAuthoritativeEngineId == snmpEngineID: # Authoritative SNMP engine: make sure securityLevel is sufficient badSecIndication = None if securityLevel == 3: if usmUserAuthProtocol == noauth.NoAuth.serviceID: badSecIndication = 'authPriv wanted while auth not expected' if usmUserPrivProtocol == nopriv.NoPriv.serviceID: badSecIndication = 'authPriv wanted while priv not expected' elif securityLevel == 2: if usmUserAuthProtocol == noauth.NoAuth.serviceID: badSecIndication = 'authNoPriv wanted while auth not expected' if usmUserPrivProtocol != nopriv.NoPriv.serviceID: # 4 (discovery phase always uses authenticated messages) if msgAuthoritativeEngineBoots or msgAuthoritativeEngineTime: badSecIndication = 'authNoPriv wanted while priv expected' elif securityLevel == 1: if usmUserAuthProtocol != noauth.NoAuth.serviceID: badSecIndication = 'noAuthNoPriv wanted while auth expected' if usmUserPrivProtocol != nopriv.NoPriv.serviceID: badSecIndication = 'noAuthNoPriv wanted while priv expected' if badSecIndication: usmStatsUnsupportedSecLevels, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsUnsupportedSecLevels') usmStatsUnsupportedSecLevels.syntax += 1 debug.logger & debug.flagSM and debug.logger( 'processIncomingMsg: reporting inappropriate security level for user %s: %s' % ( msgUserName, badSecIndication)) raise error.StatusInformation( errorIndication=errind.unsupportedSecurityLevel, oid=usmStatsUnsupportedSecLevels.name, val=usmStatsUnsupportedSecLevels.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, msgUserName=msgUserName, 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: authHandler.authenticateIncomingMsg( usmUserAuthKeyLocalized, securityParameters.getComponentByPosition(4), wholeMsg ) except error.StatusInformation: usmStatsWrongDigests, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsWrongDigests') usmStatsWrongDigests.syntax += 1 raise error.StatusInformation( errorIndication=errind.authenticationFailure, oid=usmStatsWrongDigests.name, val=usmStatsWrongDigests.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, msgUserName=msgUserName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authenticated') # synchronize time with authed peer self.__timeline[msgAuthoritativeEngineId] = ( securityParameters.getComponentByPosition(1), securityParameters.getComponentByPosition(2), securityParameters.getComponentByPosition(2), int(time.time()) ) timerResolution = snmpEngine.transportDispatcher is None and 1.0 or snmpEngine.transportDispatcher.getTimerResolution() expireAt = int(self.__expirationTimer + 300 / timerResolution) 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) = 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') # 3.2.7a if msgAuthoritativeEngineId == snmpEngineID: if (snmpEngineBoots == 2147483647 or snmpEngineBoots != msgAuthoritativeEngineBoots or abs(idleTime + int(snmpEngineTime) - int(msgAuthoritativeEngineTime)) > 150): usmStatsNotInTimeWindows, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsNotInTimeWindows') usmStatsNotInTimeWindows.syntax += 1 raise error.StatusInformation( errorIndication=errind.notInTimeWindow, oid=usmStatsNotInTimeWindows.name, val=usmStatsNotInTimeWindows.syntax, securityStateReference=securityStateReference, securityLevel=2, contextEngineId=contextEngineId, contextName=contextName, msgUserName=msgUserName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) # 3.2.7b else: # 3.2.7b.1 # noinspection PyUnboundLocalVariable if (msgAuthoritativeEngineBoots > snmpEngineBoots or msgAuthoritativeEngineBoots == snmpEngineBoots and msgAuthoritativeEngineTime > latestReceivedEngineTime): self.__timeline[msgAuthoritativeEngineId] = ( msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineTime, int(time.time()) ) timerResolution = snmpEngine.transportDispatcher is None and 1.0 or snmpEngine.transportDispatcher.getTimerResolution() expireAt = int(self.__expirationTimer + 300 / timerResolution) 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, msgUserName=msgUserName ) # 3.2.8a if securityLevel == 3: if usmUserPrivProtocol in self.privServices: privHandler = self.privServices[usmUserPrivProtocol] else: raise error.StatusInformation( errorIndication=errind.decryptionError, msgUserName=msgUserName ) encryptedPDU = scopedPduData.getComponentByPosition(1) if encryptedPDU is None: # no ciphertext raise error.StatusInformation( errorIndication=errind.decryptionError, msgUserName=msgUserName ) 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 %s' % debug.hexdump(decryptedData)) except error.StatusInformation: usmStatsDecryptionErrors, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsDecryptionErrors') usmStatsDecryptionErrors.syntax += 1 raise error.StatusInformation( errorIndication=errind.decryptionError, oid=usmStatsDecryptionErrors.name, val=usmStatsDecryptionErrors.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, msgUserName=msgUserName, 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, msgUserName=msgUserName ) if eoo.endOfOctets.isSameTypeWith(scopedPDU): raise error.StatusInformation( errorIndication=errind.decryptionError, msgUserName=msgUserName ) else: # 3.2.8b scopedPDU = scopedPduData.getComponentByPosition(0) if scopedPDU is None: # no plaintext raise error.StatusInformation( errorIndication=errind.decryptionError, msgUserName=msgUserName ) 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, = mibBuilder.importSymbols( '__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') 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, msgUserName=msgUserName, 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('__expireTimelineInfo: expiring %r' % (engineIdKey,)) del self.__timelineExpQueue[self.__expirationTimer] self.__expirationTimer += 1 def receiveTimerTick(self, snmpEngine, timeNow): self.__expireTimelineInfo() pysnmp-4.4.12/pysnmp/proto/secmod/rfc3826/000077500000000000000000000000001354244100700201705ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc3826/__init__.py000066400000000000000000000000731354244100700223010ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/rfc3826/priv/000077500000000000000000000000001354244100700211505ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc3826/priv/__init__.py000066400000000000000000000000731354244100700232610ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/rfc3826/priv/aes.py000066400000000000000000000117161354244100700223000ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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.rfc7860.auth import hmacsha2 from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import errind, error try: from Cryptodome.Cipher import AES except ImportError: AES = None try: from hashlib import md5, sha1 except ImportError: import md5 import sha md5 = md5.new sha1 = sha.new 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 += 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: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localkey.hashPassphrase(privKey, hashAlgo) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: hashAlgo = md5 elif authProtocol == hmacsha.HmacSha.serviceID: hashAlgo = sha1 elif authProtocol in hmacsha2.HmacSha2.hashAlgorithms: hashAlgo = hmacsha2.HmacSha2.hashAlgorithms[authProtocol] else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) localPrivKey = localkey.localizeKey(privKey, snmpEngineID, hashAlgo) return localPrivKey[:self.keySize] # 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()) pysnmp-4.4.12/pysnmp/proto/secmod/rfc7860/000077500000000000000000000000001354244100700201725ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc7860/__init__.py000066400000000000000000000000731354244100700223030ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/rfc7860/auth/000077500000000000000000000000001354244100700211335ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/proto/secmod/rfc7860/auth/__init__.py000066400000000000000000000000731354244100700232440ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py000066400000000000000000000077171354244100700232070ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2018, Olivier Verriest # License: http://snmplabs.com/pysnmp/license.html # import sys import hmac try: from hashlib import sha224, sha256, sha384, sha512 except ImportError: class NotAvailable(object): def __call__(self, *args, **kwargs): raise errind.authenticationError sha224 = sha256 = sha384 = sha512 = NotAvailable() 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 # 7.2.4 class HmacSha2(base.AbstractAuthenticationService): sha224ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 4) # usmHMAC128SHA224AuthProtocol sha256ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 5) # usmHMAC192SHA256AuthProtocol sha384ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 6) # usmHMAC256SHA384AuthProtocol sha512ServiceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 7) # usmHMAC384SHA512AuthProtocol keyLengths = { sha224ServiceID: 28, sha256ServiceID: 32, sha384ServiceID: 48, sha512ServiceID: 64 } digestLengths = { sha224ServiceID: 16, sha256ServiceID: 24, sha384ServiceID: 32, sha512ServiceID: 48 } hashAlgorithms = { sha224ServiceID: sha224, sha256ServiceID: sha256, sha384ServiceID: sha384, sha512ServiceID: sha512 } __ipad = [0x36] * 64 __opad = [0x5C] * 64 def __init__(self, oid): if oid not in self.hashAlgorithms: raise error.ProtocolError('No SHA-2 authentication algorithm %s available' % (oid,)) self.__hashAlgo = self.hashAlgorithms[oid] self.__digestLength = self.digestLengths[oid] self.__placeHolder = univ.OctetString((0,) * self.__digestLength).asOctets() def hashPassphrase(self, authKey): return localkey.hashPassphrase(authKey, self.__hashAlgo) def localizeKey(self, authKey, snmpEngineID): return localkey.localizeKey(authKey, snmpEngineID, self.__hashAlgo) @property def digestLength(self): return self.__digestLength # 7.3.1 def authenticateOutgoingMsg(self, authKey, wholeMsg): # 7.3.1.1 location = wholeMsg.find(self.__placeHolder) if location == -1: raise error.ProtocolError('Can\'t locate digest placeholder') wholeHead = wholeMsg[:location] wholeTail = wholeMsg[location + self.__digestLength:] # 7.3.1.2, 7.3.1.3 try: mac = hmac.new(authKey.asOctets(), wholeMsg, self.__hashAlgo) except errind.ErrorIndication: raise error.StatusInformation(errorIndication=sys.exc_info()[1]) # 7.3.1.4 mac = mac.digest()[:self.__digestLength] # 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) != self.__digestLength: raise error.StatusInformation( errorIndication=errind.authenticationError ) # 7.3.2.3 location = wholeMsg.find(authParameters.asOctets()) if location == -1: raise error.ProtocolError('Can\'t locate digest in wholeMsg') wholeHead = wholeMsg[:location] wholeTail = wholeMsg[location + self.__digestLength:] authenticatedWholeMsg = wholeHead + self.__placeHolder + wholeTail # 7.3.2.4 try: mac = hmac.new(authKey.asOctets(), authenticatedWholeMsg, self.__hashAlgo) except errind.ErrorIndication: raise error.StatusInformation(errorIndication=sys.exc_info()[1]) # 7.3.2.5 mac = mac.digest()[:self.__digestLength] # 7.3.2.6 if mac != authParameters: raise error.StatusInformation( errorIndication=errind.authenticationFailure ) return authenticatedWholeMsg pysnmp-4.4.12/pysnmp/smi/000077500000000000000000000000001354244100700152465ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/smi/__init__.py000066400000000000000000000000731354244100700173570ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/smi/builder.py000066400000000000000000000405621354244100700172550ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import os import sys import struct import marshal import time import traceback try: import importlib try: PY_MAGIC_NUMBER = importlib.util.MAGIC_NUMBER SOURCE_SUFFIXES = importlib.machinery.SOURCE_SUFFIXES BYTECODE_SUFFIXES = importlib.machinery.BYTECODE_SUFFIXES except Exception: raise ImportError() except ImportError: import imp PY_MAGIC_NUMBER = imp.get_magic() SOURCE_SUFFIXES = [s[0] for s in imp.get_suffixes() if s[2] == imp.PY_SOURCE] BYTECODE_SUFFIXES = [s[0] for s in imp.get_suffixes() if s[2] == imp.PY_COMPILED] PY_SUFFIXES = SOURCE_SUFFIXES + BYTECODE_SUFFIXES try: from errno import ENOENT except ImportError: ENOENT = -1 from pysnmp import version as pysnmp_version from pysnmp.smi import error from pysnmp import debug if sys.version_info[0] <= 2: import types classTypes = (types.ClassType, type) else: classTypes = (type,) class __AbstractMibSource(object): def __init__(self, srcName): self._srcName = srcName self.__inited = None 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 = set() for f in files: if f.startswith('__init__.'): continue u.update(f[:-len(sfx)] for sfx in PY_SUFFIXES if f.endswith(sfx)) return tuple(u) # 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): pycTime = pyTime = -1 for pycSfx in BYTECODE_SUFFIXES: try: pycData, pycPath = self._getData(f + pycSfx, 'rb') except IOError: why = sys.exc_info()[1] if ENOENT == -1 or why.errno == ENOENT: debug.logger & debug.flagBld and debug.logger( 'file %s access error: %s' % (f + pycSfx, why) ) else: raise error.MibLoadError('MIB file %s access error: %s' % (f + pycSfx, why)) else: if PY_MAGIC_NUMBER == pycData[:4]: pycData = pycData[4:] pycTime = struct.unpack('= pyTime: return marshal.loads(pycData), pycSfx if pyTime != -1: modData, pyPath = self._getData(f + pySfx, 'r') return compile(modData, pyPath, 'exec'), pyPath raise IOError(ENOENT, 'No suitable module found', f) # Interfaces for subclasses def _init(self): raise NotImplementedError() def _listdir(self): raise NotImplementedError() def _getTimestamp(self, f): raise NotImplementedError() def _getData(self, f, mode): NotImplementedError() class ZipMibSource(__AbstractMibSource): def _init(self): try: p = __import__(self._srcName, globals(), locals(), ['__init__']) if hasattr(p, '__loader__') and hasattr(p.__loader__, '_files'): self.__loader = p.__loader__ self._srcName = self._srcName.replace('.', os.sep) return self elif hasattr(p, '__file__'): # Dir relative to PYTHONPATH return DirMibSource(os.path.split(p.__file__)[0]).init() else: raise error.MibLoadError('%s access error' % (p,)) except ImportError: # Dir relative to CWD return DirMibSource(self._srcName).init() @staticmethod def _parseDosTime(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 = [] # noinspection PyProtectedMember 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, f): p = os.path.join(self._srcName, f) # noinspection PyProtectedMember if p in self.__loader._files: # noinspection PyProtectedMember return self._parseDosTime( self.__loader._files[p][6], self.__loader._files[p][5] ) else: raise IOError(ENOENT, 'No such file in ZIP archive', p) def _getData(self, f, mode=None): p = os.path.join(self._srcName, f) try: return self.__loader.get_data(p), p except Exception: # ZIP code seems to return all kinds of errors why = sys.exc_info() raise IOError(ENOENT, 'File or ZIP archive %s access error: %s' % (p, why[1])) 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: why = sys.exc_info() debug.logger & debug.flagBld and debug.logger( 'listdir() failed for %s: %s' % (self._srcName, why[1])) return () def _getTimestamp(self, f): p = os.path.join(self._srcName, f) try: return os.stat(p)[8] except OSError: raise IOError(ENOENT, 'No such file: %s' % sys.exc_info()[1], p) def _getData(self, f, mode): p = os.path.join(self._srcName, '*') try: if f in os.listdir(self._srcName): # make FS case-sensitive p = os.path.join(self._srcName, f) fp = open(p, mode) data = fp.read() fp.close() return data, p except (IOError, OSError): why = sys.exc_info() msg = 'File or directory %s access error: %s' % (p, why[1]) else: msg = 'No such file or directory: %s' % p raise IOError(ENOENT, msg) class MibBuilder(object): defaultCoreMibs = os.pathsep.join( ('pysnmp.smi.mibs.instances', 'pysnmp.smi.mibs') ) defaultMiscMibs = 'pysnmp_mibs' moduleID = 'PYSNMP_MODULE_ID' loadTexts = False # MIB modules can use this to select the features they can use version = pysnmp_version def __init__(self): self.lastBuildId = self._autoName = 0 sources = [] for ev in 'PYSNMP_MIB_PKGS', 'PYSNMP_MIB_DIRS', 'PYSNMP_MIB_DIR': if ev in os.environ: for m in os.environ[ev].split(os.pathsep): sources.append(ZipMibSource(m)) if not sources and self.defaultMiscMibs: for m in self.defaultMiscMibs.split(os.pathsep): sources.append(ZipMibSource(m)) for m in self.defaultCoreMibs.split(os.pathsep): sources.insert(0, ZipMibSource(m)) self.mibSymbols = {} self.__mibSources = [] self.__modSeen = {} self.__modPathsSeen = set() self.__mibCompiler = None self.setMibSources(*sources) # MIB compiler management def getMibCompiler(self): return self.__mibCompiler def setMibCompiler(self, mibCompiler, destDir): self.addMibSources(DirMibSource(destDir)) self.__mibCompiler = mibCompiler return self # MIB modules management def addMibSources(self, *mibSources): self.__mibSources.extend([s.init() for s in mibSources]) debug.logger & debug.flagBld and debug.logger('addMibSources: new MIB sources %s' % (self.__mibSources,)) def setMibSources(self, *mibSources): self.__mibSources = [s.init() for s in mibSources] debug.logger & debug.flagBld and debug.logger('setMibSources: new MIB sources %s' % (self.__mibSources,)) 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.MibLoadError( 'MIB source is not a plain directory: %s' % (mibSource,) ) return paths def loadModule(self, modName, **userCtx): """Load and execute MIB modules as Python code""" for mibSource in self.__mibSources: debug.logger & debug.flagBld and debug.logger('loadModule: trying %s at %s' % (modName, mibSource)) try: codeObj, sfx = mibSource.read(modName) except IOError: debug.logger & debug.flagBld and debug.logger( 'loadModule: 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('loadModule: seen %s' % modPath) break else: self.__modPathsSeen.add(modPath) debug.logger & debug.flagBld and debug.logger('loadModule: evaluating %s' % modPath) g = {'mibBuilder': self, 'userCtx': userCtx} try: exec(codeObj, g) except Exception: self.__modPathsSeen.remove(modPath) raise error.MibLoadError( 'MIB module \'%s\' load error: %s' % (modPath, traceback.format_exception(*sys.exc_info())) ) self.__modSeen[modName] = modPath debug.logger & debug.flagBld and debug.logger('loadModule: loaded %s' % modPath) break if modName not in self.__modSeen: raise error.MibNotFoundError( 'MIB file \"%s\" not found in search path (%s)' % ( modName and modName + ".py[co]", ', '.join([str(x) for x in self.__mibSources])) ) return self def loadModules(self, *modNames, **userCtx): """Load (optionally, compiling) pysnmp MIB modules""" # 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) if not modNames: raise error.MibNotFoundError( 'No MIB module to load at %s' % (self,) ) for modName in modNames: try: self.loadModule(modName, **userCtx) except error.MibNotFoundError: if self.__mibCompiler: debug.logger & debug.flagBld and debug.logger('loadModules: calling MIB compiler for %s' % modName) status = self.__mibCompiler.compile(modName, genTexts=self.loadTexts) errs = '; '.join([hasattr(x, 'error') and str(x.error) or x for x in status.values() if x in ('failed', 'missing')]) if errs: raise error.MibNotFoundError('%s compilation error(s): %s' % (modName, errs)) # compilation succeeded, MIB might load now self.loadModule(modName, **userCtx) 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.MibNotFoundError( 'No module %s at %s' % (modName, self) ) self.unexportSymbols(modName) self.__modPathsSeen.remove(self.__modSeen[modName]) del self.__modSeen[modName] debug.logger & debug.flagBld and debug.logger('unloadModules: %s' % 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.MibNotFoundError( '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 += 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 += 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 += 1 pysnmp-4.4.12/pysnmp/smi/compiler.py000066400000000000000000000044231354244100700174350ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import os import sys defaultSources = ['file:///usr/share/snmp/mibs', 'file:///usr/share/mibs'] if sys.platform[:3] == 'win': defaultDest = os.path.join(os.path.expanduser("~"), 'PySNMP Configuration', 'mibs') else: defaultDest = os.path.join(os.path.expanduser("~"), '.pysnmp', 'mibs') defaultBorrowers = [] try: from pysmi.reader.url import getReadersFromUrls from pysmi.searcher.pypackage import PyPackageSearcher from pysmi.searcher.stub import StubSearcher from pysmi.borrower.pyfile import PyFileBorrower from pysmi.writer.pyfile import PyFileWriter from pysmi.parser.smi import parserFactory from pysmi.parser.dialect import smiV1Relaxed from pysmi.codegen.pysnmp import PySnmpCodeGen, baseMibs from pysmi.compiler import MibCompiler except ImportError: from pysnmp.smi import error def addMibCompilerDecorator(errorMsg): def addMibCompiler(mibBuilder, **kwargs): if not kwargs.get('ifAvailable'): raise error.SmiError('MIB compiler not available: %s' % errorMsg) return addMibCompiler addMibCompiler = addMibCompilerDecorator(sys.exc_info()[1]) else: def addMibCompiler(mibBuilder, **kwargs): if kwargs.get('ifNotAdded') and mibBuilder.getMibCompiler(): return compiler = MibCompiler(parserFactory(**smiV1Relaxed)(), PySnmpCodeGen(), PyFileWriter(kwargs.get('destination') or defaultDest)) compiler.addSources(*getReadersFromUrls(*kwargs.get('sources') or defaultSources)) compiler.addSearchers(StubSearcher(*baseMibs)) compiler.addSearchers(*[PyPackageSearcher(x.fullPath()) for x in mibBuilder.getMibSources()]) compiler.addBorrowers(*[PyFileBorrower(x, genTexts=mibBuilder.loadTexts) for x in getReadersFromUrls(*kwargs.get('borrowers') or defaultBorrowers, **dict(lowcaseMatching=False))]) mibBuilder.setMibCompiler( compiler, kwargs.get('destination') or defaultDest ) pysnmp-4.4.12/pysnmp/smi/error.py000066400000000000000000000044621354244100700167570ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.error import PyAsn1Error from pysnmp.error import PySnmpError class SmiError(PySnmpError, PyAsn1Error): pass class MibLoadError(SmiError): pass class MibNotFoundError(MibLoadError): 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 values class TooBigError(MibOperationError): pass class NoSuchNameError(MibOperationError): pass class BadValueError(MibOperationError): pass class ReadOnlyError(MibOperationError): pass class GenError(MibOperationError): pass class NoAccessError(MibOperationError): pass class WrongTypeError(MibOperationError): pass class WrongLengthError(MibOperationError): pass class WrongEncodingError(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 PDU exceptions or error-status values class NoSuchObjectError(NoSuchNameError): pass class NoSuchInstanceError(NoSuchNameError): pass class EndOfMibViewError(NoSuchNameError): pass # SNMP table management exceptions class TableRowManagement(MibOperationError): pass class RowCreationWanted(TableRowManagement): pass class RowDestructionWanted(TableRowManagement): pass pysnmp-4.4.12/pysnmp/smi/exval.py000066400000000000000000000004721354244100700167420ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pysnmp.proto import rfc1905 noSuchObject = rfc1905.noSuchObject noSuchInstance = rfc1905.noSuchInstance endOfMibView = endOfMib = rfc1905.endOfMibView pysnmp-4.4.12/pysnmp/smi/indices.py000066400000000000000000000061361354244100700172440ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from bisect import bisect class OrderedDict(dict): """Ordered dictionary used for indices""" def __init__(self, *args, **kwargs): self.__keys = [] self.__dirty = True super(OrderedDict, self).__init__() if args: self.update(*args) if kwargs: self.update(**kwargs) def __setitem__(self, key, value): super(OrderedDict, self).__setitem__(key, value) if key not in self.__keys: self.__keys.append(key) self.__dirty = True def __delitem__(self, key): super(OrderedDict, self).__delitem__(key) if key in self.__keys: self.__keys.remove(key) self.__dirty = True def clear(self): super(OrderedDict, self).clear() self.__keys = [] self.__dirty = True 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, *args, **kwargs): if args: iterable = args[0] if hasattr(iterable, 'keys'): for k in iterable: self[k] = iterable[k] else: for k, v in iterable: self[k] = v if kwargs: for k in kwargs: self[k] = kwargs[k] def sortingFun(self, keys): keys.sort() def __order(self): self.sortingFun(self.__keys) self.__keysLens = sorted(set(len(k) for k in self.__keys), reverse=True) self.__dirty = False def nextKey(self, key): if self.__dirty: self.__order() keys = self.__keys if key in keys: 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): """OID-ordered dictionary used for indices""" def __init__(self, *args, **kwargs): self.__keysCache = {} OrderedDict.__init__(self, *args, **kwargs) def __setitem__(self, key, value): OrderedDict.__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] def __delitem__(self, key): OrderedDict.__delitem__(self, key) if key in self.__keysCache: del self.__keysCache[key] def sortingFun(self, keys): keys.sort(key=lambda k, d=self.__keysCache: d[k]) pysnmp-4.4.12/pysnmp/smi/instrum.py000066400000000000000000000222341354244100700173240ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys import traceback from pysnmp.smi import error from pysnmp import debug __all__ = ['AbstractMibInstrumController', 'MibInstrumController'] class AbstractMibInstrumController(object): def readVars(self, varBinds, acInfo=(None, None)): raise error.NoSuchInstanceError(idx=0) def readNextVars(self, varBinds, acInfo=(None, None)): raise error.EndOfMibViewError(idx=0) def writeVars(self, varBinds, acInfo=(None, None)): raise error.NoSuchObjectError(idx=0) class MibInstrumController(AbstractMibInstrumController): 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 self.lastBuildSyms = {} def getMibBuilder(self): return self.mibBuilder # 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) = self.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance', 'MibScalar', 'MibTableColumn', 'MibTableRow', 'MibTable' ) 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 %r at %r' % (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 %r at %r' % (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, inputVarBinds, acInfo): self.__indexMib() debug.logger & debug.flagIns and debug.logger('flipFlopFsm: input var-binds %r' % (inputVarBinds,)) mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') outputVarBinds = [] state, status = 'start', 'ok' origExc = None while True: 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 inputVarBinds: 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: exc_t, exc_v, exc_tb = sys.exc_info() debug.logger & debug.flagIns and debug.logger( 'flipFlopFsm: fun %s exception %s for %s=%r with traceback: %s' % ( f, exc_t, name, val, traceback.format_exception(exc_t, exc_v, exc_tb))) if origExc is None: # Take the first exception origExc, origTraceback = exc_v, exc_tb 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: outputVarBinds.append((rval[0], rval[1])) 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 outputVarBinds def readVars(self, varBinds, acInfo=(None, None)): return self.flipFlopFsm(self.fsmReadVar, varBinds, acInfo) def readNextVars(self, varBinds, acInfo=(None, None)): return self.flipFlopFsm(self.fsmReadNextVar, varBinds, acInfo) def writeVars(self, varBinds, acInfo=(None, None)): return self.flipFlopFsm(self.fsmWriteVar, varBinds, acInfo) pysnmp-4.4.12/pysnmp/smi/mibs/000077500000000000000000000000001354244100700162005ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/smi/mibs/ASN1-ENUMERATION.py000066400000000000000000000004301354244100700210350ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import namedval mibBuilder.exportSymbols( 'ASN1-ENUMERATION', NamedValues=namedval.NamedValues ) pysnmp-4.4.12/pysnmp/smi/mibs/ASN1-REFINEMENT.py000066400000000000000000000010231354244100700207020ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from pyasn1.type import constraint mibBuilder.exportSymbols( 'ASN1-REFINEMENT', ConstraintsUnion=constraint.ConstraintsUnion, ConstraintsIntersection=constraint.ConstraintsIntersection, SingleValueConstraint=constraint.SingleValueConstraint, ValueRangeConstraint=constraint.ValueRangeConstraint, ValueSizeConstraint=constraint.ValueSizeConstraint ) pysnmp-4.4.12/pysnmp/smi/mibs/ASN1.py000066400000000000000000000007661354244100700172650ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/INET-ADDRESS-MIB.py000066400000000000000000000423221354244100700210040ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module INET-ADDRESS-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/INET-ADDRESS-MIB # Produced by pysmi-0.1.2 at Sat Apr 15 23:36:33 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # from pysnmp.smi import error ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Gauge32, iso, Bits, Integer32, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Counter32, mib_2, Counter64, IpAddress, Unsigned32, ObjectIdentity, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "iso", "Bits", "Integer32", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Counter32", "mib-2", "Counter64", "IpAddress", "Unsigned32", "ObjectIdentity", "ModuleIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") inetAddressMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 76)) if mibBuilder.loadTexts: inetAddressMIB.setRevisions(('2005-02-04 00:00', '2002-05-09 00:00', '2000-06-08 00:00',)) if mibBuilder.loadTexts: inetAddressMIB.setLastUpdated('200502040000Z') if mibBuilder.loadTexts: inetAddressMIB.setOrganization('IETF Operations and Management Area') if mibBuilder.loadTexts: inetAddressMIB.setContactInfo('Juergen Schoenwaelder (Editor) International University Bremen P.O. Box 750 561 28725 Bremen, Germany Phone: +49 421 200-3587 EMail: j.schoenwaelder@iu-bremen.de Send comments to .') if mibBuilder.loadTexts: inetAddressMIB.setDescription('This MIB module defines textual conventions for representing Internet addresses. An Internet address can be an IPv4 address, an IPv6 address, or a DNS domain name. This module also defines textual conventions for Internet port numbers, autonomous system numbers, and the length of an Internet address prefix. Copyright (C) The Internet Society (2005). This version of this MIB module is part of RFC 4001, see the RFC itself for full legal notices.') class InetAddressType(TextualConvention, Integer32): description = 'A value that represents a type of Internet address. unknown(0) An unknown address type. This value MUST be used if the value of the corresponding InetAddress object is a zero-length string. It may also be used to indicate an IP address that is not in one of the formats defined below. ipv4(1) An IPv4 address as defined by the InetAddressIPv4 textual convention. ipv6(2) An IPv6 address as defined by the InetAddressIPv6 textual convention. ipv4z(3) A non-global IPv4 address including a zone index as defined by the InetAddressIPv4z textual convention. ipv6z(4) A non-global IPv6 address including a zone index as defined by the InetAddressIPv6z textual convention. dns(16) A DNS domain name as defined by the InetAddressDNS textual convention. Each definition of a concrete InetAddressType value must be accompanied by a definition of a textual convention for use with that InetAddressType. To support future extensions, the InetAddressType textual convention SHOULD NOT be sub-typed in object type definitions. It MAY be sub-typed in compliance statements in order to require only a subset of these address types for a compliant implementation. Implementations must ensure that InetAddressType objects and any dependent objects (e.g., InetAddress objects) are consistent. An inconsistentValue error must be generated if an attempt to change an InetAddressType object would, for example, lead to an undefined InetAddress value. In particular, InetAddressType/InetAddress pairs must be changed together if the address type changes (e.g., from ipv6(2) to ipv4(1)).' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 16)) namedValues = NamedValues(("unknown", 0), ("ipv4", 1), ("ipv6", 2), ("ipv4z", 3), ("ipv6z", 4), ("dns", 16)) class InetAddressIPv4(TextualConvention, OctetString): description = 'Represents an IPv4 network address: Octets Contents Encoding 1-4 IPv4 address network-byte order The corresponding InetAddressType value is ipv4(1). This textual convention SHOULD NOT be used directly in object definitions, as it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with InetAddressType, as a pair.' status = 'current' displayHint = '1d.1d.1d.1d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4) class InetAddressIPv6(TextualConvention, OctetString): description = 'Represents an IPv6 network address: Octets Contents Encoding 1-16 IPv6 address network-byte order The corresponding InetAddressType value is ipv6(2). This textual convention SHOULD NOT be used directly in object definitions, as it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with InetAddressType, as a pair.' status = 'current' displayHint = '2x:2x:2x:2x:2x:2x:2x:2x' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(16, 16) class InetAddressIPv4z(TextualConvention, OctetString): description = 'Represents a non-global IPv4 network address, together with its zone index: Octets Contents Encoding 1-4 IPv4 address network-byte order 5-8 zone index network-byte order The corresponding InetAddressType value is ipv4z(3). The zone index (bytes 5-8) is used to disambiguate identical address values on nodes that have interfaces attached to different zones of the same scope. The zone index may contain the special value 0, which refers to the default zone for each scope. This textual convention SHOULD NOT be used directly in object definitions, as it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with InetAddressType, as a pair.' status = 'current' displayHint = '1d.1d.1d.1d%4d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8) class InetAddressIPv6z(TextualConvention, OctetString): description = 'Represents a non-global IPv6 network address, together with its zone index: Octets Contents Encoding 1-16 IPv6 address network-byte order 17-20 zone index network-byte order The corresponding InetAddressType value is ipv6z(4). The zone index (bytes 17-20) is used to disambiguate identical address values on nodes that have interfaces attached to different zones of the same scope. The zone index may contain the special value 0, which refers to the default zone for each scope. This textual convention SHOULD NOT be used directly in object definitions, as it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with InetAddressType, as a pair.' status = 'current' displayHint = '2x:2x:2x:2x:2x:2x:2x:2x%4d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(20, 20) class InetAddressDNS(TextualConvention, OctetString): description = 'Represents a DNS domain name. The name SHOULD be fully qualified whenever possible. The corresponding InetAddressType is dns(16). The DESCRIPTION clause of InetAddress objects that may have InetAddressDNS values MUST fully describe how (and when) these names are to be resolved to IP addresses. The resolution of an InetAddressDNS value may require to query multiple DNS records (e.g., A for IPv4 and AAAA for IPv6). The order of the resolution process and which DNS record takes precedence depends on the configuration of the resolver. This textual convention SHOULD NOT be used directly in object definitions, as it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with InetAddressType, as a pair.' status = 'current' displayHint = '255a' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 255) # https://tools.ietf.org/html/rfc4001#section-4.1 class InetAddress(TextualConvention, OctetString): description = "Denotes a generic Internet address. An InetAddress value is always interpreted within the context of an InetAddressType value. Every usage of the InetAddress textual convention is required to specify the InetAddressType object that provides the context. It is suggested that the InetAddressType object be logically registered before the object(s) that use the InetAddress textual convention, if they appear in the same logical row. The value of an InetAddress object must always be consistent with the value of the associated InetAddressType object. Attempts to set an InetAddress object to a value inconsistent with the associated InetAddressType must fail with an inconsistentValue error. When this textual convention is used as the syntax of an index object, there may be issues with the limit of 128 sub-identifiers specified in SMIv2, STD 58. In this case, the object definition MUST include a 'SIZE' clause to limit the number of potential instance sub-identifiers; otherwise the applicable constraints MUST be stated in the appropriate conceptual row DESCRIPTION clauses, or in the surrounding documentation if there is no single DESCRIPTION clause that is appropriate." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) typeMap = { InetAddressType.namedValues.getValue("ipv4"): InetAddressIPv4(), InetAddressType.namedValues.getValue("ipv6"): InetAddressIPv6(), InetAddressType.namedValues.getValue("ipv4z"): InetAddressIPv4z(), InetAddressType.namedValues.getValue("ipv6z"): InetAddressIPv6z(), InetAddressType.namedValues.getValue("dns"): InetAddressDNS() } @classmethod def cloneFromName(cls, value, impliedFlag, parentRow, parentIndices): for parentIndex in reversed(parentIndices): if isinstance(parentIndex, InetAddressType): try: return parentRow.setFromName(cls.typeMap[int(parentIndex)], value, impliedFlag, parentIndices) except KeyError: pass raise error.SmiError('%s object encountered without preceding InetAddressType-like index: %r' % (cls.__name__, value)) def cloneAsName(self, impliedFlag, parentRow, parentIndices): for parentIndex in reversed(parentIndices): if isinstance(parentIndex, InetAddressType): try: return parentRow.getAsName(self.typeMap[int(parentIndex)].clone(self.asOctets().decode('ascii')), impliedFlag, parentIndices) except KeyError: pass raise error.SmiError('%s object encountered without preceding InetAddressType-like index: %r' % (self.__class__.__name__, self)) class InetAddressPrefixLength(TextualConvention, Unsigned32): description = "Denotes the length of a generic Internet network address prefix. A value of n corresponds to an IP address mask that has n contiguous 1-bits from the most significant bit (MSB), with all other bits set to 0. An InetAddressPrefixLength value is always interpreted within the context of an InetAddressType value. Every usage of the InetAddressPrefixLength textual convention is required to specify the InetAddressType object that provides the context. It is suggested that the InetAddressType object be logically registered before the object(s) that use the InetAddressPrefixLength textual convention, if they appear in the same logical row. InetAddressPrefixLength values larger than the maximum length of an IP address for a specific InetAddressType are treated as the maximum significant value applicable for the InetAddressType. The maximum significant value is 32 for the InetAddressType 'ipv4(1)' and 'ipv4z(3)' and 128 for the InetAddressType 'ipv6(2)' and 'ipv6z(4)'. The maximum significant value for the InetAddressType 'dns(16)' is 0. The value zero is object-specific and must be defined as part of the description of any object that uses this syntax. Examples of the usage of zero might include situations where the Internet network address prefix is unknown or does not apply. The upper bound of the prefix length has been chosen to be consistent with the maximum size of an InetAddress." status = 'current' displayHint = 'd' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 2040) class InetPortNumber(TextualConvention, Unsigned32): reference = 'STD 6 (RFC 768), STD 7 (RFC 793) and RFC 2960' description = 'Represents a 16 bit port number of an Internet transport layer protocol. Port numbers are assigned by IANA. A current list of all assignments is available from . The value zero is object-specific and must be defined as part of the description of any object that uses this syntax. Examples of the usage of zero might include situations where a port number is unknown, or when the value zero is used as a wildcard in a filter.' status = 'current' displayHint = 'd' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 65535) class InetAutonomousSystemNumber(TextualConvention, Unsigned32): reference = 'RFC 1771, RFC 1930' description = "Represents an autonomous system number that identifies an Autonomous System (AS). An AS is a set of routers under a single technical administration, using an interior gateway protocol and common metrics to route packets within the AS, and using an exterior gateway protocol to route packets to other ASes'. IANA maintains the AS number space and has delegated large parts to the regional registries. Autonomous system numbers are currently limited to 16 bits (0..65535). There is, however, work in progress to enlarge the autonomous system number space to 32 bits. Therefore, this textual convention uses an Unsigned32 value without a range restriction in order to support a larger autonomous system number space." status = 'current' displayHint = 'd' class InetScopeType(TextualConvention, Integer32): reference = 'RFC 3513' description = 'Represents a scope type. This textual convention can be used in cases where a MIB has to represent different scope types and there is no context information, such as an InetAddress object, that implicitly defines the scope type. Note that not all possible values have been assigned yet, but they may be assigned in future revisions of this specification. Applications should therefore be able to deal with values not yet assigned.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 8, 14)) namedValues = NamedValues(("interfaceLocal", 1), ("linkLocal", 2), ("subnetLocal", 3), ("adminLocal", 4), ("siteLocal", 5), ("organizationLocal", 8), ("global", 14)) class InetZoneIndex(TextualConvention, Unsigned32): reference = 'RFC4007' description = 'A zone index identifies an instance of a zone of a specific scope. The zone index MUST disambiguate identical address values. For link-local addresses, the zone index will typically be the interface index (ifIndex as defined in the IF-MIB) of the interface on which the address is configured. The zone index may contain the special value 0, which refers to the default zone. The default zone may be used in cases where the valid zone index is not known (e.g., when a management application has to write a link-local IPv6 address without knowing the interface index value). The default zone SHOULD NOT be used as an easy way out in cases where the zone index for a non-global IPv6 address is known.' status = 'current' displayHint = 'd' class InetVersion(TextualConvention, Integer32): reference = 'RFC 791, RFC 2460' description = 'A value representing a version of the IP protocol. unknown(0) An unknown or unspecified version of the IP protocol. ipv4(1) The IPv4 protocol as defined in RFC 791 (STD 5). ipv6(2) The IPv6 protocol as defined in RFC 2460. Note that this textual convention SHOULD NOT be used to distinguish different address types associated with IP protocols. The InetAddressType has been designed for this purpose.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2)) namedValues = NamedValues(("unknown", 0), ("ipv4", 1), ("ipv6", 2)) mibBuilder.exportSymbols("INET-ADDRESS-MIB", inetAddressMIB=inetAddressMIB, InetVersion=InetVersion, InetAddressIPv4=InetAddressIPv4, InetAddressIPv6z=InetAddressIPv6z, InetScopeType=InetScopeType, InetAddressType=InetAddressType, InetPortNumber=InetPortNumber, InetAddressIPv6=InetAddressIPv6, InetAddress=InetAddress, PYSNMP_MODULE_ID=inetAddressMIB, InetAddressDNS=InetAddressDNS, InetAutonomousSystemNumber=InetAutonomousSystemNumber, InetZoneIndex=InetZoneIndex, InetAddressPrefixLength=InetAddressPrefixLength, InetAddressIPv4z=InetAddressIPv4z) pysnmp-4.4.12/pysnmp/smi/mibs/PYSNMP-MIB.py000066400000000000000000000070051354244100700202070ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module PYSNMP-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/PYSNMP-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 11:46:02 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ModuleIdentity, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, NotificationType, IpAddress, MibIdentifier, Unsigned32, Counter32, ObjectIdentity, Counter64, Bits, Integer32, enterprises, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "NotificationType", "IpAddress", "MibIdentifier", "Unsigned32", "Counter32", "ObjectIdentity", "Counter64", "Bits", "Integer32", "enterprises", "TimeTicks") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408)) if mibBuilder.loadTexts: pysnmp.setRevisions(('2017-04-14 00:00', '2005-05-14 00:00',)) if mibBuilder.loadTexts: pysnmp.setLastUpdated('201704140000Z') if mibBuilder.loadTexts: pysnmp.setOrganization('The PySNMP Project') if mibBuilder.loadTexts: pysnmp.setContactInfo('E-mail: Ilya Etingof GitHub: https://github.com/etingof/pysnmp') if mibBuilder.loadTexts: pysnmp.setDescription('PySNMP top-level MIB tree infrastructure') 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)) pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999)) 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)) mibBuilder.exportSymbols("PYSNMP-MIB", pysnmpCompliances=pysnmpCompliances, pysnmpObjects=pysnmpObjects, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpGroups=pysnmpGroups, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmp=pysnmp, pysnmpExperimental=pysnmpExperimental, pysnmpNotifications=pysnmpNotifications, PYSNMP_MODULE_ID=pysnmp, pysnmpEnumerations=pysnmpEnumerations, pysnmpDomains=pysnmpDomains, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpConformance=pysnmpConformance, pysnmpExamples=pysnmpExamples) pysnmp-4.4.12/pysnmp/smi/mibs/PYSNMP-SOURCE-MIB.py000066400000000000000000000110121354244100700211760ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module PYSNMP-SOURCE-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/PYSNMP-SOURCE-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 11:46:02 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion") pysnmpModuleIDs, = mibBuilder.importSymbols("PYSNMP-MIB", "pysnmpModuleIDs") snmpTargetAddrEntry, = mibBuilder.importSymbols("SNMP-TARGET-MIB", "snmpTargetAddrEntry") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ModuleIdentity, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, NotificationType, IpAddress, MibIdentifier, Unsigned32, Counter32, ObjectIdentity, Counter64, Bits, Integer32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "NotificationType", "IpAddress", "MibIdentifier", "Unsigned32", "Counter32", "ObjectIdentity", "Counter64", "Bits", "Integer32", "TimeTicks") TextualConvention, DisplayString, TAddress = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TAddress") pysnmpSourceMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8)) if mibBuilder.loadTexts: pysnmpSourceMIB.setRevisions(('2017-04-14 00:00', '2015-01-16 00:00',)) if mibBuilder.loadTexts: pysnmpSourceMIB.setLastUpdated('201704140000Z') if mibBuilder.loadTexts: pysnmpSourceMIB.setOrganization('The PySNMP Project') if mibBuilder.loadTexts: pysnmpSourceMIB.setContactInfo('E-mail: Ilya Etingof GitHub: https://github.com/etingof/pysnmp') if mibBuilder.loadTexts: pysnmpSourceMIB.setDescription('This MIB module defines implementation specific objects that provide variable source transport endpoints feature to SNMP Engine and Standard SNMP Applications.') pysnmpSourceMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 1)) pysnmpSourceMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 2)) snmpSourceAddrTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 1, 1), ) if mibBuilder.loadTexts: snmpSourceAddrTable.setStatus('current') if mibBuilder.loadTexts: snmpSourceAddrTable.setDescription('A table of transport addresses to be used as a source in the generation of SNMP messages. This table contains additional objects for the SNMP-TRANSPORT-ADDRESS::snmpSourceAddressTable.') snmpSourceAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 1, 1, 1), ) snmpTargetAddrEntry.registerAugmentions(("PYSNMP-SOURCE-MIB", "snmpSourceAddrEntry")) snmpSourceAddrEntry.setIndexNames(*snmpTargetAddrEntry.getIndexNames()) if mibBuilder.loadTexts: snmpSourceAddrEntry.setStatus('current') if mibBuilder.loadTexts: snmpSourceAddrEntry.setDescription('A transport address to be used as a source in the generation of SNMP operations. An entry containing additional management information applicable to a particular target.') snmpSourceAddrTAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 1, 1, 1, 1), TAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpSourceAddrTAddress.setStatus('current') if mibBuilder.loadTexts: snmpSourceAddrTAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpSourceAddrTDomain object.') pysnmpSourceMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 2, 1)) pysnmpSourceMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 8, 2, 2)) mibBuilder.exportSymbols("PYSNMP-SOURCE-MIB", pysnmpSourceMIBConformance=pysnmpSourceMIBConformance, pysnmpSourceMIB=pysnmpSourceMIB, snmpSourceAddrTable=snmpSourceAddrTable, snmpSourceAddrEntry=snmpSourceAddrEntry, pysnmpSourceMIBGroups=pysnmpSourceMIBGroups, PYSNMP_MODULE_ID=pysnmpSourceMIB, snmpSourceAddrTAddress=snmpSourceAddrTAddress, pysnmpSourceMIBObjects=pysnmpSourceMIBObjects, pysnmpSourceMIBCompliances=pysnmpSourceMIBCompliances) pysnmp-4.4.12/pysnmp/smi/mibs/PYSNMP-USM-MIB.py000066400000000000000000000233001354244100700206450ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module PYSNMP-USM-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/PYSNMP-USM-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 11:46:02 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion") pysnmpModuleIDs, = mibBuilder.importSymbols("PYSNMP-MIB", "pysnmpModuleIDs") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") usmUserEntry, = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ModuleIdentity, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, NotificationType, IpAddress, MibIdentifier, Unsigned32, Counter32, ObjectIdentity, Counter64, Bits, Integer32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "NotificationType", "IpAddress", "MibIdentifier", "Unsigned32", "Counter32", "ObjectIdentity", "Counter64", "Bits", "Integer32", "TimeTicks") RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention") pysnmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1)) if mibBuilder.loadTexts: pysnmpUsmMIB.setRevisions(('2017-04-14 00:00', '2005-05-14 00:00',)) if mibBuilder.loadTexts: pysnmpUsmMIB.setLastUpdated('201704140000Z') if mibBuilder.loadTexts: pysnmpUsmMIB.setOrganization('The PySNMP Project') if mibBuilder.loadTexts: pysnmpUsmMIB.setContactInfo('E-mail: Ilya Etingof GitHub: https://github.com/etingof/pysnmp') if mibBuilder.loadTexts: pysnmpUsmMIB.setDescription('This MIB module defines objects specific to User Security Model (USM) implementation at PySNMP.') pysnmpUsmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1)) pysnmpUsmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2)) 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), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("notDiscoverable", 0), ("discoverable", 1))).clone('discoverable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: pysnmpUsmDiscoverable.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmDiscoverable.setDescription('Whether SNMP engine would support its discovery by responding to unknown clients.') pysnmpUsmDiscovery = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("doNotDiscover", 0), ("doDiscover", 1))).clone('doDiscover')).setMaxAccess("readwrite") if mibBuilder.loadTexts: pysnmpUsmDiscovery.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmDiscovery.setDescription('Whether SNMP engine would try to figure out the EngineIDs of its peers by sending discover requests.') pysnmpUsmKeyType = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("passphrase", 0), ("master", 1), ("localized", 2))).clone('passphrase')).setMaxAccess("not-accessible") if mibBuilder.loadTexts: pysnmpUsmKeyType.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmKeyType.setDescription('When configuring USM user, the value of this enumeration determines how the keys should be treated. The default value "passphrase" means that given keys are plain-text pass-phrases, "master" indicates that the keys are pre-hashed pass-phrases, while "localized" stands for pre-hashed pass-phrases mixed with SNMP Security Engine ID value.') pysnmpUsmUser = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3)) pysnmpUsmSecretTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2), ) if mibBuilder.loadTexts: pysnmpUsmSecretTable.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmSecretTable.setDescription("The table of USM users passphrases configured in the SNMP engine'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.setStatus('current') 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))) if mibBuilder.loadTexts: pysnmpUsmSecretUserName.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmSecretUserName.setDescription('The username string for which a row in this table represents a configuration.') pysnmpUsmSecretAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 2), OctetString('\x00\x00\x00\x00\x00\x00\x00\x00').subtype(subtypeSpec=ValueSizeConstraint(8, 65535))) if mibBuilder.loadTexts: pysnmpUsmSecretAuthKey.setStatus('current') 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('\x00\x00\x00\x00\x00\x00\x00\x00').subtype(subtypeSpec=ValueSizeConstraint(8, 65535))) if mibBuilder.loadTexts: pysnmpUsmSecretPrivKey.setStatus('current') 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.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmSecretStatus.setDescription('Table status') pysnmpUsmKeyTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3), ) if mibBuilder.loadTexts: pysnmpUsmKeyTable.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmKeyTable.setDescription("The table of USM users localized keys configured in the SNMP engine's Local Configuration Datastore (LCD).") pysnmpUsmKeyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1), ) usmUserEntry.registerAugmentions(("PYSNMP-USM-MIB", "pysnmpUsmKeyEntry")) pysnmpUsmKeyEntry.setIndexNames(*usmUserEntry.getIndexNames()) if mibBuilder.loadTexts: pysnmpUsmKeyEntry.setStatus('current') 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('\x00\x00\x00\x00\x00\x00\x00\x00').subtype(subtypeSpec=ValueSizeConstraint(8, 64))) if mibBuilder.loadTexts: pysnmpUsmKeyAuthLocalized.setStatus('current') 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('\x00\x00\x00\x00\x00\x00\x00\x00').subtype(subtypeSpec=ValueSizeConstraint(8, 64))) if mibBuilder.loadTexts: pysnmpUsmKeyPrivLocalized.setStatus('current') 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('\x00\x00\x00\x00\x00\x00\x00\x00').subtype(subtypeSpec=ValueSizeConstraint(8, 64))) if mibBuilder.loadTexts: pysnmpUsmKeyAuth.setStatus('current') 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('\x00\x00\x00\x00\x00\x00\x00\x00').subtype(subtypeSpec=ValueSizeConstraint(8, 64))) if mibBuilder.loadTexts: pysnmpUsmKeyPriv.setStatus('current') if mibBuilder.loadTexts: pysnmpUsmKeyPriv.setDescription("User's non-localized key used for encryption.") 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)) mibBuilder.exportSymbols("PYSNMP-USM-MIB", pysnmpUsmCfg=pysnmpUsmCfg, pysnmpUsmDiscoverable=pysnmpUsmDiscoverable, pysnmpUsmKeyType=pysnmpUsmKeyType, pysnmpUsmKeyEntry=pysnmpUsmKeyEntry, pysnmpUsmKeyTable=pysnmpUsmKeyTable, pysnmpUsmKeyPrivLocalized=pysnmpUsmKeyPrivLocalized, pysnmpUsmMIBCompliances=pysnmpUsmMIBCompliances, pysnmpUsmMIBObjects=pysnmpUsmMIBObjects, pysnmpUsmSecretTable=pysnmpUsmSecretTable, PYSNMP_MODULE_ID=pysnmpUsmMIB, pysnmpUsmSecretEntry=pysnmpUsmSecretEntry, pysnmpUsmMIBConformance=pysnmpUsmMIBConformance, pysnmpUsmUser=pysnmpUsmUser, pysnmpUsmKeyAuth=pysnmpUsmKeyAuth, pysnmpUsmSecretPrivKey=pysnmpUsmSecretPrivKey, pysnmpUsmKeyAuthLocalized=pysnmpUsmKeyAuthLocalized, pysnmpUsmMIB=pysnmpUsmMIB, pysnmpUsmDiscovery=pysnmpUsmDiscovery, pysnmpUsmSecretUserName=pysnmpUsmSecretUserName, pysnmpUsmKeyPriv=pysnmpUsmKeyPriv, pysnmpUsmSecretAuthKey=pysnmpUsmSecretAuthKey, pysnmpUsmSecretStatus=pysnmpUsmSecretStatus, pysnmpUsmMIBGroups=pysnmpUsmMIBGroups) pysnmp-4.4.12/pysnmp/smi/mibs/RFC1158-MIB.py000066400000000000000000000024421354244100700201120ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module RFC1158-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/RFC1158-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 12:12:07 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # # It is a stripped version of MIB that contains only symbols that is # unique to SMIv1 and have no analogues in SMIv2 # Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, iso, Gauge32, MibIdentifier, Bits, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "iso", "Gauge32", "MibIdentifier", "Bits","Counter32") snmpInBadTypes = MibScalar((1, 3, 6, 1, 2, 1, 11, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadTypes.setStatus('mandatory') snmpOutReadOnlys = MibScalar((1, 3, 6, 1, 2, 1, 11, 23), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutReadOnlys.setStatus('mandatory') mibBuilder.exportSymbols("RFC1158-MIB", snmpOutReadOnlys=snmpOutReadOnlys, snmpInBadTypes=snmpInBadTypes) pysnmp-4.4.12/pysnmp/smi/mibs/RFC1213-MIB.py000066400000000000000000001567451354244100700201220ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module RFC1213-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/RFC1213-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 12:12:07 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # # It is a stripped version of MIB that contains only symbols that is # unique to SMIv1 and have no analogues in SMIv2 # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, TimeTicks, NotificationType, ModuleIdentity, Integer32, Counter32, MibIdentifier, ObjectIdentity, Gauge32, Unsigned32, mgmt, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, iso, Counter64, mib_2 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "TimeTicks", "NotificationType", "ModuleIdentity", "Integer32", "Counter32", "MibIdentifier", "ObjectIdentity", "Gauge32", "Unsigned32", "mgmt", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "iso", "Counter64","mib-2") DisplayString, PhysAddress = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "PhysAddress") from pysnmp.proto.rfc1155 import NetworkAddress at = MibIdentifier((1, 3, 6, 1, 2, 1, 3)) ip = MibIdentifier((1, 3, 6, 1, 2, 1, 4)) egp = MibIdentifier((1, 3, 6, 1, 2, 1, 8)) atTable = MibTable((1, 3, 6, 1, 2, 1, 3, 1), ) if mibBuilder.loadTexts: atTable.setStatus('deprecated') if mibBuilder.loadTexts: atTable.setDescription("The Address Translation tables contain the NetworkAddress to `physical' address equivalences. Some interfaces do not use translation tables for determining address equivalences (e.g., DDN-X.25 has an algorithmic method); if all interfaces are of this type, then the Address Translation table is empty, i.e., has zero entries.") atEntry = MibTableRow((1, 3, 6, 1, 2, 1, 3, 1, 1), ).setIndexNames((0, "RFC1213-MIB", "atIfIndex"), (0, "RFC1213-MIB", "atNetAddress")) if mibBuilder.loadTexts: atEntry.setStatus('deprecated') if mibBuilder.loadTexts: atEntry.setDescription("Each entry contains one NetworkAddress to `physical' address equivalence.") atIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atIfIndex.setStatus('deprecated') if mibBuilder.loadTexts: atIfIndex.setDescription("The interface on which this entry's equivalence is effective. The interface identified by a particular value of this index is the same interface as identified by the same value of ifIndex.") atPhysAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 2), PhysAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atPhysAddress.setStatus('deprecated') if mibBuilder.loadTexts: atPhysAddress.setDescription("The media-dependent `physical' address. Setting this object to a null string (one of zero length) has the effect of invaliding the corresponding entry in the atTable object. That is, it effectively dissasociates the interface identified with said entry from the mapping identified with said entry. It is an implementation-specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries not currently in use. Proper interpretation of such entries requires examination of the relevant atPhysAddress object.") atNetAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 3, 1, 1, 3), NetworkAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: atNetAddress.setStatus('deprecated') if mibBuilder.loadTexts: atNetAddress.setDescription("The NetworkAddress (e.g., the IP address) corresponding to the media-dependent `physical' address.") ipForwarding = MibScalar((1, 3, 6, 1, 2, 1, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("forwarding", 1), ("not-forwarding", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipForwarding.setStatus('mandatory') if mibBuilder.loadTexts: ipForwarding.setDescription("The indication of whether this entity is acting as an IP gateway in respect to the forwarding of datagrams received by, but not addressed to, this entity. IP gateways forward datagrams. IP hosts do not (except those source-routed via the host). Note that for some managed nodes, this object may take on only a subset of the values possible. Accordingly, it is appropriate for an agent to return a `badValue' response if a management station attempts to change this object to an inappropriate value.") ipDefaultTTL = MibScalar((1, 3, 6, 1, 2, 1, 4, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipDefaultTTL.setStatus('mandatory') if mibBuilder.loadTexts: ipDefaultTTL.setDescription('The default value inserted into the Time-To-Live field of the IP header of datagrams originated at this entity, whenever a TTL value is not supplied by the transport layer protocol.') ipInReceives = MibScalar((1, 3, 6, 1, 2, 1, 4, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipInReceives.setStatus('mandatory') if mibBuilder.loadTexts: ipInReceives.setDescription('The total number of input datagrams received from interfaces, including those received in error.') ipInHdrErrors = MibScalar((1, 3, 6, 1, 2, 1, 4, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipInHdrErrors.setStatus('mandatory') if mibBuilder.loadTexts: ipInHdrErrors.setDescription('The number of input datagrams discarded due to errors in their IP headers, including bad checksums, version number mismatch, other format errors, time-to-live exceeded, errors discovered in processing their IP options, etc.') ipInAddrErrors = MibScalar((1, 3, 6, 1, 2, 1, 4, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipInAddrErrors.setStatus('mandatory') if mibBuilder.loadTexts: ipInAddrErrors.setDescription("The number of input datagrams discarded because the IP address in their IP header's destination field was not a valid address to be received at this entity. This count includes invalid addresses (e.g., 0.0.0.0) and addresses of unsupported Classes (e.g., Class E). For entities which are not IP Gateways and therefore do not forward datagrams, this counter includes datagrams discarded because the destination address was not a local address.") ipForwDatagrams = MibScalar((1, 3, 6, 1, 2, 1, 4, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipForwDatagrams.setStatus('mandatory') if mibBuilder.loadTexts: ipForwDatagrams.setDescription('The number of input datagrams for which this entity was not their final IP destination, as a result of which an attempt was made to find a route to forward them to that final destination. In entities which do not act as IP Gateways, this counter will include only those packets which were Source-Routed via this entity, and the Source- Route option processing was successful.') ipInUnknownProtos = MibScalar((1, 3, 6, 1, 2, 1, 4, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipInUnknownProtos.setStatus('mandatory') if mibBuilder.loadTexts: ipInUnknownProtos.setDescription('The number of locally-addressed datagrams received successfully but discarded because of an unknown or unsupported protocol.') ipInDiscards = MibScalar((1, 3, 6, 1, 2, 1, 4, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipInDiscards.setStatus('mandatory') if mibBuilder.loadTexts: ipInDiscards.setDescription('The number of input IP datagrams for which no problems were encountered to prevent their continued processing, but which were discarded (e.g., for lack of buffer space). Note that this counter does not include any datagrams discarded while awaiting re-assembly.') ipInDelivers = MibScalar((1, 3, 6, 1, 2, 1, 4, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipInDelivers.setStatus('mandatory') if mibBuilder.loadTexts: ipInDelivers.setDescription('The total number of input datagrams successfully delivered to IP user-protocols (including ICMP).') ipOutRequests = MibScalar((1, 3, 6, 1, 2, 1, 4, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipOutRequests.setStatus('mandatory') if mibBuilder.loadTexts: ipOutRequests.setDescription('The total number of IP datagrams which local IP user-protocols (including ICMP) supplied to IP in requests for transmission. Note that this counter does not include any datagrams counted in ipForwDatagrams.') ipOutDiscards = MibScalar((1, 3, 6, 1, 2, 1, 4, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipOutDiscards.setStatus('mandatory') if mibBuilder.loadTexts: ipOutDiscards.setDescription('The number of output IP datagrams for which no problem was encountered to prevent their transmission to their destination, but which were discarded (e.g., for lack of buffer space). Note that this counter would include datagrams counted in ipForwDatagrams if any such packets met this (discretionary) discard criterion.') ipOutNoRoutes = MibScalar((1, 3, 6, 1, 2, 1, 4, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipOutNoRoutes.setStatus('mandatory') if mibBuilder.loadTexts: ipOutNoRoutes.setDescription("The number of IP datagrams discarded because no route could be found to transmit them to their destination. Note that this counter includes any packets counted in ipForwDatagrams which meet this `no-route' criterion. Note that this includes any datagarms which a host cannot route because all of its default gateways are down.") ipReasmTimeout = MibScalar((1, 3, 6, 1, 2, 1, 4, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipReasmTimeout.setStatus('mandatory') if mibBuilder.loadTexts: ipReasmTimeout.setDescription('The maximum number of seconds which received fragments are held while they are awaiting reassembly at this entity.') ipReasmReqds = MibScalar((1, 3, 6, 1, 2, 1, 4, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipReasmReqds.setStatus('mandatory') if mibBuilder.loadTexts: ipReasmReqds.setDescription('The number of IP fragments received which needed to be reassembled at this entity.') ipReasmOKs = MibScalar((1, 3, 6, 1, 2, 1, 4, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipReasmOKs.setStatus('mandatory') if mibBuilder.loadTexts: ipReasmOKs.setDescription('The number of IP datagrams successfully re- assembled.') ipReasmFails = MibScalar((1, 3, 6, 1, 2, 1, 4, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipReasmFails.setStatus('mandatory') if mibBuilder.loadTexts: ipReasmFails.setDescription('The number of failures detected by the IP re- assembly algorithm (for whatever reason: timed out, errors, etc). Note that this is not necessarily a count of discarded IP fragments since some algorithms (notably the algorithm in RFC 815) can lose track of the number of fragments by combining them as they are received.') ipFragOKs = MibScalar((1, 3, 6, 1, 2, 1, 4, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipFragOKs.setStatus('mandatory') if mibBuilder.loadTexts: ipFragOKs.setDescription('The number of IP datagrams that have been successfully fragmented at this entity.') ipFragFails = MibScalar((1, 3, 6, 1, 2, 1, 4, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipFragFails.setStatus('mandatory') if mibBuilder.loadTexts: ipFragFails.setDescription("The number of IP datagrams that have been discarded because they needed to be fragmented at this entity but could not be, e.g., because their Don't Fragment flag was set.") ipFragCreates = MibScalar((1, 3, 6, 1, 2, 1, 4, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipFragCreates.setStatus('mandatory') if mibBuilder.loadTexts: ipFragCreates.setDescription('The number of IP datagram fragments that have been generated as a result of fragmentation at this entity.') ipAddrTable = MibTable((1, 3, 6, 1, 2, 1, 4, 20), ) if mibBuilder.loadTexts: ipAddrTable.setStatus('mandatory') if mibBuilder.loadTexts: ipAddrTable.setDescription("The table of addressing information relevant to this entity's IP addresses.") ipAddrEntry = MibTableRow((1, 3, 6, 1, 2, 1, 4, 20, 1), ).setIndexNames((0, "RFC1213-MIB", "ipAdEntAddr")) if mibBuilder.loadTexts: ipAddrEntry.setStatus('mandatory') if mibBuilder.loadTexts: ipAddrEntry.setDescription("The addressing information for one of this entity's IP addresses.") ipAdEntAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipAdEntAddr.setStatus('mandatory') if mibBuilder.loadTexts: ipAdEntAddr.setDescription("The IP address to which this entry's addressing information pertains.") ipAdEntIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipAdEntIfIndex.setStatus('mandatory') if mibBuilder.loadTexts: ipAdEntIfIndex.setDescription('The index value which uniquely identifies the interface to which this entry is applicable. The interface identified by a particular value of this index is the same interface as identified by the same value of ifIndex.') ipAdEntNetMask = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipAdEntNetMask.setStatus('mandatory') if mibBuilder.loadTexts: ipAdEntNetMask.setDescription('The subnet mask associated with the IP address of this entry. The value of the mask is an IP address with all the network bits set to 1 and all the hosts bits set to 0.') ipAdEntBcastAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipAdEntBcastAddr.setStatus('mandatory') if mibBuilder.loadTexts: ipAdEntBcastAddr.setDescription('The value of the least-significant bit in the IP broadcast address used for sending datagrams on the (logical) interface associated with the IP address of this entry. For example, when the Internet standard all-ones broadcast address is used, the value will be 1. This value applies to both the subnet and network broadcasts addresses used by the entity on this (logical) interface.') ipAdEntReasmMaxSize = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 20, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: ipAdEntReasmMaxSize.setStatus('mandatory') if mibBuilder.loadTexts: ipAdEntReasmMaxSize.setDescription('The size of the largest IP datagram which this entity can re-assemble from incoming IP fragmented datagrams received on this interface.') ipRouteTable = MibTable((1, 3, 6, 1, 2, 1, 4, 21), ) if mibBuilder.loadTexts: ipRouteTable.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteTable.setDescription("This entity's IP Routing table.") ipRouteEntry = MibTableRow((1, 3, 6, 1, 2, 1, 4, 21, 1), ).setIndexNames((0, "RFC1213-MIB", "ipRouteDest")) if mibBuilder.loadTexts: ipRouteEntry.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteEntry.setDescription('A route to a particular destination.') ipRouteDest = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 1), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteDest.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteDest.setDescription('The destination IP address of this route. An entry with a value of 0.0.0.0 is considered a default route. Multiple routes to a single destination can appear in the table, but access to such multiple entries is dependent on the table- access mechanisms defined by the network management protocol in use.') ipRouteIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteIfIndex.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteIfIndex.setDescription('The index value which uniquely identifies the local interface through which the next hop of this route should be reached. The interface identified by a particular value of this index is the same interface as identified by the same value of ifIndex.') ipRouteMetric1 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteMetric1.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteMetric1.setDescription("The primary routing metric for this route. The semantics of this metric are determined by the routing-protocol specified in the route's ipRouteProto value. If this metric is not used, its value should be set to -1.") ipRouteMetric2 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteMetric2.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteMetric2.setDescription("An alternate routing metric for this route. The semantics of this metric are determined by the routing-protocol specified in the route's ipRouteProto value. If this metric is not used, its value should be set to -1.") ipRouteMetric3 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteMetric3.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteMetric3.setDescription("An alternate routing metric for this route. The semantics of this metric are determined by the routing-protocol specified in the route's ipRouteProto value. If this metric is not used, its value should be set to -1.") ipRouteMetric4 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteMetric4.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteMetric4.setDescription("An alternate routing metric for this route. The semantics of this metric are determined by the routing-protocol specified in the route's ipRouteProto value. If this metric is not used, its value should be set to -1.") ipRouteNextHop = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 7), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteNextHop.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteNextHop.setDescription("The IP address of the next hop of this route. (In the case of a route bound to an interface which is realized via a broadcast media, the value of this field is the agent's IP address on that interface.)") ipRouteType = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("direct", 3), ("indirect", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteType.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteType.setDescription('The type of route. Note that the values direct(3) and indirect(4) refer to the notion of direct and indirect routing in the IP architecture. Setting this object to the value invalid(2) has the effect of invalidating the corresponding entry in the ipRouteTable object. That is, it effectively dissasociates the destination identified with said entry from the route identified with said entry. It is an implementation-specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries not currently in use. Proper interpretation of such entries requires examination of the relevant ipRouteType object.') ipRouteProto = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14))).clone(namedValues=NamedValues(("other", 1), ("local", 2), ("netmgmt", 3), ("icmp", 4), ("egp", 5), ("ggp", 6), ("hello", 7), ("rip", 8), ("is-is", 9), ("es-is", 10), ("ciscoIgrp", 11), ("bbnSpfIgp", 12), ("ospf", 13), ("bgp", 14)))).setMaxAccess("readonly") if mibBuilder.loadTexts: ipRouteProto.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteProto.setDescription('The routing mechanism via which this route was learned. Inclusion of values for gateway routing protocols is not intended to imply that hosts should support those protocols.') ipRouteAge = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 10), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteAge.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteAge.setDescription("The number of seconds since this route was last updated or otherwise determined to be correct. Note that no semantics of `too old' can be implied except through knowledge of the routing protocol by which the route was learned.") ipRouteMask = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 11), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteMask.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteMask.setDescription('Indicate the mask to be logical-ANDed with the destination address before being compared to the value in the ipRouteDest field. For those systems that do not support arbitrary subnet masks, an agent constructs the value of the ipRouteMask by determining whether the value of the correspondent ipRouteDest field belong to a class-A, B, or C network, and then using one of: mask network 255.0.0.0 class-A 255.255.0.0 class-B 255.255.255.0 class-C If the value of the ipRouteDest is 0.0.0.0 (a default route), then the mask value is also 0.0.0.0. It should be noted that all IP routing subsystems implicitly use this mechanism.') ipRouteMetric5 = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 12), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipRouteMetric5.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteMetric5.setDescription("An alternate routing metric for this route. The semantics of this metric are determined by the routing-protocol specified in the route's ipRouteProto value. If this metric is not used, its value should be set to -1.") ipRouteInfo = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 21, 1, 13), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipRouteInfo.setStatus('mandatory') if mibBuilder.loadTexts: ipRouteInfo.setDescription("A reference to MIB definitions specific to the particular routing protocol which is responsible for this route, as determined by the value specified in the route's ipRouteProto value. If this information is not present, its value should be set to the OBJECT IDENTIFIER { 0 0 }, which is a syntatically valid object identifier, and any conformant implementation of ASN.1 and BER must be able to generate and recognize this value.") ipNetToMediaTable = MibTable((1, 3, 6, 1, 2, 1, 4, 22), ) if mibBuilder.loadTexts: ipNetToMediaTable.setStatus('mandatory') if mibBuilder.loadTexts: ipNetToMediaTable.setDescription('The IP Address Translation table used for mapping from IP addresses to physical addresses.') ipNetToMediaEntry = MibTableRow((1, 3, 6, 1, 2, 1, 4, 22, 1), ).setIndexNames((0, "RFC1213-MIB", "ipNetToMediaIfIndex"), (0, "RFC1213-MIB", "ipNetToMediaNetAddress")) if mibBuilder.loadTexts: ipNetToMediaEntry.setStatus('mandatory') if mibBuilder.loadTexts: ipNetToMediaEntry.setDescription("Each entry contains one IpAddress to `physical' address equivalence.") ipNetToMediaIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNetToMediaIfIndex.setStatus('mandatory') if mibBuilder.loadTexts: ipNetToMediaIfIndex.setDescription("The interface on which this entry's equivalence is effective. The interface identified by a particular value of this index is the same interface as identified by the same value of ifIndex.") ipNetToMediaPhysAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 2), PhysAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNetToMediaPhysAddress.setStatus('mandatory') if mibBuilder.loadTexts: ipNetToMediaPhysAddress.setDescription("The media-dependent `physical' address.") ipNetToMediaNetAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 3), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNetToMediaNetAddress.setStatus('mandatory') if mibBuilder.loadTexts: ipNetToMediaNetAddress.setDescription("The IpAddress corresponding to the media- dependent `physical' address.") ipNetToMediaType = MibTableColumn((1, 3, 6, 1, 2, 1, 4, 22, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("dynamic", 3), ("static", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: ipNetToMediaType.setStatus('mandatory') if mibBuilder.loadTexts: ipNetToMediaType.setDescription('The type of mapping. Setting this object to the value invalid(2) has the effect of invalidating the corresponding entry in the ipNetToMediaTable. That is, it effectively dissasociates the interface identified with said entry from the mapping identified with said entry. It is an implementation-specific matter as to whether the agent removes an invalidated entry from the table. Accordingly, management stations must be prepared to receive tabular information from agents that corresponds to entries not currently in use. Proper interpretation of such entries requires examination of the relevant ipNetToMediaType object.') ipRoutingDiscards = MibScalar((1, 3, 6, 1, 2, 1, 4, 23), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ipRoutingDiscards.setStatus('mandatory') if mibBuilder.loadTexts: ipRoutingDiscards.setDescription('The number of routing entries which were chosen to be discarded even though they are valid. One possible reason for discarding such an entry could be to free-up buffer space for other routing entries.') icmpInMsgs = MibScalar((1, 3, 6, 1, 2, 1, 5, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInMsgs.setStatus('mandatory') if mibBuilder.loadTexts: icmpInMsgs.setDescription('The total number of ICMP messages which the entity received. Note that this counter includes all those counted by icmpInErrors.') icmpInErrors = MibScalar((1, 3, 6, 1, 2, 1, 5, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInErrors.setStatus('mandatory') if mibBuilder.loadTexts: icmpInErrors.setDescription('The number of ICMP messages which the entity received but determined as having ICMP-specific errors (bad ICMP checksums, bad length, etc.).') icmpInDestUnreachs = MibScalar((1, 3, 6, 1, 2, 1, 5, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInDestUnreachs.setStatus('mandatory') if mibBuilder.loadTexts: icmpInDestUnreachs.setDescription('The number of ICMP Destination Unreachable messages received.') icmpInTimeExcds = MibScalar((1, 3, 6, 1, 2, 1, 5, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInTimeExcds.setStatus('mandatory') if mibBuilder.loadTexts: icmpInTimeExcds.setDescription('The number of ICMP Time Exceeded messages received.') icmpInParmProbs = MibScalar((1, 3, 6, 1, 2, 1, 5, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInParmProbs.setStatus('mandatory') if mibBuilder.loadTexts: icmpInParmProbs.setDescription('The number of ICMP Parameter Problem messages received.') icmpInSrcQuenchs = MibScalar((1, 3, 6, 1, 2, 1, 5, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInSrcQuenchs.setStatus('mandatory') if mibBuilder.loadTexts: icmpInSrcQuenchs.setDescription('The number of ICMP Source Quench messages received.') icmpInRedirects = MibScalar((1, 3, 6, 1, 2, 1, 5, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInRedirects.setStatus('mandatory') if mibBuilder.loadTexts: icmpInRedirects.setDescription('The number of ICMP Redirect messages received.') icmpInEchos = MibScalar((1, 3, 6, 1, 2, 1, 5, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInEchos.setStatus('mandatory') if mibBuilder.loadTexts: icmpInEchos.setDescription('The number of ICMP Echo (request) messages received.') icmpInEchoReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInEchoReps.setStatus('mandatory') if mibBuilder.loadTexts: icmpInEchoReps.setDescription('The number of ICMP Echo Reply messages received.') icmpInTimestamps = MibScalar((1, 3, 6, 1, 2, 1, 5, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInTimestamps.setStatus('mandatory') if mibBuilder.loadTexts: icmpInTimestamps.setDescription('The number of ICMP Timestamp (request) messages received.') icmpInTimestampReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInTimestampReps.setStatus('mandatory') if mibBuilder.loadTexts: icmpInTimestampReps.setDescription('The number of ICMP Timestamp Reply messages received.') icmpInAddrMasks = MibScalar((1, 3, 6, 1, 2, 1, 5, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInAddrMasks.setStatus('mandatory') if mibBuilder.loadTexts: icmpInAddrMasks.setDescription('The number of ICMP Address Mask Request messages received.') icmpInAddrMaskReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpInAddrMaskReps.setStatus('mandatory') if mibBuilder.loadTexts: icmpInAddrMaskReps.setDescription('The number of ICMP Address Mask Reply messages received.') icmpOutMsgs = MibScalar((1, 3, 6, 1, 2, 1, 5, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutMsgs.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutMsgs.setDescription('The total number of ICMP messages which this entity attempted to send. Note that this counter includes all those counted by icmpOutErrors.') icmpOutErrors = MibScalar((1, 3, 6, 1, 2, 1, 5, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutErrors.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutErrors.setDescription("The number of ICMP messages which this entity did not send due to problems discovered within ICMP such as a lack of buffers. This value should not include errors discovered outside the ICMP layer such as the inability of IP to route the resultant datagram. In some implementations there may be no types of error which contribute to this counter's value.") icmpOutDestUnreachs = MibScalar((1, 3, 6, 1, 2, 1, 5, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutDestUnreachs.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutDestUnreachs.setDescription('The number of ICMP Destination Unreachable messages sent.') icmpOutTimeExcds = MibScalar((1, 3, 6, 1, 2, 1, 5, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutTimeExcds.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutTimeExcds.setDescription('The number of ICMP Time Exceeded messages sent.') icmpOutParmProbs = MibScalar((1, 3, 6, 1, 2, 1, 5, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutParmProbs.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutParmProbs.setDescription('The number of ICMP Parameter Problem messages sent.') icmpOutSrcQuenchs = MibScalar((1, 3, 6, 1, 2, 1, 5, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutSrcQuenchs.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutSrcQuenchs.setDescription('The number of ICMP Source Quench messages sent.') icmpOutRedirects = MibScalar((1, 3, 6, 1, 2, 1, 5, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutRedirects.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutRedirects.setDescription('The number of ICMP Redirect messages sent. For a host, this object will always be zero, since hosts do not send redirects.') icmpOutEchos = MibScalar((1, 3, 6, 1, 2, 1, 5, 21), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutEchos.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutEchos.setDescription('The number of ICMP Echo (request) messages sent.') icmpOutEchoReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 22), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutEchoReps.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutEchoReps.setDescription('The number of ICMP Echo Reply messages sent.') icmpOutTimestamps = MibScalar((1, 3, 6, 1, 2, 1, 5, 23), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutTimestamps.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutTimestamps.setDescription('The number of ICMP Timestamp (request) messages sent.') icmpOutTimestampReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 24), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutTimestampReps.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutTimestampReps.setDescription('The number of ICMP Timestamp Reply messages sent.') icmpOutAddrMasks = MibScalar((1, 3, 6, 1, 2, 1, 5, 25), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutAddrMasks.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutAddrMasks.setDescription('The number of ICMP Address Mask Request messages sent.') icmpOutAddrMaskReps = MibScalar((1, 3, 6, 1, 2, 1, 5, 26), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: icmpOutAddrMaskReps.setStatus('mandatory') if mibBuilder.loadTexts: icmpOutAddrMaskReps.setDescription('The number of ICMP Address Mask Reply messages sent.') tcpRtoAlgorithm = MibScalar((1, 3, 6, 1, 2, 1, 6, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("constant", 2), ("rsre", 3), ("vanj", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpRtoAlgorithm.setStatus('mandatory') if mibBuilder.loadTexts: tcpRtoAlgorithm.setDescription('The algorithm used to determine the timeout value used for retransmitting unacknowledged octets.') tcpRtoMin = MibScalar((1, 3, 6, 1, 2, 1, 6, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpRtoMin.setStatus('mandatory') if mibBuilder.loadTexts: tcpRtoMin.setDescription('The minimum value permitted by a TCP implementation for the retransmission timeout, measured in milliseconds. More refined semantics for objects of this type depend upon the algorithm used to determine the retransmission timeout. In particular, when the timeout algorithm is rsre(3), an object of this type has the semantics of the LBOUND quantity described in RFC 793.') tcpRtoMax = MibScalar((1, 3, 6, 1, 2, 1, 6, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpRtoMax.setStatus('mandatory') if mibBuilder.loadTexts: tcpRtoMax.setDescription('The maximum value permitted by a TCP implementation for the retransmission timeout, measured in milliseconds. More refined semantics for objects of this type depend upon the algorithm used to determine the retransmission timeout. In particular, when the timeout algorithm is rsre(3), an object of this type has the semantics of the UBOUND quantity described in RFC 793.') tcpMaxConn = MibScalar((1, 3, 6, 1, 2, 1, 6, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpMaxConn.setStatus('mandatory') if mibBuilder.loadTexts: tcpMaxConn.setDescription('The limit on the total number of TCP connections the entity can support. In entities where the maximum number of connections is dynamic, this object should contain the value -1.') tcpActiveOpens = MibScalar((1, 3, 6, 1, 2, 1, 6, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpActiveOpens.setStatus('mandatory') if mibBuilder.loadTexts: tcpActiveOpens.setDescription('The number of times TCP connections have made a direct transition to the SYN-SENT state from the CLOSED state.') tcpPassiveOpens = MibScalar((1, 3, 6, 1, 2, 1, 6, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpPassiveOpens.setStatus('mandatory') if mibBuilder.loadTexts: tcpPassiveOpens.setDescription('The number of times TCP connections have made a direct transition to the SYN-RCVD state from the LISTEN state.') tcpAttemptFails = MibScalar((1, 3, 6, 1, 2, 1, 6, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpAttemptFails.setStatus('mandatory') if mibBuilder.loadTexts: tcpAttemptFails.setDescription('The number of times TCP connections have made a direct transition to the CLOSED state from either the SYN-SENT state or the SYN-RCVD state, plus the number of times TCP connections have made a direct transition to the LISTEN state from the SYN-RCVD state.') tcpEstabResets = MibScalar((1, 3, 6, 1, 2, 1, 6, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpEstabResets.setStatus('mandatory') if mibBuilder.loadTexts: tcpEstabResets.setDescription('The number of times TCP connections have made a direct transition to the CLOSED state from either the ESTABLISHED state or the CLOSE-WAIT state.') tcpCurrEstab = MibScalar((1, 3, 6, 1, 2, 1, 6, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpCurrEstab.setStatus('mandatory') if mibBuilder.loadTexts: tcpCurrEstab.setDescription('The number of TCP connections for which the current state is either ESTABLISHED or CLOSE- WAIT.') tcpInSegs = MibScalar((1, 3, 6, 1, 2, 1, 6, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpInSegs.setStatus('mandatory') if mibBuilder.loadTexts: tcpInSegs.setDescription('The total number of segments received, including those received in error. This count includes segments received on currently established connections.') tcpOutSegs = MibScalar((1, 3, 6, 1, 2, 1, 6, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpOutSegs.setStatus('mandatory') if mibBuilder.loadTexts: tcpOutSegs.setDescription('The total number of segments sent, including those on current connections but excluding those containing only retransmitted octets.') tcpRetransSegs = MibScalar((1, 3, 6, 1, 2, 1, 6, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpRetransSegs.setStatus('mandatory') if mibBuilder.loadTexts: tcpRetransSegs.setDescription('The total number of segments retransmitted - that is, the number of TCP segments transmitted containing one or more previously transmitted octets.') tcpConnTable = MibTable((1, 3, 6, 1, 2, 1, 6, 13), ) if mibBuilder.loadTexts: tcpConnTable.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnTable.setDescription('A table containing TCP connection-specific information.') 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")) if mibBuilder.loadTexts: tcpConnEntry.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnEntry.setDescription('Information about a particular current TCP connection. An object of this type is transient, in that it ceases to exist when (or soon after) the connection makes the transition to the CLOSED state.') tcpConnState = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("closed", 1), ("listen", 2), ("synSent", 3), ("synReceived", 4), ("established", 5), ("finWait1", 6), ("finWait2", 7), ("closeWait", 8), ("lastAck", 9), ("closing", 10), ("timeWait", 11), ("deleteTCB", 12)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: tcpConnState.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnState.setDescription("The state of this TCP connection. The only value which may be set by a management station is deleteTCB(12). Accordingly, it is appropriate for an agent to return a `badValue' response if a management station attempts to set this object to any other value. If a management station sets this object to the value deleteTCB(12), then this has the effect of deleting the TCB (as defined in RFC 793) of the corresponding connection on the managed node, resulting in immediate termination of the connection. As an implementation-specific option, a RST segment may be sent from the managed node to the other TCP endpoint (note however that RST segments are not sent reliably).") tcpConnLocalAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpConnLocalAddress.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnLocalAddress.setDescription('The local IP address for this TCP connection. In the case of a connection in the listen state which is willing to accept connections for any IP interface associated with the node, the value 0.0.0.0 is used.') tcpConnLocalPort = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpConnLocalPort.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnLocalPort.setDescription('The local port number for this TCP connection.') tcpConnRemAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpConnRemAddress.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnRemAddress.setDescription('The remote IP address for this TCP connection.') tcpConnRemPort = MibTableColumn((1, 3, 6, 1, 2, 1, 6, 13, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpConnRemPort.setStatus('mandatory') if mibBuilder.loadTexts: tcpConnRemPort.setDescription('The remote port number for this TCP connection.') tcpInErrs = MibScalar((1, 3, 6, 1, 2, 1, 6, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpInErrs.setStatus('mandatory') if mibBuilder.loadTexts: tcpInErrs.setDescription('The total number of segments received in error (e.g., bad TCP checksums).') tcpOutRsts = MibScalar((1, 3, 6, 1, 2, 1, 6, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tcpOutRsts.setStatus('mandatory') if mibBuilder.loadTexts: tcpOutRsts.setDescription('The number of TCP segments sent containing the RST flag.') udpInDatagrams = MibScalar((1, 3, 6, 1, 2, 1, 7, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: udpInDatagrams.setStatus('mandatory') if mibBuilder.loadTexts: udpInDatagrams.setDescription('The total number of UDP datagrams delivered to UDP users.') udpNoPorts = MibScalar((1, 3, 6, 1, 2, 1, 7, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: udpNoPorts.setStatus('mandatory') if mibBuilder.loadTexts: udpNoPorts.setDescription('The total number of received UDP datagrams for which there was no application at the destination port.') udpInErrors = MibScalar((1, 3, 6, 1, 2, 1, 7, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: udpInErrors.setStatus('mandatory') if mibBuilder.loadTexts: udpInErrors.setDescription('The number of received UDP datagrams that could not be delivered for reasons other than the lack of an application at the destination port.') udpOutDatagrams = MibScalar((1, 3, 6, 1, 2, 1, 7, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: udpOutDatagrams.setStatus('mandatory') if mibBuilder.loadTexts: udpOutDatagrams.setDescription('The total number of UDP datagrams sent from this entity.') udpTable = MibTable((1, 3, 6, 1, 2, 1, 7, 5), ) if mibBuilder.loadTexts: udpTable.setStatus('mandatory') if mibBuilder.loadTexts: udpTable.setDescription('A table containing UDP listener information.') udpEntry = MibTableRow((1, 3, 6, 1, 2, 1, 7, 5, 1), ).setIndexNames((0, "RFC1213-MIB", "udpLocalAddress"), (0, "RFC1213-MIB", "udpLocalPort")) if mibBuilder.loadTexts: udpEntry.setStatus('mandatory') if mibBuilder.loadTexts: udpEntry.setDescription('Information about a particular current UDP listener.') udpLocalAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 7, 5, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: udpLocalAddress.setStatus('mandatory') if mibBuilder.loadTexts: udpLocalAddress.setDescription('The local IP address for this UDP listener. In the case of a UDP listener which is willing to accept datagrams for any IP interface associated with the node, the value 0.0.0.0 is used.') udpLocalPort = MibTableColumn((1, 3, 6, 1, 2, 1, 7, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: udpLocalPort.setStatus('mandatory') if mibBuilder.loadTexts: udpLocalPort.setDescription('The local port number for this UDP listener.') egpInMsgs = MibScalar((1, 3, 6, 1, 2, 1, 8, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpInMsgs.setStatus('mandatory') if mibBuilder.loadTexts: egpInMsgs.setDescription('The number of EGP messages received without error.') egpInErrors = MibScalar((1, 3, 6, 1, 2, 1, 8, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpInErrors.setStatus('mandatory') if mibBuilder.loadTexts: egpInErrors.setDescription('The number of EGP messages received that proved to be in error.') egpOutMsgs = MibScalar((1, 3, 6, 1, 2, 1, 8, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpOutMsgs.setStatus('mandatory') if mibBuilder.loadTexts: egpOutMsgs.setDescription('The total number of locally generated EGP messages.') egpOutErrors = MibScalar((1, 3, 6, 1, 2, 1, 8, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpOutErrors.setStatus('mandatory') if mibBuilder.loadTexts: egpOutErrors.setDescription('The number of locally generated EGP messages not sent due to resource limitations within an EGP entity.') egpNeighTable = MibTable((1, 3, 6, 1, 2, 1, 8, 5), ) if mibBuilder.loadTexts: egpNeighTable.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighTable.setDescription('The EGP neighbor table.') egpNeighEntry = MibTableRow((1, 3, 6, 1, 2, 1, 8, 5, 1), ).setIndexNames((0, "RFC1213-MIB", "egpNeighAddr")) if mibBuilder.loadTexts: egpNeighEntry.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighEntry.setDescription("Information about this entity's relationship with a particular EGP neighbor.") egpNeighState = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("idle", 1), ("acquisition", 2), ("down", 3), ("up", 4), ("cease", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighState.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighState.setDescription("The EGP state of the local system with respect to this entry's EGP neighbor. Each EGP state is represented by a value that is one greater than the numerical value associated with said state in RFC 904.") egpNeighAddr = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighAddr.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighAddr.setDescription("The IP address of this entry's EGP neighbor.") egpNeighAs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighAs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighAs.setDescription('The autonomous system of this EGP peer. Zero should be specified if the autonomous system number of the neighbor is not yet known.') egpNeighInMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighInMsgs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighInMsgs.setDescription('The number of EGP messages received without error from this EGP peer.') egpNeighInErrs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighInErrs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighInErrs.setDescription('The number of EGP messages received from this EGP peer that proved to be in error (e.g., bad EGP checksum).') egpNeighOutMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighOutMsgs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighOutMsgs.setDescription('The number of locally generated EGP messages to this EGP peer.') egpNeighOutErrs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighOutErrs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighOutErrs.setDescription('The number of locally generated EGP messages not sent to this EGP peer due to resource limitations within an EGP entity.') egpNeighInErrMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighInErrMsgs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighInErrMsgs.setDescription('The number of EGP-defined error messages received from this EGP peer.') egpNeighOutErrMsgs = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighOutErrMsgs.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighOutErrMsgs.setDescription('The number of EGP-defined error messages sent to this EGP peer.') egpNeighStateUps = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighStateUps.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighStateUps.setDescription('The number of EGP state transitions to the UP state with this EGP peer.') egpNeighStateDowns = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighStateDowns.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighStateDowns.setDescription('The number of EGP state transitions from the UP state to any other state with this EGP peer.') egpNeighIntervalHello = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighIntervalHello.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighIntervalHello.setDescription('The interval between EGP Hello command retransmissions (in hundredths of a second). This represents the t1 timer as defined in RFC 904.') egpNeighIntervalPoll = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighIntervalPoll.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighIntervalPoll.setDescription('The interval between EGP poll command retransmissions (in hundredths of a second). This represents the t3 timer as defined in RFC 904.') egpNeighMode = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("active", 1), ("passive", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: egpNeighMode.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighMode.setDescription('The polling mode of this EGP entity, either passive or active.') egpNeighEventTrigger = MibTableColumn((1, 3, 6, 1, 2, 1, 8, 5, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("start", 1), ("stop", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: egpNeighEventTrigger.setStatus('mandatory') if mibBuilder.loadTexts: egpNeighEventTrigger.setDescription("A control variable used to trigger operator- initiated Start and Stop events. When read, this variable always returns the most recent value that egpNeighEventTrigger was set to. If it has not been set since the last initialization of the network management subsystem on the node, it returns a value of `stop'. When set, this variable causes a Start or Stop event on the specified neighbor, as specified on pages 8-10 of RFC 904. Briefly, a Start event causes an Idle peer to begin neighbor acquisition and a non-Idle peer to reinitiate neighbor acquisition. A stop event causes a non-Idle peer to return to the Idle state until a Start event occurs, either via egpNeighEventTrigger or otherwise.") egpAs = MibScalar((1, 3, 6, 1, 2, 1, 8, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: egpAs.setStatus('mandatory') if mibBuilder.loadTexts: egpAs.setDescription('The autonomous system number of this EGP entity.') mibBuilder.exportSymbols("RFC1213-MIB", ipAdEntReasmMaxSize=ipAdEntReasmMaxSize, icmpOutAddrMasks=icmpOutAddrMasks, ipRouteNextHop=ipRouteNextHop, tcpRtoMax=tcpRtoMax, ipOutRequests=ipOutRequests, udpNoPorts=udpNoPorts, ipNetToMediaIfIndex=ipNetToMediaIfIndex, ipNetToMediaTable=ipNetToMediaTable, udpTable=udpTable, tcpRetransSegs=tcpRetransSegs, icmpOutAddrMaskReps=icmpOutAddrMaskReps, icmpInEchoReps=icmpInEchoReps, ipRouteMetric5=ipRouteMetric5, ipNetToMediaNetAddress=ipNetToMediaNetAddress, ipAddrTable=ipAddrTable, tcpAttemptFails=tcpAttemptFails, icmpInDestUnreachs=icmpInDestUnreachs, ipAdEntIfIndex=ipAdEntIfIndex, egpInErrors=egpInErrors, TtcpInSegs=tcpInSegs, icmpInAddrMaskReps=icmpInAddrMaskReps, egp=egp, icmpInSrcQuenchs=icmpInSrcQuenchs, icmpInTimestamps=icmpInTimestamps, ipOutNoRoutes=ipOutNoRoutes, icmpOutTimestampReps=icmpOutTimestampReps, udpLocalPort=udpLocalPort, ipRouteType=ipRouteType, atIfIndex=atIfIndex, tcpEstabResets=tcpEstabResets, icmpOutTimestamps=icmpOutTimestamps, ipAdEntBcastAddr=ipAdEntBcastAddr, PhysAddress=PhysAddress, mib_2=mib_2, atPhysAddress=atPhysAddress, icmpInAddrMasks=icmpInAddrMasks, ipRouteMask=ipRouteMask, ipInHdrErrors=ipInHdrErrors, egpNeighInMsgs=egpNeighInMsgs, egpNeighAs=egpNeighAs, icmpOutErrors=icmpOutErrors, icmpOutTimeExcds=icmpOutTimeExcds, icmpOutEchoReps=icmpOutEchoReps, icmpOutDestUnreachs=icmpOutDestUnreachs, ipReasmFails=ipReasmFails, egpNeighOutErrMsgs=egpNeighOutErrMsgs, egpNeighEntry=egpNeighEntry, egpNeighTable=egpNeighTable, DisplayString=DisplayString, ipRouteIfIndex=ipRouteIfIndex, tcpRtoMin=tcpRtoMin, icmpInParmProbs=icmpInParmProbs, tcpCurrEstab=tcpCurrEstab, tcpConnLocalPort=tcpConnLocalPort, tcpOutRsts=tcpOutRsts, icmpOutEchos=icmpOutEchos, ipAdEntAddr=ipAdEntAddr, ipRouteInfo=ipRouteInfo, tcpConnRemAddress=tcpConnRemAddress, ipNetToMediaPhysAddress=ipNetToMediaPhysAddress, ipDefaultTTL=ipDefaultTTL, ipInUnknownProtos=ipInUnknownProtos, ipOutDiscards=ipOutDiscards, ipRouteEntry=ipRouteEntry, egpInMsgs=egpInMsgs, egpNeighIntervalHello=egpNeighIntervalHello, ipRouteProto=ipRouteProto, icmpOutMsgs=icmpOutMsgs, egpNeighStateDowns=egpNeighStateDowns, ipRouteAge=ipRouteAge, icmpInErrors=icmpInErrors, tcpConnTable=tcpConnTable, egpNeighInErrMsgs=egpNeighInErrMsgs, ipInAddrErrors=ipInAddrErrors, tcpOutSegs=tcpOutSegs, icmpInTimestampReps=icmpInTimestampReps, tcpConnLocalAddress=tcpConnLocalAddress, udpOutDatagrams=udpOutDatagrams, tcpRtoAlgorithm=tcpRtoAlgorithm, ipFragCreates=ipFragCreates, tcpPassiveOpens=tcpPassiveOpens, ipNetToMediaEntry=ipNetToMediaEntry, ipInReceives=ipInReceives, ipForwDatagrams=ipForwDatagrams, tcpActiveOpens=tcpActiveOpens, ipFragOKs=ipFragOKs, ipAddrEntry=ipAddrEntry, ipRouteDest=ipRouteDest, udpInDatagrams=udpInDatagrams, egpOutErrors=egpOutErrors, ipRouteMetric1=ipRouteMetric1, ipAdEntNetMask=ipAdEntNetMask, tcpConnEntry=tcpConnEntry, tcpConnRemPort=tcpConnRemPort, ipReasmTimeout=ipReasmTimeout, udpInErrors=udpInErrors, udpEntry=udpEntry, egpNeighState=egpNeighState, ipReasmReqds=ipReasmReqds, egpNeighInErrs=egpNeighInErrs, tcpInErrs=tcpInErrs, egpNeighAddr=egpNeighAddr, ipInDelivers=ipInDelivers, udpLocalAddress=udpLocalAddress, icmpOutRedirects=icmpOutRedirects, icmpInRedirects=icmpInRedirects, ipReasmOKs=ipReasmOKs, egpAs=egpAs, egpOutMsgs=egpOutMsgs, ipRouteMetric3=ipRouteMetric3, icmpInMsgs=icmpInMsgs, icmpOutParmProbs=icmpOutParmProbs, ipRouteMetric2=ipRouteMetric2, atTable=atTable, egpNeighEventTrigger=egpNeighEventTrigger, ipNetToMediaType=ipNetToMediaType, icmpOutSrcQuenchs=icmpOutSrcQuenchs, icmpInTimeExcds=icmpInTimeExcds, icmpInEchos=icmpInEchos, egpNeighStateUps=egpNeighStateUps, atNetAddress=atNetAddress, egpNeighOutMsgs=egpNeighOutMsgs, ipRouteTable=ipRouteTable, tcpConnState=tcpConnState, tcpMaxConn=tcpMaxConn, ipForwarding=ipForwarding, atEntry=atEntry, ipRoutingDiscards=ipRoutingDiscards, ipRouteMetric4=ipRouteMetric4, egpNeighIntervalPoll=egpNeighIntervalPoll, ipFragFails=ipFragFails, egpNeighOutErrs=egpNeighOutErrs, at=at, ipInDiscards=ipInDiscards, egpNeighMode=egpNeighMode) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py000066400000000000000000000420311354244100700213160ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-COMMUNITY-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-COMMUNITY-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 13:47:39 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint") SnmpAdminString, SnmpEngineID = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID") snmpTargetAddrEntry, SnmpTagValue = mibBuilder.importSymbols("SNMP-TARGET-MIB", "snmpTargetAddrEntry", "SnmpTagValue") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, ModuleIdentity, TimeTicks, Counter32, Gauge32, Integer32, Counter64, MibIdentifier, IpAddress, snmpModules, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "ModuleIdentity", "TimeTicks", "Counter32", "Gauge32", "Integer32", "Counter64", "MibIdentifier", "IpAddress", "snmpModules", "iso", "ObjectIdentity") DisplayString, RowStatus, StorageType, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "StorageType", "TextualConvention") snmpCommunityMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 18)) if mibBuilder.loadTexts: snmpCommunityMIB.setRevisions(('2003-08-06 00:00', '2000-03-06 00:00',)) if mibBuilder.loadTexts: snmpCommunityMIB.setLastUpdated('200308060000Z') if mibBuilder.loadTexts: snmpCommunityMIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpCommunityMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In msg body: subscribe snmpv3 Co-Chair: Russ Mundy SPARTA, Inc Postal: 7075 Samuel Morse Drive Columbia, MD 21045 USA EMail: mundy@tislabs.com Phone: +1 410-872-1515 Co-Chair: David Harrington Enterasys Networks Postal: 35 Industrial Way P. O. Box 5005 Rochester, New Hampshire 03866-5005 USA EMail: dbh@enterasys.com Phone: +1 603-337-2614 Co-editor: Rob Frye Vibrant Solutions Postal: 2711 Prosperity Ave Fairfax, Virginia 22031 USA E-mail: rfrye@vibrant-1.com Phone: +1-703-270-2000 Co-editor: David B. Levi Nortel Networks Postal: 3505 Kesterwood Drive Knoxville, Tennessee 37918 E-mail: dlevi@nortelnetworks.com Phone: +1 865 686 0432 Co-editor: Shawn A. Routhier Wind River Systems, Inc. Postal: 500 Wind River Way Alameda, CA 94501 E-mail: sar@epilogue.com Phone: +1 510 749 2095 Co-editor: Bert Wijnen Lucent Technologies Postal: Schagen 33 3461 GL Linschoten Netherlands Email: bwijnen@lucent.com Phone: +31-348-407-775 ') if mibBuilder.loadTexts: snmpCommunityMIB.setDescription('This MIB module defines objects to help support coexistence between SNMPv1, SNMPv2c, and SNMPv3. Copyright (C) The Internet Society (2003) This version of this MIB module is part of RFC 3584; see the RFC itself for full legal notices.') snmpCommunityMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 1)) snmpCommunityMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2)) snmpCommunityTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 1), ) if mibBuilder.loadTexts: snmpCommunityTable.setStatus('current') if mibBuilder.loadTexts: snmpCommunityTable.setDescription("The table of community strings configured in the SNMP engine'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.setStatus('current') 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))) if mibBuilder.loadTexts: snmpCommunityIndex.setStatus('current') 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.setStatus('current') if mibBuilder.loadTexts: snmpCommunityName.setDescription('The community string for which a row in this table represents a configuration. There is no SIZE constraint specified for this object because RFC 1157 does not impose any explicit limitation on the length of community strings (their size is constrained indirectly by the SNMP message size).') 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.setStatus('current') if mibBuilder.loadTexts: snmpCommunitySecurityName.setDescription('A human readable string representing the corresponding value of snmpCommunityName in a Security Model independent format.') snmpCommunityContextEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 4), SnmpEngineID()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityContextEngineID.setStatus('current') if mibBuilder.loadTexts: snmpCommunityContextEngineID.setDescription('The contextEngineID indicating the location of the context in which management information is accessed when using the community string specified by the corresponding instance of snmpCommunityName. The default value is the snmpEngineID of the entity in which this object is instantiated.') snmpCommunityContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityContextName.setStatus('current') if mibBuilder.loadTexts: snmpCommunityContextName.setDescription('The context in which management information is accessed when using the community string specified by the corresponding instance of snmpCommunityName.') snmpCommunityTransportTag = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 6), SnmpTagValue().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityTransportTag.setStatus('current') if mibBuilder.loadTexts: snmpCommunityTransportTag.setDescription('This object specifies a set of transport endpoints which are used in two ways: - to specify the transport endpoints from which an SNMP entity will accept management requests, and - to specify the transport endpoints to which a notification may be sent using the community string matching the corresponding instance of snmpCommunityName. In either case, if the value of this object has zero-length, transport endpoints are not checked when either authenticating messages containing this community string, nor when generating notifications. The transports identified by this object are specified in the snmpTargetAddrTable. Entries in that table whose snmpTargetAddrTagList contains this tag value are identified. If a management request containing a community string that matches the corresponding instance of snmpCommunityName is received on a transport endpoint other than the transport endpoints identified by this object the request is deemed unauthentic. When a notification is to be sent using an entry in this table, if the destination transport endpoint of the notification does not match one of the transport endpoints selected by this object, the notification is not sent.') snmpCommunityStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 7), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityStorageType.setStatus('current') if mibBuilder.loadTexts: snmpCommunityStorageType.setDescription("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.") snmpCommunityStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityStatus.setStatus('current') if mibBuilder.loadTexts: snmpCommunityStatus.setDescription('The status of this conceptual row in the snmpCommunityTable. An entry in this table is not qualified for activation until instances of all corresponding columns have been initialized, either through default values, or through Set operations. The snmpCommunityName and snmpCommunitySecurityName objects must be explicitly set. There is no restriction on setting columns in this table when the value of snmpCommunityStatus is active(1).') snmpTargetAddrExtTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 2), ) if mibBuilder.loadTexts: snmpTargetAddrExtTable.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrExtTable.setDescription('The table of mask and maximum message size (mms) values associated with the snmpTargetAddrTable. The snmpTargetAddrExtTable augments the snmpTargetAddrTable with a transport address mask value and a maximum message size value. The transport address mask allows entries in the snmpTargetAddrTable to define a set of addresses instead of just a single address. The maximum message size value allows the maximum message size of another SNMP entity to be configured for use in SNMPv1 (and SNMPv2c) transactions, where the message format does not specify a maximum message size.') snmpTargetAddrExtEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 2, 1), ) snmpTargetAddrEntry.registerAugmentions(("SNMP-COMMUNITY-MIB", "snmpTargetAddrExtEntry")) snmpTargetAddrExtEntry.setIndexNames(*snmpTargetAddrEntry.getIndexNames()) if mibBuilder.loadTexts: snmpTargetAddrExtEntry.setStatus('current') 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(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTMask.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrTMask.setDescription('The mask value associated with an entry in the snmpTargetAddrTable. The value of this object must have the same length as the corresponding instance of snmpTargetAddrTAddress, or must have length 0. An attempt to set it to any other value will result in an inconsistentValue error. The value of this object allows an entry in the snmpTargetAddrTable to specify multiple addresses. The mask value is used to select which bits of a transport address must match bits of the corresponding instance of snmpTargetAddrTAddress, in order for the transport address to match a particular entry in the snmpTargetAddrTable. Bits which are 1 in the mask value indicate bits in the transport address which must match bits in the snmpTargetAddrTAddress value. Bits which are 0 in the mask indicate bits in the transport address which need not match. If the length of the mask is 0, the mask should be treated as if all its bits were 1 and its length were equal to the length of the corresponding value of snmpTargetAddrTable. This object may not be modified while the value of the corresponding instance of snmpTargetAddrRowStatus is active(1). An attempt to set this object in this case will 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrMMS.setDescription('The maximum message size value associated with an entry in the snmpTargetAddrTable. Note that a value of 0 means that the maximum message size is unknown.') snmpTrapAddress = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 3), IpAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: snmpTrapAddress.setStatus('current') if mibBuilder.loadTexts: snmpTrapAddress.setDescription('The value of the agent-addr field of a Trap PDU which is forwarded by a proxy forwarder application using an SNMP version other than SNMPv1. The value of this object SHOULD contain the value of the agent-addr field from the original Trap PDU as generated by an SNMPv1 agent.') snmpTrapCommunity = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 4), OctetString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: snmpTrapCommunity.setStatus('current') if mibBuilder.loadTexts: snmpTrapCommunity.setDescription('The value of the community string field of an SNMPv1 message containing a Trap PDU which is forwarded by a a proxy forwarder application using an SNMP version other than SNMPv1. The value of this object SHOULD contain the value of the community string field from the original SNMPv1 message containing a Trap PDU as generated by an SNMPv1 agent. There is no SIZE constraint specified for this object because RFC 1157 does not impose any explicit limitation on the length of community strings (their size is constrained indirectly by the SNMP message size).') snmpCommunityMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 1)) snmpCommunityMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 2)) snmpCommunityMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 18, 2, 1, 1)).setObjects(("SNMP-COMMUNITY-MIB", "snmpCommunityTableGroup")) if mibBuilder.loadTexts: snmpCommunityMIBCompliance.setDescription('The compliance statement for SNMP engines which implement 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 contain a proxy forwarding application which is capable of forwarding SNMPv1 traps using SNMPv2c or SNMPv3.') snmpCommunityMIBFullCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 18, 2, 1, 3)).setObjects(("SNMP-COMMUNITY-MIB", "snmpCommunityTableGroup")) if mibBuilder.loadTexts: snmpCommunityMIBFullCompliance.setDescription('The compliance statement for SNMP engines which implement the SNMP-COMMUNITY-MIB with full read-create access.') snmpCommunityTableGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 18, 2, 2, 1)).setObjects(("SNMP-COMMUNITY-MIB", "snmpCommunityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunitySecurityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextEngineID"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityTransportTag"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStorageType"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStatus"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrTMask"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrMMS")) if mibBuilder.loadTexts: snmpCommunityTableGroup.setDescription('A collection of objects providing for configuration of 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 when translating traps between SNMP versions. These are used to preserve SNMPv1-specific information when translating to SNMPv2c or SNMPv3.') mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", PYSNMP_MODULE_ID=snmpCommunityMIB, snmpCommunityMIBFullCompliance=snmpCommunityMIBFullCompliance, snmpTargetAddrTMask=snmpTargetAddrTMask, snmpTargetAddrExtEntry=snmpTargetAddrExtEntry, snmpCommunityContextName=snmpCommunityContextName, snmpCommunityMIBConformance=snmpCommunityMIBConformance, snmpCommunityTableGroup=snmpCommunityTableGroup, snmpCommunityIndex=snmpCommunityIndex, snmpTrapCommunity=snmpTrapCommunity, snmpCommunityContextEngineID=snmpCommunityContextEngineID, snmpTrapAddress=snmpTrapAddress, snmpCommunityMIBObjects=snmpCommunityMIBObjects, snmpCommunityMIBCompliances=snmpCommunityMIBCompliances, snmpCommunityStorageType=snmpCommunityStorageType, snmpCommunitySecurityName=snmpCommunitySecurityName, snmpCommunityTable=snmpCommunityTable, snmpCommunityMIBGroups=snmpCommunityMIBGroups, snmpCommunityEntry=snmpCommunityEntry, snmpTargetAddrExtTable=snmpTargetAddrExtTable, snmpCommunityName=snmpCommunityName, snmpCommunityMIBCompliance=snmpCommunityMIBCompliance, snmpCommunityMIB=snmpCommunityMIB, snmpCommunityStatus=snmpCommunityStatus, snmpProxyTrapForwardCompliance=snmpProxyTrapForwardCompliance, snmpProxyTrapForwardGroup=snmpProxyTrapForwardGroup, snmpTargetAddrMMS=snmpTargetAddrMMS, snmpCommunityTransportTag=snmpCommunityTransportTag) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py000066400000000000000000000446201354244100700212750ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-FRAMEWORK-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-FRAMEWORK-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 13:59:41 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # import time try: import os except ImportError: pass OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Gauge32, Unsigned32, MibIdentifier, ObjectIdentity, iso, Counter64, IpAddress, Counter32, ModuleIdentity, Bits, snmpModules, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "MibIdentifier", "ObjectIdentity", "iso", "Counter64", "IpAddress", "Counter32", "ModuleIdentity", "Bits", "snmpModules", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") snmpFrameworkMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 10)) if mibBuilder.loadTexts: snmpFrameworkMIB.setRevisions(('2002-10-14 00:00', '1999-01-19 00:00', '1997-11-20 00:00',)) if mibBuilder.loadTexts: snmpFrameworkMIB.setLastUpdated('200210140000Z') if mibBuilder.loadTexts: snmpFrameworkMIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpFrameworkMIB.setContactInfo('WG-EMail: snmpv3@lists.tislabs.com Subscribe: snmpv3-request@lists.tislabs.com Co-Chair: Russ Mundy Network Associates Laboratories postal: 15204 Omega Drive, Suite 300 Rockville, MD 20850-4601 USA EMail: mundy@tislabs.com phone: +1 301-947-7107 Co-Chair & Co-editor: David Harrington Enterasys Networks postal: 35 Industrial Way P. O. Box 5005 Rochester, New Hampshire 03866-5005 USA EMail: dbh@enterasys.com phone: +1 603-337-2614 Co-editor: Randy Presuhn BMC Software, Inc. postal: 2141 North First Street San Jose, California 95131 USA EMail: randy_presuhn@bmc.com phone: +1 408-546-1006 Co-editor: Bert Wijnen Lucent Technologies postal: Schagen 33 3461 GL Linschoten Netherlands EMail: bwijnen@lucent.com phone: +31 348-680-485 ') if mibBuilder.loadTexts: snmpFrameworkMIB.setDescription('The SNMP Management Architecture MIB Copyright (C) The Internet Society (2002). This version of this MIB module is part of RFC 3411; see the RFC itself for full legal notices. ') # # WARNING: some of the classes below are manually implemented # class SnmpAdminString(TextualConvention, OctetString): description = 'An octet string containing administrative information, preferably in human-readable form. To facilitate internationalization, this information is represented using the ISO/IEC IS 10646-1 character set, encoded as an octet string using the UTF-8 transformation format described in [RFC2279]. Since additional code points are added by amendments to the 10646 standard from time to time, implementations must be prepared to encounter any code point from 0x00000000 to 0x7fffffff. Byte sequences that do not correspond to the valid UTF-8 encoding of a code point or are outside this range are prohibited. The use of control codes should be avoided. When it is necessary to represent a newline, the control code sequence CR LF should be used. The use of leading or trailing white space should be avoided. For code points not directly supported by user interface hardware or software, an alternative means of entry and display, such as hexadecimal, may be provided. For information encoded in 7-bit US-ASCII, the UTF-8 encoding is identical to the US-ASCII encoding. UTF-8 may require multiple bytes to represent a single character / code point; thus the length of this object in octets may be different from the number of characters encoded. Similarly, size constraints refer to the number of encoded octets, not the number of characters represented by an encoding. Note that when this TC is used for an object that is used or envisioned to be used as an index, then a SIZE restriction MUST be specified so that the number of sub-identifiers for any object instance does not exceed the limit of 128, as defined by [RFC3416]. Note that the size of an SnmpAdminString object is measured in octets, not characters. ' status = 'current' displayHint = "255t" subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) encoding = 'utf-8' class SnmpEngineID(TextualConvention, OctetString): description = "An SNMP engine's administratively-unique identifier. Objects of this type are for identification, not for addressing, even though it is possible that an address may have been used in the generation of a specific value. The value for this object may not be all zeros or all 'ff'H or the empty (zero length) string. The initial value for this object may be configured via an operator console entry or via an algorithmic function. In the latter case, the following example algorithm is recommended. In cases where there are multiple engines on the same system, the use of this algorithm is NOT appropriate, as it would result in all of those engines ending up with the same ID value. 1) The very first bit is used to indicate how the rest of the data is composed. 0 - as defined by enterprise using former methods that existed before SNMPv3. See item 2 below. 1 - as defined by this architecture, see item 3 below. Note that this allows existing uses of the engineID (also known as AgentID [RFC1910]) to co-exist with any new uses. 2) The snmpEngineID has a length of 12 octets. The first four octets are set to the binary equivalent of the agent's SNMP management private enterprise number as assigned by the Internet Assigned Numbers Authority (IANA). For example, if Acme Networks has been assigned { enterprises 696 }, the first four octets would be assigned '000002b8'H. The remaining eight octets are determined via one or more enterprise-specific methods. Such methods must be designed so as to maximize the possibility that the value of this object will be unique in the agent's administrative domain. For example, it may be the IP address of the SNMP entity, or the MAC address of one of the interfaces, with each address suitably padded with random octets. If multiple methods are defined, then it is recommended that the first octet indicate the method being used and the remaining octets be a function of the method. 3) The length of the octet string varies. The first four octets are set to the binary equivalent of the agent's SNMP management private enterprise number as assigned by the Internet Assigned Numbers Authority (IANA). For example, if Acme Networks has been assigned { enterprises 696 }, the first four octets would be assigned '000002b8'H. The very first bit is set to 1. For example, the above value for Acme Networks now changes to be '800002b8'H. The fifth octet indicates how the rest (6th and following octets) are formatted. The values for the fifth octet are: 0 - reserved, unused. 1 - IPv4 address (4 octets) lowest non-special IP address 2 - IPv6 address (16 octets) lowest non-special IP address 3 - MAC address (6 octets) lowest IEEE MAC address, canonical order 4 - Text, administratively assigned Maximum remaining length 27 5 - Octets, administratively assigned Maximum remaining length 27 6-127 - reserved, unused 128-255 - as defined by the enterprise Maximum remaining length 27 " status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(5, 32) defaultValue = [128, 0, 79, 184, 5] try: # Attempt to base engine ID on local system name and properties defaultValue += [ord(x) for x in os.uname()[1][:16]] except Exception: pass try: # Attempt to base engine ID on PID defaultValue += [os.getpid() >> 8 & 0xff, os.getpid() & 0xff] except Exception: pass # add pseudo-random text ID defaultValue += [id(defaultValue) >> 8 & 0xff, id(defaultValue) & 0xff] defaultValue = OctetString(defaultValue).asOctets() class SnmpEngineTime(Integer32): def clone(self, *args, **kwargs): if not args: try: args = (time.time() - self,) except Exception: pass return Integer32.clone(self, *args, **kwargs) class SnmpSecurityModel(Integer32, TextualConvention): description = "An identifier that uniquely identifies a Security Model of the Security Subsystem within this SNMP Management Architecture. The values for securityModel are allocated as follows: - The zero value does not identify any particular security model. - Values between 1 and 255, inclusive, are reserved for standards-track Security Models and are managed by the Internet Assigned Numbers Authority (IANA). - Values greater than 255 are allocated to enterprise-specific Security Models. An enterprise-specific securityModel value is defined to be: enterpriseID * 256 + security model within enterprise For example, the fourth Security Model defined by the enterprise whose enterpriseID is 1 would be 259. This scheme for allocation of securityModel values allows for a maximum of 255 standards- based Security Models, and for a maximum of 256 Security Models per enterprise. It is believed that the assignment of new securityModel values will be rare in practice because the larger the number of simultaneously utilized Security Models, the larger the chance that interoperability will suffer. Consequently, it is believed that such a range will be sufficient. In the unlikely event that the standards committee finds this number to be insufficient over time, an enterprise number can be allocated to obtain an additional 256 possible values. Note that the most significant bit must be zero; hence, there are 23 bits allocated for various organizations to design and define non-standard securityModels. This limits the ability to define new proprietary implementations of Security Models to the first 8,388,608 enterprises. It is worthwhile to note that, in its encoded form, the securityModel value will normally require only a single byte since, in practice, the leftmost bits will be zero for most messages and sign extension is suppressed by the encoding rules. As of this writing, there are several values of securityModel defined for use with SNMP or reserved for use with supporting MIB objects. They are as follows: 0 reserved for 'any' 1 reserved for SNMPv1 2 reserved for SNMPv2c 3 User-Based Security Model (USM) " status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647) class SnmpMessageProcessingModel(Integer32, TextualConvention): description = 'An identifier that uniquely identifies a Message Processing Model of the Message Processing Subsystem within this SNMP Management Architecture. The values for messageProcessingModel are allocated as follows: - Values between 0 and 255, inclusive, are reserved for standards-track Message Processing Models and are managed by the Internet Assigned Numbers Authority (IANA). - Values greater than 255 are allocated to enterprise-specific Message Processing Models. An enterprise messageProcessingModel value is defined to be: enterpriseID * 256 + messageProcessingModel within enterprise For example, the fourth Message Processing Model defined by the enterprise whose enterpriseID is 1 would be 259. This scheme for allocating messageProcessingModel values allows for a maximum of 255 standards- based Message Processing Models, and for a maximum of 256 Message Processing Models per enterprise. It is believed that the assignment of new messageProcessingModel values will be rare in practice because the larger the number of simultaneously utilized Message Processing Models, the larger the chance that interoperability will suffer. It is believed that such a range will be sufficient. In the unlikely event that the standards committee finds this number to be insufficient over time, an enterprise number can be allocated to obtain an additional 256 possible values. Note that the most significant bit must be zero; hence, there are 23 bits allocated for various organizations to design and define non-standard messageProcessingModels. This limits the ability to define new proprietary implementations of Message Processing Models to the first 8,388,608 enterprises. It is worthwhile to note that, in its encoded form, the messageProcessingModel value will normally require only a single byte since, in practice, the leftmost bits will be zero for most messages and sign extension is suppressed by the encoding rules. As of this writing, there are several values of messageProcessingModel defined for use with SNMP. They are as follows: 0 reserved for SNMPv1 1 reserved for SNMPv2c 2 reserved for SNMPv2u and SNMPv2* 3 reserved for SNMPv3 ' status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647) class SnmpSecurityLevel(Integer32, TextualConvention): description = 'A Level of Security at which SNMP messages can be sent or with which operations are being processed; in particular, one of: noAuthNoPriv - without authentication and without privacy, authNoPriv - with authentication but without privacy, authPriv - with authentication and with privacy. These three values are ordered such that noAuthNoPriv is less than authNoPriv and authNoPriv is less than authPriv. ' status = 'current' subtypeSpec = Integer32.subtypeSpec + SingleValueConstraint(1, 2, 3, ) namedValues = NamedValues(("noAuthNoPriv", 1), ("authNoPriv", 2), ("authPriv", 3), ) snmpFrameworkAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1)) snmpFrameworkMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 2)) snmpFrameworkMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3)) 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.setStatus('current') if mibBuilder.loadTexts: snmpEngineID.setDescription("An SNMP engine's administratively-unique identifier. This information SHOULD be stored in non-volatile storage so that it remains constant across re-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.setStatus('current') if mibBuilder.loadTexts: snmpEngineBoots.setDescription('The number of times that the SNMP engine has (re-)initialized itself since snmpEngineID was last configured. ') snmpEngineTime = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 3), SnmpEngineTime().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: snmpEngineTime.setStatus('current') if mibBuilder.loadTexts: snmpEngineTime.setDescription("The number of seconds since the value of the snmpEngineBoots object last changed. When incrementing this object's value would cause it to exceed its maximum, snmpEngineBoots is incremented as if a re-initialization had occurred, and this object'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.setStatus('current') if mibBuilder.loadTexts: snmpEngineMaxMessageSize.setDescription('The maximum length in octets of an SNMP message which this SNMP engine can send or receive and process, determined as the minimum of the maximum message size values supported among all of the transports available to and supported by the engine. ') snmpAuthProtocols = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1)) if mibBuilder.loadTexts: snmpAuthProtocols.setStatus('current') if mibBuilder.loadTexts: snmpAuthProtocols.setDescription('Registration point for standards-track authentication protocols used in SNMP Management Frameworks. ') snmpPrivProtocols = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2)) if mibBuilder.loadTexts: snmpPrivProtocols.setStatus('current') if mibBuilder.loadTexts: snmpPrivProtocols.setDescription('Registration point for standards-track privacy protocols used in SNMP Management Frameworks. ') snmpFrameworkMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 1)) snmpFrameworkMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 2)) 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 implement the SNMP Management Framework MIB. ') snmpEngineGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 10, 3, 2, 1)).setObjects(("SNMP-FRAMEWORK-MIB", "snmpEngineID"), ("SNMP-FRAMEWORK-MIB", "snmpEngineBoots"), ("SNMP-FRAMEWORK-MIB", "snmpEngineTime"), ("SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize")) if mibBuilder.loadTexts: snmpEngineGroup.setDescription('A collection of objects for identifying and determining the configuration and current timeliness values of an SNMP engine. ') mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpFrameworkMIBConformance=snmpFrameworkMIBConformance, snmpFrameworkMIB=snmpFrameworkMIB, snmpFrameworkMIBGroups=snmpFrameworkMIBGroups, SnmpEngineID=SnmpEngineID, SnmpSecurityLevel=SnmpSecurityLevel, snmpEngineMaxMessageSize=snmpEngineMaxMessageSize, snmpFrameworkAdmin=snmpFrameworkAdmin, PYSNMP_MODULE_ID=snmpFrameworkMIB, snmpFrameworkMIBObjects=snmpFrameworkMIBObjects, snmpFrameworkMIBCompliances=snmpFrameworkMIBCompliances, snmpAuthProtocols=snmpAuthProtocols, snmpFrameworkMIBCompliance=snmpFrameworkMIBCompliance, snmpEngineTime=snmpEngineTime, snmpPrivProtocols=snmpPrivProtocols, SnmpMessageProcessingModel=SnmpMessageProcessingModel, snmpEngine=snmpEngine, SnmpSecurityModel=SnmpSecurityModel, snmpEngineGroup=snmpEngineGroup, snmpEngineBoots=snmpEngineBoots, SnmpAdminString=SnmpAdminString, snmpEngineID=snmpEngineID) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-MPD-MIB.py000066400000000000000000000133661354244100700203630ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # # PySNMP MIB module SNMP-MPD-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-MPD-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:17:00 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") iso, Counter32, Unsigned32, Gauge32, MibIdentifier, TimeTicks, NotificationType, ObjectIdentity, Bits, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, Counter64, IpAddress, snmpModules = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter32", "Unsigned32", "Gauge32", "MibIdentifier", "TimeTicks", "NotificationType", "ObjectIdentity", "Bits", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "Counter64", "IpAddress", "snmpModules") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") snmpMPDMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 11)) if mibBuilder.loadTexts: snmpMPDMIB.setRevisions(('1999-05-04 16:36', '1997-09-30 00:00',)) if mibBuilder.loadTexts: snmpMPDMIB.setLastUpdated('9905041636Z') if mibBuilder.loadTexts: snmpMPDMIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpMPDMIB.setContactInfo('WG-EMail: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In message body: subscribe snmpv3 Chair: Russ Mundy TIS Labs at Network Associates postal: 3060 Washington Road Glenwood, MD 21738 USA EMail: mundy@tislabs.com phone: +1 301-854-6889 Co-editor: Jeffrey Case SNMP Research, Inc. postal: 3001 Kimberlin Heights Road Knoxville, TN 37920-9716 USA EMail: case@snmp.com phone: +1 423-573-1434 Co-editor Dave Harrington Cabletron Systems, Inc. postal: Post Office Box 5005 MailStop: Durham 35 Industrial Way Rochester, NH 03867-5005 USA EMail: dbh@ctron.com phone: +1 603-337-7357 Co-editor: Randy Presuhn BMC Software, Inc. postal: 965 Stewart Drive Sunnyvale, CA 94086 USA EMail: randy_presuhn@bmc.com phone: +1 408-616-3100 Co-editor: Bert Wijnen IBM T. J. Watson Research postal: Schagen 33 3461 GL Linschoten Netherlands EMail: wijnen@vnet.ibm.com phone: +31 348-432-794 ') if mibBuilder.loadTexts: snmpMPDMIB.setDescription('The MIB for Message Processing and Dispatching') snmpMPDAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 1)) snmpMPDMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2)) snmpMPDMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3)) 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.setStatus('current') if mibBuilder.loadTexts: snmpUnknownSecurityModels.setDescription('The total number of packets received by the SNMP engine which were dropped because they referenced a securityModel that was not known to or supported by the SNMP engine. ') snmpInvalidMsgs = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInvalidMsgs.setStatus('current') if mibBuilder.loadTexts: snmpInvalidMsgs.setDescription('The total number of packets received by the SNMP engine which were dropped because there were invalid or 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.setStatus('current') if mibBuilder.loadTexts: snmpUnknownPDUHandlers.setDescription('The total number of packets received by the SNMP engine which were dropped because the PDU contained in the packet could not be passed to an application responsible for handling the pduType, e.g. no SNMP application had registered for the proper combination of the contextEngineID and the pduType. ') snmpMPDMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 1)) snmpMPDMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 2)) 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 implement the SNMP-MPD-MIB. ') snmpMPDGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 11, 3, 2, 1)).setObjects(("SNMP-MPD-MIB", "snmpUnknownSecurityModels"), ("SNMP-MPD-MIB", "snmpInvalidMsgs"), ("SNMP-MPD-MIB", "snmpUnknownPDUHandlers")) if mibBuilder.loadTexts: snmpMPDGroup.setDescription('A collection of objects providing for remote monitoring of the SNMP Message Processing and Dispatching process. ') mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDMIBGroups=snmpMPDMIBGroups, PYSNMP_MODULE_ID=snmpMPDMIB, snmpMPDMIBConformance=snmpMPDMIBConformance, snmpMPDMIBCompliances=snmpMPDMIBCompliances, snmpUnknownPDUHandlers=snmpUnknownPDUHandlers, snmpMPDGroup=snmpMPDGroup, snmpMPDMIB=snmpMPDMIB, snmpInvalidMsgs=snmpInvalidMsgs, snmpMPDCompliance=snmpMPDCompliance, snmpMPDMIBObjects=snmpMPDMIBObjects, snmpMPDAdmin=snmpMPDAdmin, snmpMPDStats=snmpMPDStats, snmpUnknownSecurityModels=snmpUnknownSecurityModels) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py000066400000000000000000000451231354244100700216250ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-NOTIFICATION-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-NOTIFICATION-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:41:37 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") snmpTargetParamsName, SnmpTagValue = mibBuilder.importSymbols("SNMP-TARGET-MIB", "snmpTargetParamsName", "SnmpTagValue") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") TimeTicks, IpAddress, Integer32, snmpModules, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter32, Gauge32, Unsigned32, MibIdentifier, iso, ModuleIdentity, ObjectIdentity, NotificationType, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "IpAddress", "Integer32", "snmpModules", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter32", "Gauge32", "Unsigned32", "MibIdentifier", "iso", "ModuleIdentity", "ObjectIdentity", "NotificationType", "Counter64") DisplayString, TextualConvention, RowStatus, StorageType = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus", "StorageType") snmpNotificationMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 13)) if mibBuilder.loadTexts: snmpNotificationMIB.setRevisions(('2002-10-14 00:00', '1998-08-04 00:00', '1997-07-14 00:00',)) if mibBuilder.loadTexts: snmpNotificationMIB.setLastUpdated('200210140000Z') if mibBuilder.loadTexts: snmpNotificationMIB.setOrganization('IETF SNMPv3 Working Group') if mibBuilder.loadTexts: snmpNotificationMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In message body: subscribe snmpv3 Co-Chair: Russ Mundy Network Associates Laboratories Postal: 15204 Omega Drive, Suite 300 Rockville, MD 20850-4601 USA EMail: mundy@tislabs.com Phone: +1 301-947-7107 Co-Chair: David Harrington Enterasys Networks Postal: 35 Industrial Way P. O. Box 5004 Rochester, New Hampshire 03866-5005 USA EMail: dbh@enterasys.com Phone: +1 603-337-2614 Co-editor: David B. Levi Nortel Networks Postal: 3505 Kesterwood Drive Knoxville, Tennessee 37918 EMail: dlevi@nortelnetworks.com Phone: +1 865 686 0432 Co-editor: Paul Meyer Secure Computing Corporation Postal: 2675 Long Lake Road Roseville, Minnesota 55113 EMail: paul_meyer@securecomputing.com Phone: +1 651 628 1592 Co-editor: Bob Stewart Retired') if mibBuilder.loadTexts: snmpNotificationMIB.setDescription('This MIB module defines MIB objects which provide mechanisms to remotely configure the parameters used by an SNMP entity for the generation of notifications. Copyright (C) The Internet Society (2002). This version of this MIB module is part of RFC 3413; see the RFC itself for full legal notices. ') snmpNotifyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 1)) snmpNotifyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3)) snmpNotifyTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 1), ) if mibBuilder.loadTexts: snmpNotifyTable.setStatus('current') if mibBuilder.loadTexts: snmpNotifyTable.setDescription('This table is used to select management targets which should receive notifications, as well as the type of notification which 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyEntry.setDescription('An entry in this table selects a set of management targets which should receive notifications, as well as the type of notification which should be sent to each selected management target. Entries in the snmpNotifyTable are created and deleted using the snmpNotifyRowStatus object.') snmpNotifyName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: snmpNotifyName.setStatus('current') if mibBuilder.loadTexts: snmpNotifyName.setDescription('The locally arbitrary, but unique identifier associated with this snmpNotifyEntry.') snmpNotifyTag = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 2), SnmpTagValue()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyTag.setStatus('current') if mibBuilder.loadTexts: snmpNotifyTag.setDescription('This object contains a single tag value which is used to select entries in the snmpTargetAddrTable. Any entry in the snmpTargetAddrTable which contains a tag value which is equal to the value of an instance of this object is selected. If this object contains a value of zero length, no entries are selected.') snmpNotifyType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("trap", 1), ("inform", 2))).clone('trap')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyType.setStatus('current') if mibBuilder.loadTexts: snmpNotifyType.setDescription('This object determines the type of notification to be generated for entries in the snmpTargetAddrTable selected by the corresponding instance of snmpNotifyTag. This value is only used when generating notifications, and is ignored when using the snmpTargetAddrTable for other purposes. If the value of this object is trap(1), then any messages generated for selected rows will contain Unconfirmed-Class PDUs. If the value of this object is inform(2), then any messages generated for selected rows will contain Confirmed-Class PDUs. Note that if an SNMP entity only supports generation of Unconfirmed-Class PDUs (and not Confirmed-Class PDUs), then this object may be read-only.') snmpNotifyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyStorageType.setStatus('current') if mibBuilder.loadTexts: snmpNotifyStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyRowStatus.setDescription('The status of this conceptual row. To create a row in this table, a manager must set this object to either createAndGo(4) or createAndWait(5).') snmpNotifyFilterProfileTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 2), ) if mibBuilder.loadTexts: snmpNotifyFilterProfileTable.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterProfileTable.setDescription('This table is used to associate a notification filter profile 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterProfileEntry.setDescription('An entry in this table indicates the name of the filter profile to be used when generating notifications using the corresponding entry in the snmpTargetParamsTable. Entries in the snmpNotifyFilterProfileTable are created and deleted using the snmpNotifyFilterProfileRowStatus object.') 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterProfileName.setDescription('The name of the filter profile to be used when generating notifications using the corresponding entry in the snmpTargetAddrTable.') snmpNotifyFilterProfileStorType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 2), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterProfileStorType.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterProfileStorType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterProfileRowStatus.setDescription("The status of this conceptual row. To create a row in this table, a manager must set this object to either createAndGo(4) or createAndWait(5). Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the snmpNotifyFilterProfileRowStatus column is 'notReady'. In particular, a newly created row cannot be made active until the corresponding instance of snmpNotifyFilterProfileName has been set.") snmpNotifyFilterTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 3), ) if mibBuilder.loadTexts: snmpNotifyFilterTable.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterTable.setDescription('The table of filter profiles. Filter profiles are used to determine whether particular management targets should receive particular notifications. When a notification is generated, it must be compared with the filters associated with each management target which is configured to receive notifications, in order to determine whether it may be sent to each such management target. A more complete discussion of notification filtering can 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterEntry.setDescription('An element of a filter profile. Entries in the snmpNotifyFilterTable are created and deleted using the snmpNotifyFilterRowStatus object.') snmpNotifyFilterSubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 1), ObjectIdentifier()) if mibBuilder.loadTexts: snmpNotifyFilterSubtree.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterSubtree.setDescription('The MIB subtree which, when combined with the corresponding instance of snmpNotifyFilterMask, defines a family of subtrees which are included in or excluded from the filter profile.') snmpNotifyFilterMask = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16)).clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterMask.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterMask.setDescription("The bit mask which, in combination with the corresponding instance of snmpNotifyFilterSubtree, defines a family of subtrees which are included in or excluded from the filter profile. Each bit of this bit mask corresponds to a sub-identifier of snmpNotifyFilterSubtree, with the most significant bit of the i-th octet of this octet string value (extended if necessary, see below) corresponding to the (8*i - 7)-th sub-identifier, and the least significant bit of the i-th octet of this octet string corresponding to the (8*i)-th sub-identifier, where i is in the range 1 through 16. Each bit of this bit mask specifies whether or not the corresponding sub-identifiers must match when determining if an OBJECT IDENTIFIER matches this family of filter subtrees; a '1' indicates that an exact match must occur; a '0' indicates 'wild card', i.e., any sub-identifier value matches. Thus, the OBJECT IDENTIFIER X of an object instance is contained in a family of filter subtrees if, for each sub-identifier of the value of snmpNotifyFilterSubtree, either: the i-th bit of snmpNotifyFilterMask is 0, or the i-th sub-identifier of X is equal to the i-th sub-identifier of the value of snmpNotifyFilterSubtree. If the value of this bit mask is M bits long and there are more than M sub-identifiers in the corresponding instance of snmpNotifyFilterSubtree, then the bit mask is extended with 1's to be the required length. Note that when the value of this object is the zero-length string, this extension rule results in a mask of all-1's being used (i.e., no 'wild card'), and the family of filter subtrees is the one subtree uniquely identified by the corresponding instance of snmpNotifyFilterSubtree.") snmpNotifyFilterType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("included", 1), ("excluded", 2))).clone('included')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterType.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterType.setDescription('This object indicates whether the family of filter subtrees defined by this entry are included in or excluded from a filter. A more detailed discussion of the use of this object 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: snmpNotifyFilterRowStatus.setDescription('The status of this conceptual row. To create a row in this table, a manager must set this object to either createAndGo(4) or createAndWait(5).') snmpNotifyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 1)) snmpNotifyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 2)) 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 implement only SNMP Unconfirmed-Class notifications and read-create operations on only the snmpTargetAddrTable.') snmpNotifyBasicFiltersCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 2)).setObjects(("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterGroup")) if mibBuilder.loadTexts: snmpNotifyBasicFiltersCompliance.setDescription('The compliance statement for SNMP entities which implement SNMP Unconfirmed-Class notifications with filtering, and read-create operations on all related tables.') snmpNotifyFullCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 3)).setObjects(("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-TARGET-MIB", "snmpTargetResponseGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterGroup")) if mibBuilder.loadTexts: snmpNotifyFullCompliance.setDescription('The compliance statement for SNMP entities which either implement only SNMP Confirmed-Class notifications, or both SNMP Unconfirmed-Class and Confirmed-Class notifications, plus filtering and read-create operations on all related tables.') snmpNotifyGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 1)).setObjects(("SNMP-NOTIFICATION-MIB", "snmpNotifyTag"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyRowStatus")) if mibBuilder.loadTexts: snmpNotifyGroup.setDescription('A collection of objects for selecting which management targets are used for generating notifications, and the type of notification to be generated for each selected management target.') snmpNotifyFilterGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 2)).setObjects(("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileStorType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileRowStatus"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterMask"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterRowStatus")) if mibBuilder.loadTexts: snmpNotifyFilterGroup.setDescription('A collection of objects providing remote configuration of notification filters.') mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", PYSNMP_MODULE_ID=snmpNotificationMIB, snmpNotifyFilterProfileTable=snmpNotifyFilterProfileTable, snmpNotifyTag=snmpNotifyTag, snmpNotifyGroup=snmpNotifyGroup, snmpNotifyFilterProfileRowStatus=snmpNotifyFilterProfileRowStatus, snmpNotifyRowStatus=snmpNotifyRowStatus, snmpNotifyCompliances=snmpNotifyCompliances, snmpNotifyTable=snmpNotifyTable, snmpNotifyType=snmpNotifyType, snmpNotifyStorageType=snmpNotifyStorageType, snmpNotifyConformance=snmpNotifyConformance, snmpNotifyFilterMask=snmpNotifyFilterMask, snmpNotifyFilterProfileName=snmpNotifyFilterProfileName, snmpNotifyEntry=snmpNotifyEntry, snmpNotifyFullCompliance=snmpNotifyFullCompliance, snmpNotifyObjects=snmpNotifyObjects, snmpNotifyFilterEntry=snmpNotifyFilterEntry, snmpNotificationMIB=snmpNotificationMIB, snmpNotifyFilterRowStatus=snmpNotifyFilterRowStatus, snmpNotifyBasicFiltersCompliance=snmpNotifyBasicFiltersCompliance, snmpNotifyFilterGroup=snmpNotifyFilterGroup, snmpNotifyFilterProfileEntry=snmpNotifyFilterProfileEntry, snmpNotifyFilterTable=snmpNotifyFilterTable, snmpNotifyFilterSubtree=snmpNotifyFilterSubtree, snmpNotifyBasicCompliance=snmpNotifyBasicCompliance, snmpNotifyFilterStorageType=snmpNotifyFilterStorageType, snmpNotifyGroups=snmpNotifyGroups, snmpNotifyName=snmpNotifyName, snmpNotifyFilterProfileStorType=snmpNotifyFilterProfileStorType, snmpNotifyFilterType=snmpNotifyFilterType) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-PROXY-MIB.py000066400000000000000000000236261354244100700206640ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-PROXY-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-PROXY-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:43:17 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") SnmpAdminString, SnmpEngineID = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID") SnmpTagValue, = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ModuleIdentity, Counter64, Gauge32, Integer32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, NotificationType, iso, Counter32, ObjectIdentity, IpAddress, TimeTicks, Unsigned32, snmpModules = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter64", "Gauge32", "Integer32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "NotificationType", "iso", "Counter32", "ObjectIdentity", "IpAddress", "TimeTicks", "Unsigned32", "snmpModules") TextualConvention, RowStatus, DisplayString, StorageType = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString", "StorageType") snmpProxyMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 14)) if mibBuilder.loadTexts: snmpProxyMIB.setRevisions(('1998-08-04 00:00', '1997-07-14 00:00',)) if mibBuilder.loadTexts: snmpProxyMIB.setLastUpdated('9808040000Z') if mibBuilder.loadTexts: snmpProxyMIB.setOrganization('IETF SNMPv3 Working Group') if mibBuilder.loadTexts: snmpProxyMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In message body: subscribe snmpv3 Chair: Russ Mundy Trusted Information Systems Postal: 3060 Washington Rd Glenwood MD 21738 USA EMail: mundy@tislabs.com Phone: +1-301-854-6889 Co-editor: David B. Levi SNMP Research, Inc. Postal: 3001 Kimberlin Heights Road Knoxville, TN 37920-9716 EMail: levi@snmp.com Phone: +1 423 573 1434 Co-editor: Paul Meyer Secure Computing Corporation Postal: 2675 Long Lake Road Roseville, MN 55113 EMail: paul_meyer@securecomputing.com Phone: +1 651 628 1592 Co-editor: Bob Stewart Cisco Systems, Inc. Postal: 170 West Tasman Drive San Jose, CA 95134-1706 EMail: bstewart@cisco.com Phone: +1 603 654 2686') if mibBuilder.loadTexts: snmpProxyMIB.setDescription('This MIB module defines MIB objects which provide mechanisms to remotely configure the parameters used by a proxy forwarding application.') snmpProxyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 1)) snmpProxyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3)) snmpProxyTable = MibTable((1, 3, 6, 1, 6, 3, 14, 1, 2), ) if mibBuilder.loadTexts: snmpProxyTable.setStatus('current') if mibBuilder.loadTexts: snmpProxyTable.setDescription('The table of translation parameters used by proxy forwarder applications 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.setStatus('current') if mibBuilder.loadTexts: snmpProxyEntry.setDescription('A set of translation parameters used by a proxy forwarder application for forwarding SNMP messages. Entries in the snmpProxyTable are created and deleted using the snmpProxyRowStatus object.') snmpProxyName = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: snmpProxyName.setStatus('current') if mibBuilder.loadTexts: snmpProxyName.setDescription('The locally arbitrary, but unique identifier associated with this snmpProxyEntry.') snmpProxyType = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("read", 1), ("write", 2), ("trap", 3), ("inform", 4)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyType.setStatus('current') if mibBuilder.loadTexts: snmpProxyType.setDescription('The type of message that may be forwarded using the 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.setStatus('current') if mibBuilder.loadTexts: snmpProxyContextEngineID.setDescription('The contextEngineID contained in messages that may be forwarded using the translation parameters defined by this entry.') snmpProxyContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 4), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyContextName.setStatus('current') if mibBuilder.loadTexts: snmpProxyContextName.setDescription('The contextName contained in messages that may be forwarded using the translation parameters defined by this entry. This object is optional, and if not supported, the contextName contained in a message is ignored when selecting 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.setStatus('current') if mibBuilder.loadTexts: snmpProxyTargetParamsIn.setDescription('This object selects an entry in the snmpTargetParamsTable. The selected entry is used to determine which row of the snmpProxyTable 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.setStatus('current') if mibBuilder.loadTexts: snmpProxySingleTargetOut.setDescription('This object selects a management target defined in the snmpTargetAddrTable (in the SNMP-TARGET-MIB). The selected target is defined by an entry in the snmpTargetAddrTable whose index value (snmpTargetAddrName) is equal to this object. This object is only used when selection of a single target is required (i.e. when forwarding an incoming read or write request).') snmpProxyMultipleTargetOut = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7), SnmpTagValue()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyMultipleTargetOut.setStatus('current') if mibBuilder.loadTexts: snmpProxyMultipleTargetOut.setDescription('This object selects a set of management targets defined in the snmpTargetAddrTable (in the SNMP-TARGET-MIB). This object is only used when selection of multiple targets is required (i.e. when forwarding an incoming notification).') snmpProxyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyStorageType.setStatus('current') if mibBuilder.loadTexts: snmpProxyStorageType.setDescription('The storage type of this conceptual row.') snmpProxyRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyRowStatus.setStatus('current') if mibBuilder.loadTexts: snmpProxyRowStatus.setDescription('The status of this conceptual row. To create a row in this table, a manager must set this object to either createAndGo(4) or createAndWait(5). The following objects may not be modified while the value of this object is active(1): - snmpProxyType - snmpProxyContextEngineID - snmpProxyContextName - snmpProxyTargetParamsIn - snmpProxySingleTargetOut - snmpProxyMultipleTargetOut') snmpProxyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3, 1)) snmpProxyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3, 2)) snmpProxyCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 14, 3, 1, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-TARGET-MIB", "snmpTargetResponseGroup"), ("SNMP-PROXY-MIB", "snmpProxyGroup")) if mibBuilder.loadTexts: snmpProxyCompliance.setDescription('The compliance statement for SNMP entities which include a proxy forwarding application.') snmpProxyGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 14, 3, 2, 3)).setObjects(("SNMP-PROXY-MIB", "snmpProxyType"), ("SNMP-PROXY-MIB", "snmpProxyContextEngineID"), ("SNMP-PROXY-MIB", "snmpProxyContextName"), ("SNMP-PROXY-MIB", "snmpProxyTargetParamsIn"), ("SNMP-PROXY-MIB", "snmpProxySingleTargetOut"), ("SNMP-PROXY-MIB", "snmpProxyMultipleTargetOut"), ("SNMP-PROXY-MIB", "snmpProxyStorageType"), ("SNMP-PROXY-MIB", "snmpProxyRowStatus")) if mibBuilder.loadTexts: snmpProxyGroup.setDescription('A collection of objects providing remote configuration of management target translation parameters for use by proxy forwarder applications.') mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyObjects=snmpProxyObjects, snmpProxyType=snmpProxyType, snmpProxyRowStatus=snmpProxyRowStatus, snmpProxyName=snmpProxyName, snmpProxyGroups=snmpProxyGroups, snmpProxySingleTargetOut=snmpProxySingleTargetOut, snmpProxyGroup=snmpProxyGroup, snmpProxyConformance=snmpProxyConformance, snmpProxyCompliance=snmpProxyCompliance, PYSNMP_MODULE_ID=snmpProxyMIB, snmpProxyContextEngineID=snmpProxyContextEngineID, snmpProxyCompliances=snmpProxyCompliances, snmpProxyStorageType=snmpProxyStorageType, snmpProxyEntry=snmpProxyEntry, snmpProxyTargetParamsIn=snmpProxyTargetParamsIn, snmpProxyContextName=snmpProxyContextName, snmpProxyMultipleTargetOut=snmpProxyMultipleTargetOut, snmpProxyTable=snmpProxyTable, snmpProxyMIB=snmpProxyMIB) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-TARGET-MIB.py000066400000000000000000000603751354244100700207330ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-TARGET-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-TARGET-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:44:13 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint") SnmpAdminString, SnmpSecurityLevel, SnmpMessageProcessingModel, SnmpSecurityModel = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpSecurityLevel", "SnmpMessageProcessingModel", "SnmpSecurityModel") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Counter32, ObjectIdentity, Bits, NotificationType, Unsigned32, IpAddress, Integer32, ModuleIdentity, snmpModules, TimeTicks, Gauge32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Counter32", "ObjectIdentity", "Bits", "NotificationType", "Unsigned32", "IpAddress", "Integer32", "ModuleIdentity", "snmpModules", "TimeTicks", "Gauge32", "Counter64") TimeInterval, RowStatus, TextualConvention, TestAndIncr, TAddress, StorageType, TDomain, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TimeInterval", "RowStatus", "TextualConvention", "TestAndIncr", "TAddress", "StorageType", "TDomain", "DisplayString") snmpTargetMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 12)) if mibBuilder.loadTexts: snmpTargetMIB.setRevisions(('2002-10-14 00:00', '1998-08-04 00:00', '1997-07-14 00:00',)) if mibBuilder.loadTexts: snmpTargetMIB.setLastUpdated('200210140000Z') if mibBuilder.loadTexts: snmpTargetMIB.setOrganization('IETF SNMPv3 Working Group') if mibBuilder.loadTexts: snmpTargetMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In message body: subscribe snmpv3 Co-Chair: Russ Mundy Network Associates Laboratories Postal: 15204 Omega Drive, Suite 300 Rockville, MD 20850-4601 USA EMail: mundy@tislabs.com Phone: +1 301-947-7107 Co-Chair: David Harrington Enterasys Networks Postal: 35 Industrial Way P. O. Box 5004 Rochester, New Hampshire 03866-5005 USA EMail: dbh@enterasys.com Phone: +1 603-337-2614 Co-editor: David B. Levi Nortel Networks Postal: 3505 Kesterwood Drive Knoxville, Tennessee 37918 EMail: dlevi@nortelnetworks.com Phone: +1 865 686 0432 Co-editor: Paul Meyer Secure Computing Corporation Postal: 2675 Long Lake Road Roseville, Minnesota 55113 EMail: paul_meyer@securecomputing.com Phone: +1 651 628 1592 Co-editor: Bob Stewart Retired') if mibBuilder.loadTexts: snmpTargetMIB.setDescription('This MIB module defines MIB objects which provide mechanisms to remotely configure the parameters used by an SNMP entity for the generation of SNMP messages. Copyright (C) The Internet Society (2002). This version of this MIB module is part of RFC 3413; see the RFC itself for full legal notices. ') snmpTargetObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 1)) snmpTargetConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3)) # # WARNING: some of the classes below are manually implemented # class SnmpTagList(TextualConvention, OctetString): description = "An octet string containing a list of tag values. Tag values are preferably in human-readable form. To facilitate internationalization, this information is represented using the ISO/IEC IS 10646-1 character set, encoded as an octet string using the UTF-8 character encoding scheme described in RFC 2279. Since additional code points are added by amendments to the 10646 standard from time to time, implementations must be prepared to encounter any code point from 0x00000000 to 0x7fffffff. The use of control codes should be avoided, except as described below. For code points not directly supported by user interface hardware or software, an alternative means of entry and display, such as hexadecimal, may be provided. For information encoded in 7-bit US-ASCII, the UTF-8 representation is identical to the US-ASCII encoding. An object of this type contains a list of tag values which are used to select a set of entries in a table. A tag value is an arbitrary string of octets, but may not contain a delimiter character. Delimiter characters are defined to be one of the following: - An ASCII space character (0x20). - An ASCII TAB character (0x09). - An ASCII carriage return (CR) character (0x0D). - An ASCII line feed (LF) character (0x0A). Delimiter characters are used to separate tag values in a tag list. Only a single delimiter character may occur between two tag values. A tag value may not have a zero length. These constraints imply certain restrictions on the contents of this object: - There cannot be a leading or trailing delimiter character. - There cannot be multiple adjacent delimiter characters. Some examples of valid tag lists are: - '' -- an empty list - 'acme' -- list of one tag - 'host router bridge' -- list of several tags Note that although a tag value may not have a length of zero, an empty string is still valid. This indicates an empty list (i.e. there are no tag values in the list). The use of the tag list to select table entries is application and MIB specific. Typically, an application will provide one or more tag values, and any entry which contains some combination of these tag values will be selected." status = 'current' displayHint = "255t" subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) encoding = 'utf-8' _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): description = "An octet string containing a tag value. Tag values are preferably in human-readable form. To facilitate internationalization, this information is represented using the ISO/IEC IS 10646-1 character set, encoded as an octet string using the UTF-8 character encoding scheme described in RFC 2279. Since additional code points are added by amendments to the 10646 standard from time to time, implementations must be prepared to encounter any code point from 0x00000000 to 0x7fffffff. The use of control codes should be avoided, and certain control codes are not allowed as described below. For code points not directly supported by user interface hardware or software, an alternative means of entry and display, such as hexadecimal, may be provided. For information encoded in 7-bit US-ASCII, the UTF-8 representation is identical to the US-ASCII encoding. Note that when this TC is used for an object that is used or envisioned to be used as an index, then a SIZE restriction must be specified so that the number of sub-identifiers for any object instance does not exceed the limit of 128, as defined by [RFC1905]. An object of this type contains a single tag value which is used to select a set of entries in a table. A tag value is an arbitrary string of octets, but may not contain a delimiter character. Delimiter characters are defined to be one of the following: - An ASCII space character (0x20). - An ASCII TAB character (0x09). - An ASCII carriage return (CR) character (0x0D). - An ASCII line feed (LF) character (0x0A). Delimiter characters are used to separate tag values in a tag list. An object of this type may only contain a single tag value, and so delimiter characters are not allowed in a value of this type. Note that a tag value of 0 length means that no tag is defined. In other words, a tag value of 0 length would never match anything in a tag list, and would never select any table entries. Some examples of valid tag values are: - 'acme' - 'router' - 'host' The use of a tag value to select table entries is application and MIB specific." status = 'current' displayHint = "255t" subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) encoding = 'utf-8' _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) snmpTargetSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 1), TestAndIncr()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpTargetSpinLock.setStatus('current') if mibBuilder.loadTexts: snmpTargetSpinLock.setDescription('This object is used to facilitate modification of table entries in the SNMP-TARGET-MIB module by multiple managers. In particular, it is useful when modifying the value of the snmpTargetAddrTagList object. The procedure for modifying the snmpTargetAddrTagList object is as follows: 1. Retrieve the value of snmpTargetSpinLock and of snmpTargetAddrTagList. 2. Generate a new value for snmpTargetAddrTagList. 3. Set the value of snmpTargetSpinLock to the retrieved value, and the value of snmpTargetAddrTagList to the new value. If the set fails for the snmpTargetSpinLock object, go back to step 1.') snmpTargetAddrTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 2), ) if mibBuilder.loadTexts: snmpTargetAddrTable.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrTable.setDescription('A table of transport addresses to be used in the generation of SNMP messages.') snmpTargetAddrEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 2, 1), ).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetAddrName")) if mibBuilder.loadTexts: snmpTargetAddrEntry.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrEntry.setDescription('A transport address to be used in the generation of SNMP operations. Entries in the snmpTargetAddrTable are created and deleted using the snmpTargetAddrRowStatus object.') snmpTargetAddrName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: snmpTargetAddrName.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrName.setDescription('The locally arbitrary, but unique identifier associated with this snmpTargetAddrEntry.') snmpTargetAddrTDomain = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 2), TDomain()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTDomain.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrTDomain.setDescription('This object indicates the transport type of the address contained in the snmpTargetAddrTAddress object.') snmpTargetAddrTAddress = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 3), TAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTAddress.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrTAddress.setDescription('This object contains a transport address. The format of this address depends on the value of the snmpTargetAddrTDomain object.') snmpTargetAddrTimeout = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 4), TimeInterval().clone(1500)).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTimeout.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrTimeout.setDescription('This object should reflect the expected maximum round trip time for communicating with the transport address defined by this row. When a message is sent to this address, and a response (if one is expected) is not received within this time period, an implementation may assume that the response will not be delivered. Note that the time interval that an application waits for a response may actually be derived from the value of this object. The method for deriving the actual time interval is implementation dependent. One such method is to derive the expected round trip time based on a particular retransmission algorithm and on the number of timeouts which have occurred. The type of message may also be considered when deriving expected round trip times for retransmissions. For example, if a message is being sent with a securityLevel that indicates both authentication and privacy, the derived value may be increased to compensate for extra processing time spent during 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrRetryCount.setDescription('This object specifies a default number of retries to be attempted when a response is not received for a generated message. An application may provide its own retry count, in which case the value of this object is ignored.') snmpTargetAddrTagList = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 6), SnmpTagList()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTagList.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrTagList.setDescription('This object contains a list of tag values which are used to select target addresses for a particular operation.') 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrParams.setDescription('The value of this object identifies an entry in the snmpTargetParamsTable. The identified entry contains SNMP parameters to be used when generating messages 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetAddrRowStatus.setDescription("The status of this conceptual row. To create a row in this table, a manager must set this object to either createAndGo(4) or createAndWait(5). Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the snmpTargetAddrRowStatus column is 'notReady'. In particular, a newly created row cannot be made active until the corresponding instances of snmpTargetAddrTDomain, snmpTargetAddrTAddress, and snmpTargetAddrParams have all been set. The following objects may not be modified while the value of this object is active(1): - snmpTargetAddrTDomain - snmpTargetAddrTAddress An attempt to set these objects while the value of snmpTargetAddrRowStatus is active(1) will result in an inconsistentValue error.") snmpTargetParamsTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 3), ) if mibBuilder.loadTexts: snmpTargetParamsTable.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsTable.setDescription('A table of SNMP target information to be used in 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsEntry.setDescription('A set of SNMP target information. Entries in the snmpTargetParamsTable are created and deleted using the snmpTargetParamsRowStatus object.') snmpTargetParamsName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: snmpTargetParamsName.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsName.setDescription('The locally arbitrary, but unique identifier associated with this snmpTargetParamsEntry.') snmpTargetParamsMPModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 2), SnmpMessageProcessingModel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsMPModel.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsMPModel.setDescription('The Message Processing Model to be used when generating SNMP 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsSecurityModel.setDescription('The Security Model to be used when generating SNMP messages using this entry. An implementation may choose to return an inconsistentValue error if an attempt is made to set this variable to a value for a security model which the implementation does not support.') snmpTargetParamsSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 4), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsSecurityName.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsSecurityName.setDescription('The securityName which identifies the Principal on whose behalf SNMP messages will be generated using this entry.') snmpTargetParamsSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 5), SnmpSecurityLevel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsSecurityLevel.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsSecurityLevel.setDescription('The Level of Security to be used when generating SNMP 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: snmpTargetParamsRowStatus.setDescription("The status of this conceptual row. To create a row in this table, a manager must set this object to either createAndGo(4) or createAndWait(5). Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the snmpTargetParamsRowStatus column is 'notReady'. In particular, a newly created row cannot be made active until the corresponding snmpTargetParamsMPModel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, and snmpTargetParamsSecurityLevel have all been set. The following objects may not be modified while the value of this object is active(1): - snmpTargetParamsMPModel - snmpTargetParamsSecurityModel - snmpTargetParamsSecurityName - snmpTargetParamsSecurityLevel An attempt to set these objects while the value of snmpTargetParamsRowStatus is active(1) will result in an inconsistentValue error.") snmpUnavailableContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpUnavailableContexts.setStatus('current') if mibBuilder.loadTexts: snmpUnavailableContexts.setDescription('The total number of packets received by the SNMP engine which were dropped because the context contained in the message was unavailable.') snmpUnknownContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpUnknownContexts.setStatus('current') if mibBuilder.loadTexts: snmpUnknownContexts.setDescription('The total number of packets received by the SNMP engine which were dropped because the context contained in the message was unknown.') snmpTargetCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 1)) snmpTargetGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 2)) 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 a command responder application.') snmpTargetBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 1)).setObjects(("SNMP-TARGET-MIB", "snmpTargetSpinLock"), ("SNMP-TARGET-MIB", "snmpTargetAddrTDomain"), ("SNMP-TARGET-MIB", "snmpTargetAddrTAddress"), ("SNMP-TARGET-MIB", "snmpTargetAddrTagList"), ("SNMP-TARGET-MIB", "snmpTargetAddrParams"), ("SNMP-TARGET-MIB", "snmpTargetAddrStorageType"), ("SNMP-TARGET-MIB", "snmpTargetAddrRowStatus"), ("SNMP-TARGET-MIB", "snmpTargetParamsMPModel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityModel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityName"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityLevel"), ("SNMP-TARGET-MIB", "snmpTargetParamsStorageType"), ("SNMP-TARGET-MIB", "snmpTargetParamsRowStatus")) if mibBuilder.loadTexts: snmpTargetBasicGroup.setDescription('A collection of objects providing basic remote configuration of management targets.') snmpTargetResponseGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 2)).setObjects(("SNMP-TARGET-MIB", "snmpTargetAddrTimeout"), ("SNMP-TARGET-MIB", "snmpTargetAddrRetryCount")) if mibBuilder.loadTexts: snmpTargetResponseGroup.setDescription('A collection of objects providing remote configuration of management targets for applications which generate SNMP messages for which a response message would be expected.') 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 applications, used for counting error conditions.') mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetAddrTimeout=snmpTargetAddrTimeout, SnmpTagValue=SnmpTagValue, snmpTargetParamsSecurityModel=snmpTargetParamsSecurityModel, snmpTargetParamsSecurityLevel=snmpTargetParamsSecurityLevel, snmpTargetParamsTable=snmpTargetParamsTable, snmpTargetAddrEntry=snmpTargetAddrEntry, snmpTargetAddrParams=snmpTargetAddrParams, snmpTargetParamsSecurityName=snmpTargetParamsSecurityName, snmpTargetParamsMPModel=snmpTargetParamsMPModel, snmpTargetSpinLock=snmpTargetSpinLock, snmpTargetAddrTAddress=snmpTargetAddrTAddress, snmpTargetResponseGroup=snmpTargetResponseGroup, snmpTargetCompliances=snmpTargetCompliances, snmpTargetMIB=snmpTargetMIB, snmpUnavailableContexts=snmpUnavailableContexts, snmpTargetCommandResponderCompliance=snmpTargetCommandResponderCompliance, snmpTargetParamsEntry=snmpTargetParamsEntry, snmpUnknownContexts=snmpUnknownContexts, snmpTargetParamsName=snmpTargetParamsName, snmpTargetAddrTDomain=snmpTargetAddrTDomain, snmpTargetAddrTable=snmpTargetAddrTable, snmpTargetObjects=snmpTargetObjects, snmpTargetBasicGroup=snmpTargetBasicGroup, snmpTargetAddrRetryCount=snmpTargetAddrRetryCount, snmpTargetAddrTagList=snmpTargetAddrTagList, snmpTargetAddrRowStatus=snmpTargetAddrRowStatus, SnmpTagList=SnmpTagList, snmpTargetParamsStorageType=snmpTargetParamsStorageType, snmpTargetCommandResponderGroup=snmpTargetCommandResponderGroup, snmpTargetConformance=snmpTargetConformance, snmpTargetParamsRowStatus=snmpTargetParamsRowStatus, snmpTargetGroups=snmpTargetGroups, PYSNMP_MODULE_ID=snmpTargetMIB, snmpTargetAddrName=snmpTargetAddrName, snmpTargetAddrStorageType=snmpTargetAddrStorageType) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py000066400000000000000000000075051354244100700223440ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-USER-BASED-SM-3DES-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-USER-BASED-SM-3DES-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:47:21 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection") snmpPrivProtocols, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpPrivProtocols") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, IpAddress, TimeTicks, Integer32, Counter64, NotificationType, MibIdentifier, Unsigned32, ObjectIdentity, snmpModules, ModuleIdentity, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "IpAddress", "TimeTicks", "Integer32", "Counter64", "NotificationType", "MibIdentifier", "Unsigned32", "ObjectIdentity", "snmpModules", "ModuleIdentity", "iso", "Counter32") TextualConvention, AutonomousType, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "AutonomousType", "DisplayString") snmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 15)) if mibBuilder.loadTexts: snmpUsmMIB.setRevisions(('1999-10-06 00:00',)) if mibBuilder.loadTexts: snmpUsmMIB.setLastUpdated('9910060000Z') if mibBuilder.loadTexts: snmpUsmMIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpUsmMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In msg body: subscribe snmpv3 Chair: Russ Mundy NAI Labs postal: 3060 Washington Rd Glenwood MD 21738 USA email: mundy@tislabs.com phone: +1-443-259-2307 Co-editor: David Reeder NAI Labs postal: 3060 Washington Road (Route 97) Glenwood, MD 21738 USA email: dreeder@tislabs.com phone: +1-443-259-2348 Co-editor: Olafur Gudmundsson NAI Labs postal: 3060 Washington Road (Route 97) Glenwood, MD 21738 USA email: ogud@tislabs.com phone: +1-443-259-2389 ') if mibBuilder.loadTexts: snmpUsmMIB.setDescription("Extension to the SNMP User-based Security Model to support Triple-DES EDE in 'Outside' CBC (cipher-block chaining) Mode. ") usm3DESEDEPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 3)) if mibBuilder.loadTexts: usm3DESEDEPrivProtocol.setStatus('current') if mibBuilder.loadTexts: usm3DESEDEPrivProtocol.setDescription('The 3DES-EDE Symmetric Encryption Protocol.') if mibBuilder.loadTexts: usm3DESEDEPrivProtocol.setReference('- Data Encryption Standard, National Institute of Standards and Technology. Federal Information Processing Standard (FIPS) Publication 46-3, (1999, pending approval). Will supersede FIPS Publication 46-2. - Data Encryption Algorithm, American National Standards Institute. ANSI X3.92-1981, (December, 1980). - DES Modes of Operation, National Institute of Standards and Technology. Federal Information Processing Standard (FIPS) Publication 81, (December, 1980). - Data Encryption Algorithm - Modes of Operation, American National Standards Institute. ANSI X3.106-1983, (May 1983). ') mibBuilder.exportSymbols("SNMP-USER-BASED-SM-3DES-MIB", snmpUsmMIB=snmpUsmMIB, PYSNMP_MODULE_ID=snmpUsmMIB, usm3DESEDEPrivProtocol=usm3DESEDEPrivProtocol) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py000066400000000000000000001016771354244100700216550ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-USER-BASED-SM-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-USER-BASED-SM-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:48:12 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion") SnmpAdminString, snmpAuthProtocols, snmpPrivProtocols, SnmpEngineID = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "snmpAuthProtocols", "snmpPrivProtocols", "SnmpEngineID") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Gauge32, iso, Counter32, NotificationType, Bits, Unsigned32, MibIdentifier, Integer32, TimeTicks, IpAddress, ModuleIdentity, snmpModules, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Gauge32", "iso", "Counter32", "NotificationType", "Bits", "Unsigned32", "MibIdentifier", "Integer32", "TimeTicks", "IpAddress", "ModuleIdentity", "snmpModules", "ObjectIdentity") DisplayString, AutonomousType, RowStatus, StorageType, TextualConvention, RowPointer, TestAndIncr = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "AutonomousType", "RowStatus", "StorageType", "TextualConvention", "RowPointer", "TestAndIncr") snmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 15)) if mibBuilder.loadTexts: snmpUsmMIB.setRevisions(('2002-10-16 00:00', '1999-01-20 00:00', '1997-11-20 00:00',)) if mibBuilder.loadTexts: snmpUsmMIB.setLastUpdated('200210160000Z') if mibBuilder.loadTexts: snmpUsmMIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpUsmMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In msg body: subscribe snmpv3 Chair: Russ Mundy Network Associates Laboratories postal: 15204 Omega Drive, Suite 300 Rockville, MD 20850-4601 USA email: mundy@tislabs.com phone: +1 301-947-7107 Co-Chair: David Harrington Enterasys Networks Postal: 35 Industrial Way P. O. Box 5004 Rochester, New Hampshire 03866-5005 USA EMail: dbh@enterasys.com Phone: +1 603-337-2614 Co-editor Uri Blumenthal Lucent Technologies postal: 67 Whippany Rd. Whippany, NJ 07981 USA email: uri@lucent.com phone: +1-973-386-2163 Co-editor: Bert Wijnen Lucent Technologies postal: Schagen 33 3461 GL Linschoten Netherlands email: bwijnen@lucent.com phone: +31-348-480-685 ') if mibBuilder.loadTexts: snmpUsmMIB.setDescription('The management information definitions for the SNMP User-based Security Model. Copyright (C) The Internet Society (2002). This version of this MIB module is part of RFC 3414; see the RFC itself for full legal notices. ') usmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1)) usmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2)) usmNoAuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 1)) if mibBuilder.loadTexts: usmNoAuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmNoAuthProtocol.setDescription('No Authentication Protocol.') usmHMACMD5AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 2)) if mibBuilder.loadTexts: usmHMACMD5AuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmHMACMD5AuthProtocol.setDescription('The HMAC-MD5-96 Digest Authentication Protocol.') if mibBuilder.loadTexts: usmHMACMD5AuthProtocol.setReference('- H. Krawczyk, M. Bellare, R. Canetti HMAC: Keyed-Hashing for Message Authentication, RFC2104, Feb 1997. - Rivest, R., Message Digest Algorithm MD5, RFC1321. ') usmHMACSHAAuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 3)) if mibBuilder.loadTexts: usmHMACSHAAuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmHMACSHAAuthProtocol.setDescription('The HMAC-SHA-96 Digest Authentication Protocol.') if mibBuilder.loadTexts: usmHMACSHAAuthProtocol.setReference('- H. Krawczyk, M. Bellare, R. Canetti, HMAC: Keyed-Hashing for Message Authentication, RFC2104, Feb 1997. - Secure Hash Algorithm. NIST FIPS 180-1. ') usmNoPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 1)) if mibBuilder.loadTexts: usmNoPrivProtocol.setStatus('current') if mibBuilder.loadTexts: usmNoPrivProtocol.setDescription('No Privacy Protocol.') usmDESPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 2)) if mibBuilder.loadTexts: usmDESPrivProtocol.setStatus('current') if mibBuilder.loadTexts: usmDESPrivProtocol.setDescription('The CBC-DES Symmetric Encryption Protocol.') if mibBuilder.loadTexts: usmDESPrivProtocol.setReference('- Data Encryption Standard, National Institute of Standards and Technology. Federal Information Processing Standard (FIPS) Publication 46-1. Supersedes FIPS Publication 46, (January, 1977; reaffirmed January, 1988). - Data Encryption Algorithm, American National Standards Institute. ANSI X3.92-1981, (December, 1980). - DES Modes of Operation, National Institute of Standards and Technology. Federal Information Processing Standard (FIPS) Publication 81, (December, 1980). - Data Encryption Algorithm - Modes of Operation, American National Standards Institute. ANSI X3.106-1983, (May 1983). ') class KeyChange(TextualConvention, OctetString): description = "Every definition of an object with this syntax must identify a protocol P, a secret key K, and a hash algorithm H that produces output of L octets. The object's value is a manager-generated, partially-random value which, when modified, causes the value of the secret key K, to be modified via a one-way function. The value of an instance of this object is the concatenation of two components: first a 'random' component and then a 'delta' component. The lengths of the random and delta components are given by the corresponding value of the protocol P; if P requires K to be a fixed length, the length of both the random and delta components is that fixed length; if P allows the length of K to be variable up to a particular maximum length, the length of the random component is that maximum length and the length of the delta component is any length less than or equal to that maximum length. For example, usmHMACMD5AuthProtocol requires K to be a fixed length of 16 octets and L - of 16 octets. usmHMACSHAAuthProtocol requires K to be a fixed length of 20 octets and L - of 20 octets. Other protocols may define other sizes, as deemed appropriate. When a requester wants to change the old key K to a new key keyNew on a remote entity, the 'random' component is obtained from either a true random generator, or from a pseudorandom generator, and the 'delta' component is computed as follows: - a temporary variable is initialized to the existing value of K; - if the length of the keyNew is greater than L octets, then: - the random component is appended to the value of the temporary variable, and the result is input to the the hash algorithm H to produce a digest value, and the temporary variable is set to this digest value; - the value of the temporary variable is XOR-ed with the first (next) L-octets (16 octets in case of MD5) of the keyNew to produce the first (next) L-octets (16 octets in case of MD5) of the 'delta' component. - the above two steps are repeated until the unused portion of the keyNew component is L octets or less, - the random component is appended to the value of the temporary variable, and the result is input to the hash algorithm H to produce a digest value; - this digest value, truncated if necessary to be the same length as the unused portion of the keyNew, is XOR-ed with the unused portion of the keyNew to produce the (final portion of the) 'delta' component. For example, using MD5 as the hash algorithm H: iterations = (lenOfDelta - 1)/16; /* integer division */ temp = keyOld; for (i = 0; i < iterations; i++) { temp = MD5 (temp || random); delta[i*16 .. (i*16)+15] = temp XOR keyNew[i*16 .. (i*16)+15]; } temp = MD5 (temp || random); delta[i*16 .. lenOfDelta-1] = temp XOR keyNew[i*16 .. lenOfDelta-1]; The 'random' and 'delta' components are then concatenated as described above, and the resulting octet string is sent to the recipient as the new value of an instance of this object. At the receiver side, when an instance of this object is set to a new value, then a new value of K is computed as follows: - a temporary variable is initialized to the existing value of K; - if the length of the delta component is greater than L octets, then: - the random component is appended to the value of the temporary variable, and the result is input to the hash algorithm H to produce a digest value, and the temporary variable is set to this digest value; - the value of the temporary variable is XOR-ed with the first (next) L-octets (16 octets in case of MD5) of the delta component to produce the first (next) L-octets (16 octets in case of MD5) of the new value of K. - the above two steps are repeated until the unused portion of the delta component is L octets or less, - the random component is appended to the value of the temporary variable, and the result is input to the hash algorithm H to produce a digest value; - this digest value, truncated if necessary to be the same length as the unused portion of the delta component, is XOR-ed with the unused portion of the delta component to produce the (final portion of the) new value of K. For example, using MD5 as the hash algorithm H: iterations = (lenOfDelta - 1)/16; /* integer division */ temp = keyOld; for (i = 0; i < iterations; i++) { temp = MD5 (temp || random); keyNew[i*16 .. (i*16)+15] = temp XOR delta[i*16 .. (i*16)+15]; } temp = MD5 (temp || random); keyNew[i*16 .. lenOfDelta-1] = temp XOR delta[i*16 .. lenOfDelta-1]; The value of an object with this syntax, whenever it is retrieved by the management protocol, is always the zero length string. Note that the keyOld and keyNew are the localized keys. Note that it is probably wise that when an SNMP entity sends a SetRequest to change a key, that it keeps a copy of the old key until it has confirmed that the key change actually succeeded. " status = 'current' 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.setStatus('current') if mibBuilder.loadTexts: usmStatsUnsupportedSecLevels.setDescription('The total number of packets received by the SNMP engine which were dropped because they requested a securityLevel that was unknown to the SNMP engine or otherwise unavailable. ') usmStatsNotInTimeWindows = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsNotInTimeWindows.setStatus('current') if mibBuilder.loadTexts: usmStatsNotInTimeWindows.setDescription("The total number of packets received by the SNMP engine which were dropped because they appeared outside 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.setStatus('current') if mibBuilder.loadTexts: usmStatsUnknownUserNames.setDescription('The total number of packets received by the SNMP engine which were dropped because they referenced a user 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.setStatus('current') if mibBuilder.loadTexts: usmStatsUnknownEngineIDs.setDescription('The total number of packets received by the SNMP engine which were dropped because they referenced an snmpEngineID 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.setStatus('current') if mibBuilder.loadTexts: usmStatsWrongDigests.setDescription("The total number of packets received by the SNMP engine which were dropped because they didn't contain the expected digest value. ") usmStatsDecryptionErrors = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsDecryptionErrors.setStatus('current') if mibBuilder.loadTexts: usmStatsDecryptionErrors.setDescription('The total number of packets received by the SNMP engine which were dropped because they could not be decrypted. ') 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.setStatus('current') if mibBuilder.loadTexts: usmUserSpinLock.setDescription('An advisory lock used to allow several cooperating Command Generator Applications to coordinate their use of facilities to alter secrets in the usmUserTable. ') usmUserTable = MibTable((1, 3, 6, 1, 6, 3, 15, 1, 2, 2), ) if mibBuilder.loadTexts: usmUserTable.setStatus('current') if mibBuilder.loadTexts: usmUserTable.setDescription("The table of users configured in the SNMP engine's Local Configuration Datastore (LCD). To create a new user (i.e., to instantiate a new conceptual row in this table), it is recommended to follow this procedure: 1) GET(usmUserSpinLock.0) and save in sValue. 2) SET(usmUserSpinLock.0=sValue, usmUserCloneFrom=templateUser, usmUserStatus=createAndWait) You should use a template user to clone from which has the proper auth/priv protocol defined. If the new user is to use privacy: 3) generate the keyChange value based on the secret privKey of the clone-from user and the secret key to be used for the new user. Let us call this pkcValue. 4) GET(usmUserSpinLock.0) and save in sValue. 5) SET(usmUserSpinLock.0=sValue, usmUserPrivKeyChange=pkcValue usmUserPublic=randomValue1) 6) GET(usmUserPulic) and check it has randomValue1. If not, repeat steps 4-6. If the new user will never use privacy: 7) SET(usmUserPrivProtocol=usmNoPrivProtocol) If the new user is to use authentication: 8) generate the keyChange value based on the secret authKey of the clone-from user and the secret key to be used for the new user. Let us call this akcValue. 9) GET(usmUserSpinLock.0) and save in sValue. 10) SET(usmUserSpinLock.0=sValue, usmUserAuthKeyChange=akcValue usmUserPublic=randomValue2) 11) GET(usmUserPulic) and check it has randomValue2. If not, repeat steps 9-11. If the new user will never use authentication: 12) SET(usmUserAuthProtocol=usmNoAuthProtocol) Finally, activate the new user: 13) SET(usmUserStatus=active) The new user should now be available and ready to be used for SNMPv3 communication. Note however that access to MIB data must be provided via configuration of the SNMP-VIEW-BASED-ACM-MIB. The use of usmUserSpinlock is to avoid conflicts with another SNMP command generator application which may also 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.setStatus('current') if mibBuilder.loadTexts: usmUserEntry.setDescription("A user configured in the SNMP engine's Local Configuration Datastore (LCD) for the User-based Security Model. ") usmUserEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 1), SnmpEngineID()) if mibBuilder.loadTexts: usmUserEngineID.setStatus('current') if mibBuilder.loadTexts: usmUserEngineID.setDescription("An SNMP engine's administratively-unique identifier. In a simple agent, this value is always that agent's own snmpEngineID value. The value can also take the value of the snmpEngineID of a remote SNMP engine with which this user can communicate. ") usmUserName = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: usmUserName.setStatus('current') if mibBuilder.loadTexts: usmUserName.setDescription('A human readable string representing the name of the user. This is the (User-based Security) Model dependent security ID. ') usmUserSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 3), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmUserSecurityName.setStatus('current') if mibBuilder.loadTexts: usmUserSecurityName.setDescription('A human readable string representing the user in Security Model independent format. The default transformation of the User-based Security Model dependent security ID to the securityName and vice versa is the identity function so that the securityName 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.setStatus('current') if mibBuilder.loadTexts: usmUserCloneFrom.setDescription("A pointer to another conceptual row in this usmUserTable. The user in this other conceptual row is called the clone-from user. When a new user is created (i.e., a new conceptual row is instantiated in this table), the privacy and authentication parameters of the new user must be cloned from its clone-from user. These parameters are: - authentication protocol (usmUserAuthProtocol) - privacy protocol (usmUserPrivProtocol) They will be copied regardless of what the current value is. Cloning also causes the initial values of the secret authentication key (authKey) and the secret encryption key (privKey) of the new user to be set to the same values as the corresponding secrets of the clone-from user to allow the KeyChange process to occur as required during user creation. The first time an instance of this object is set by a management operation (either at or after its instantiation), the cloning process is invoked. Subsequent writes are successful but invoke no action to be taken by the receiver. The cloning process fails with an 'inconsistentName' error if the conceptual row representing the clone-from user does not exist or is not in an active state when the cloning process is invoked. When this object is read, the ZeroDotZero OID is 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.setStatus('current') if mibBuilder.loadTexts: usmUserAuthProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be authenticated, and if so, the type of authentication protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of usmUserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the usmNoAuthProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than usmNoAuthProtocol, then an 'inconsistentValue' error must be returned. If a set operation tries to set the value to the usmNoAuthProtocol while the usmUserPrivProtocol value in the same row is not equal to usmNoPrivProtocol, then an 'inconsistentValue' error must be returned. That means that an SNMP command generator application must first ensure that the usmUserPrivProtocol is set to the usmNoPrivProtocol value before it can set the usmUserAuthProtocol value to usmNoAuthProtocol. ") usmUserAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 6), KeyChange().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserAuthKeyChange.setStatus('current') if mibBuilder.loadTexts: usmUserAuthKeyChange.setDescription("An object, which when modified, causes the secret authentication key used for messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, to be modified via a one-way function. The associated protocol is the usmUserAuthProtocol. The associated secret key is the user's secret authentication key (authKey). The associated hash algorithm is the algorithm used by the user's usmUserAuthProtocol. When creating a new user, it is an 'inconsistentName' error for a set operation to refer to this object unless it is previously or concurrently initialized through a set operation on the corresponding instance of usmUserCloneFrom. When the value of the corresponding usmUserAuthProtocol is usmNoAuthProtocol, then a set is successful, but effectively is a no-op. When this object is read, the zero-length (empty) string is returned. The recommended way to do a key change is as follows: 1) GET(usmUserSpinLock.0) and save in sValue. 2) generate the keyChange value based on the old (existing) secret key and the new secret key, let us call this kcValue. If you do the key change on behalf of another user: 3) SET(usmUserSpinLock.0=sValue, usmUserAuthKeyChange=kcValue usmUserPublic=randomValue) If you do the key change for yourself: 4) SET(usmUserSpinLock.0=sValue, usmUserOwnAuthKeyChange=kcValue usmUserPublic=randomValue) If you get a response with error-status of noError, then the SET succeeded and the new key is active. If you do not get a response, then you can issue a GET(usmUserPublic) and check if the value is equal to the randomValue you did send in the SET. If so, then the key change succeeded and the new key is active (probably the response got lost). If not, then the SET request probably never reached the target and so you can start over with the procedure above. ") usmUserOwnAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 7), KeyChange().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserOwnAuthKeyChange.setStatus('current') if mibBuilder.loadTexts: usmUserOwnAuthKeyChange.setDescription("Behaves exactly as usmUserAuthKeyChange, with one notable difference: in order for the set operation to succeed, the usmUserName of the operation requester must match the usmUserName that indexes the row which is targeted by this operation. In addition, the USM security model must be used for this operation. The idea here is that access to this column can be public, since it will only allow a user to change his own secret authentication key (authKey). Note that this can only be done once the row is active. When a set is received and the usmUserName of the requester is not the same as the umsUserName that indexes the row which is targeted by this operation, then a 'noAccess' error must be returned. When a set is received and the security model in use is 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.setStatus('current') if mibBuilder.loadTexts: usmUserPrivProtocol.setDescription("An indication of whether messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, can be protected from disclosure, and if so, the type of privacy protocol which is used. An instance of this object is created concurrently with the creation of any other object instance for the same user (i.e., as part of the processing of the set operation which creates the first object instance in the same conceptual row). If an initial set operation (i.e. at row creation time) tries to set a value for an unknown or unsupported protocol, then a 'wrongValue' error must be returned. The value will be overwritten/set when a set operation is performed on the corresponding instance of usmUserCloneFrom. Once instantiated, the value of such an instance of this object can only be changed via a set operation to the value of the usmNoPrivProtocol. If a set operation tries to change the value of an existing instance of this object to any value other than usmNoPrivProtocol, then an 'inconsistentValue' error must be returned. Note that if any privacy protocol is used, then you must also use an authentication protocol. In other words, if usmUserPrivProtocol is set to anything else than usmNoPrivProtocol, then the corresponding instance of usmUserAuthProtocol cannot have a value of usmNoAuthProtocol. If it does, then an 'inconsistentValue' error must be returned. ") usmUserPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 9), KeyChange().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserPrivKeyChange.setStatus('current') if mibBuilder.loadTexts: usmUserPrivKeyChange.setDescription("An object, which when modified, causes the secret encryption key used for messages sent on behalf of this user to/from the SNMP engine identified by usmUserEngineID, to be modified via a one-way function. The associated protocol is the usmUserPrivProtocol. The associated secret key is the user's secret privacy key (privKey). The associated hash algorithm is the algorithm used by the user's usmUserAuthProtocol. When creating a new user, it is an 'inconsistentName' error for a set operation to refer to this object unless it is previously or concurrently initialized through a set operation on the corresponding instance of usmUserCloneFrom. When the value of the corresponding usmUserPrivProtocol is usmNoPrivProtocol, then a set is successful, but effectively is a no-op. When this object is read, the zero-length (empty) string is returned. See the description clause of usmUserAuthKeyChange for a recommended procedure to do a key change. ") usmUserOwnPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 10), KeyChange().clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserOwnPrivKeyChange.setStatus('current') if mibBuilder.loadTexts: usmUserOwnPrivKeyChange.setDescription("Behaves exactly as usmUserPrivKeyChange, with one notable difference: in order for the Set operation to succeed, the usmUserName of the operation requester must match the usmUserName that indexes the row which is targeted by this operation. In addition, the USM security model must be used for this operation. The idea here is that access to this column can be public, since it will only allow a user to change his own secret privacy key (privKey). Note that this can only be done once the row is active. When a set is received and the usmUserName of the requester is not the same as the umsUserName that indexes the row which is targeted by this operation, then a 'noAccess' error must be returned. When a set is received and the security model in use is 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(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserPublic.setStatus('current') if mibBuilder.loadTexts: usmUserPublic.setDescription("A publicly-readable value which can be written as part of the procedure for changing a user's secret authentication and/or privacy key, and later read to determine whether the change of the secret was effected. ") usmUserStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 12), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserStorageType.setStatus('current') if mibBuilder.loadTexts: usmUserStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' must allow write-access at a minimum to: - usmUserAuthKeyChange, usmUserOwnAuthKeyChange and usmUserPublic for a user who employs authentication, and - usmUserPrivKeyChange, usmUserOwnPrivKeyChange and usmUserPublic for a user who employs privacy. Note that any user who employs authentication or privacy must allow its secret(s) to be updated and thus cannot be 'readOnly'. If an initial set operation tries to set the value to 'readOnly' for a user who employs authentication or privacy, then an 'inconsistentValue' error must be returned. Note that if the value has been previously set (implicit or explicit) to any value, then the rules as defined in the StorageType Textual Convention apply. It is an implementation issue to decide if a SET for a readOnly or permanent row is accepted at all. In some contexts this may make sense, in others it may not. If a SET for a readOnly or permanent row is not accepted at 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.setStatus('current') if mibBuilder.loadTexts: usmUserStatus.setDescription("The status of this conceptual row. Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the usmUserStatus column is 'notReady'. In particular, a newly created row for a user who employs authentication, cannot be made active until the corresponding usmUserCloneFrom and usmUserAuthKeyChange have been set. Further, a newly created row for a user who also employs privacy, cannot be made active until the usmUserPrivKeyChange has been set. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified, except for usmUserOwnAuthKeyChange and usmUserOwnPrivKeyChange. For these 2 objects, the value of usmUserStatus MUST be active. ") usmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 1)) usmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 2)) 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 implement the SNMP-USER-BASED-SM-MIB. ') usmMIBBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 15, 2, 2, 1)).setObjects(("SNMP-USER-BASED-SM-MIB", "usmStatsUnsupportedSecLevels"), ("SNMP-USER-BASED-SM-MIB", "usmStatsNotInTimeWindows"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownUserNames"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownEngineIDs"), ("SNMP-USER-BASED-SM-MIB", "usmStatsWrongDigests"), ("SNMP-USER-BASED-SM-MIB", "usmStatsDecryptionErrors"), ("SNMP-USER-BASED-SM-MIB", "usmUserSpinLock"), ("SNMP-USER-BASED-SM-MIB", "usmUserSecurityName"), ("SNMP-USER-BASED-SM-MIB", "usmUserCloneFrom"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserPublic"), ("SNMP-USER-BASED-SM-MIB", "usmUserStorageType"), ("SNMP-USER-BASED-SM-MIB", "usmUserStatus")) if mibBuilder.loadTexts: usmMIBBasicGroup.setDescription('A collection of objects providing for configuration of an SNMP engine which implements the SNMP User-based Security Model. ') mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmUserStorageType=usmUserStorageType, PYSNMP_MODULE_ID=snmpUsmMIB, usmUserTable=usmUserTable, KeyChange=KeyChange, usmUserStatus=usmUserStatus, usmStatsNotInTimeWindows=usmStatsNotInTimeWindows, usmMIBGroups=usmMIBGroups, usmHMACSHAAuthProtocol=usmHMACSHAAuthProtocol, usmUserPrivKeyChange=usmUserPrivKeyChange, usmUserPublic=usmUserPublic, usmUserAuthProtocol=usmUserAuthProtocol, snmpUsmMIB=snmpUsmMIB, usmNoAuthProtocol=usmNoAuthProtocol, usmUserAuthKeyChange=usmUserAuthKeyChange, usmUserOwnAuthKeyChange=usmUserOwnAuthKeyChange, usmUserPrivProtocol=usmUserPrivProtocol, usmStatsUnknownUserNames=usmStatsUnknownUserNames, usmUserEngineID=usmUserEngineID, usmMIBConformance=usmMIBConformance, usmDESPrivProtocol=usmDESPrivProtocol, usmUser=usmUser, usmMIBCompliance=usmMIBCompliance, usmUserCloneFrom=usmUserCloneFrom, usmUserEntry=usmUserEntry, usmMIBBasicGroup=usmMIBBasicGroup, usmStatsUnsupportedSecLevels=usmStatsUnsupportedSecLevels, usmMIBObjects=usmMIBObjects, usmNoPrivProtocol=usmNoPrivProtocol, usmStatsWrongDigests=usmStatsWrongDigests, usmUserOwnPrivKeyChange=usmUserOwnPrivKeyChange, usmHMACMD5AuthProtocol=usmHMACMD5AuthProtocol, usmUserSecurityName=usmUserSecurityName, usmStatsUnknownEngineIDs=usmStatsUnknownEngineIDs, usmUserSpinLock=usmUserSpinLock, usmStats=usmStats, usmUserName=usmUserName, usmMIBCompliances=usmMIBCompliances, usmStatsDecryptionErrors=usmStatsDecryptionErrors) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py000066400000000000000000000067601354244100700210150ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-USM-AES-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-USM-AES-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:49:58 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection") snmpPrivProtocols, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpPrivProtocols") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, iso, ModuleIdentity, IpAddress, MibIdentifier, Integer32, TimeTicks, snmpModules, Bits, Gauge32, NotificationType, ObjectIdentity, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "iso", "ModuleIdentity", "IpAddress", "MibIdentifier", "Integer32", "TimeTicks", "snmpModules", "Bits", "Gauge32", "NotificationType", "ObjectIdentity", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") snmpUsmAesMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 20)) if mibBuilder.loadTexts: snmpUsmAesMIB.setRevisions(('2004-06-14 00:00',)) if mibBuilder.loadTexts: snmpUsmAesMIB.setLastUpdated('200406140000Z') if mibBuilder.loadTexts: snmpUsmAesMIB.setOrganization('IETF') if mibBuilder.loadTexts: snmpUsmAesMIB.setContactInfo('Uri Blumenthal Lucent Technologies / Bell Labs 67 Whippany Rd. 14D-318 Whippany, NJ 07981, USA 973-386-2163 uri@bell-labs.com Fabio Maino Andiamo Systems, Inc. 375 East Tasman Drive San Jose, CA 95134, USA 408-853-7530 fmaino@andiamo.com Keith McCloghrie Cisco Systems, Inc. 170 West Tasman Drive San Jose, CA 95134-1706, USA 408-526-5260 kzm@cisco.com') if mibBuilder.loadTexts: snmpUsmAesMIB.setDescription("Definitions of Object Identities needed for the use of AES by SNMP's User-based Security Model. Copyright (C) The Internet Society (2004). This version of this MIB module is part of RFC 3826; see the RFC itself for full legal notices. Supplementary information may be available on http://www.ietf.org/copyrights/ianamib.html.") usmAesCfb128Protocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 4)) if mibBuilder.loadTexts: usmAesCfb128Protocol.setStatus('current') if mibBuilder.loadTexts: usmAesCfb128Protocol.setDescription('The CFB128-AES-128 Privacy Protocol.') if mibBuilder.loadTexts: usmAesCfb128Protocol.setReference('- Specification for the ADVANCED ENCRYPTION STANDARD. Federal Information Processing Standard (FIPS) Publication 197. (November 2001). - Dworkin, M., NIST Recommendation for Block Cipher Modes of Operation, Methods and Techniques. NIST Special Publication 800-38A (December 2001). ') mibBuilder.exportSymbols("SNMP-USM-AES-MIB", usmAesCfb128Protocol=usmAesCfb128Protocol, snmpUsmAesMIB=snmpUsmAesMIB, PYSNMP_MODULE_ID=snmpUsmAesMIB) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-USM-HMAC-SHA2-MIB.py000066400000000000000000000133201354244100700215760ustar00rootroot00000000000000# # PySNMP MIB module SNMP-USM-HMAC-SHA2-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-USM-HMAC-SHA2-MIB # Produced by pysmi-0.1.4 at Thu Aug 3 02:14:32 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint") snmpAuthProtocols, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpAuthProtocols") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, ObjectIdentity, TimeTicks, Gauge32, Unsigned32, MibIdentifier, mib_2, iso, ModuleIdentity, NotificationType, IpAddress, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "ObjectIdentity", "TimeTicks", "Gauge32", "Unsigned32", "MibIdentifier", "mib-2", "iso", "ModuleIdentity", "NotificationType", "IpAddress", "Integer32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") snmpUsmHmacSha2MIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 235)) if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setRevisions(('2016-04-18 00:00', '2015-10-14 00:00',)) if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setLastUpdated('201604180000Z') if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setContactInfo('WG email: OPSAWG@ietf.org Subscribe: https://www.ietf.org/mailman/listinfo/opsawg Editor: Johannes Merkle secunet Security Networks Postal: Mergenthaler Allee 77 D-65760 Eschborn Germany Phone: +49 20154543091 Email: johannes.merkle@secunet.com Co-Editor: Manfred Lochter Bundesamt fuer Sicherheit in der Informationstechnik (BSI) Postal: Postfach 200363 D-53133 Bonn Germany Phone: +49 228 9582 5643 Email: manfred.lochter@bsi.bund.de') if mibBuilder.loadTexts: snmpUsmHmacSha2MIB.setDescription("Definitions of Object Identities needed for the use of HMAC-SHA2 Authentication Protocols by SNMP's User-based Security Model. Copyright (c) 2016 IETF Trust and the persons identified as authors of the code. All rights reserved. Redistribution and use in source and binary forms, with or without modification, is permitted pursuant to, and subject to the license terms contained in, the Simplified BSD License set forth in Section 4.c of the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info).") usmHMAC128SHA224AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 4)) if mibBuilder.loadTexts: usmHMAC128SHA224AuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmHMAC128SHA224AuthProtocol.setDescription('The Authentication Protocol usmHMAC128SHA224AuthProtocol uses HMAC-SHA-224 and truncates output to 128 bits.') if mibBuilder.loadTexts: usmHMAC128SHA224AuthProtocol.setReference('- Krawczyk, H., Bellare, M., and R. Canetti, HMAC: Keyed-Hashing for Message Authentication, RFC 2104. - National Institute of Standards and Technology, Secure Hash Standard (SHS), FIPS PUB 180-4, 2012.') usmHMAC192SHA256AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 5)) if mibBuilder.loadTexts: usmHMAC192SHA256AuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmHMAC192SHA256AuthProtocol.setDescription('The Authentication Protocol usmHMAC192SHA256AuthProtocol uses HMAC-SHA-256 and truncates output to 192 bits.') if mibBuilder.loadTexts: usmHMAC192SHA256AuthProtocol.setReference('- Krawczyk, H., Bellare, M., and R. Canetti, HMAC: Keyed-Hashing for Message Authentication, RFC 2104. - National Institute of Standards and Technology, Secure Hash Standard (SHS), FIPS PUB 180-4, 2012.') usmHMAC256SHA384AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 6)) if mibBuilder.loadTexts: usmHMAC256SHA384AuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmHMAC256SHA384AuthProtocol.setDescription('The Authentication Protocol usmHMAC256SHA384AuthProtocol uses HMAC-SHA-384 and truncates output to 256 bits.') if mibBuilder.loadTexts: usmHMAC256SHA384AuthProtocol.setReference('- Krawczyk, H., Bellare, M., and R. Canetti, HMAC: Keyed-Hashing for Message Authentication, RFC 2104. - National Institute of Standards and Technology, Secure Hash Standard (SHS), FIPS PUB 180-4, 2012.') usmHMAC384SHA512AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 7)) if mibBuilder.loadTexts: usmHMAC384SHA512AuthProtocol.setStatus('current') if mibBuilder.loadTexts: usmHMAC384SHA512AuthProtocol.setDescription('The Authentication Protocol usmHMAC384SHA512AuthProtocol uses HMAC-SHA-512 and truncates output to 384 bits.') if mibBuilder.loadTexts: usmHMAC384SHA512AuthProtocol.setReference('- Krawczyk, H., Bellare, M., and R. Canetti, HMAC: Keyed-Hashing for Message Authentication, RFC 2104. - National Institute of Standards and Technology, Secure Hash Standard (SHS), FIPS PUB 180-4, 2012.') mibBuilder.exportSymbols("SNMP-USM-HMAC-SHA2-MIB", usmHMAC256SHA384AuthProtocol=usmHMAC256SHA384AuthProtocol, usmHMAC192SHA256AuthProtocol=usmHMAC192SHA256AuthProtocol, usmHMAC384SHA512AuthProtocol=usmHMAC384SHA512AuthProtocol, PYSNMP_MODULE_ID=snmpUsmHmacSha2MIB, snmpUsmHmacSha2MIB=snmpUsmHmacSha2MIB, usmHMAC128SHA224AuthProtocol=usmHMAC128SHA224AuthProtocol) pysnmp-4.4.12/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py000066400000000000000000000727311354244100700217300ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMP-VIEW-BASED-ACM-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMP-VIEW-BASED-ACM-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:50:37 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint") SnmpAdminString, SnmpSecurityLevel, SnmpSecurityModel = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpSecurityLevel", "SnmpSecurityModel") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") TimeTicks, Gauge32, Bits, snmpModules, IpAddress, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Integer32, ModuleIdentity, NotificationType, MibIdentifier, ObjectIdentity, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Gauge32", "Bits", "snmpModules", "IpAddress", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Integer32", "ModuleIdentity", "NotificationType", "MibIdentifier", "ObjectIdentity", "iso", "Counter32") TestAndIncr, RowStatus, TextualConvention, DisplayString, StorageType = mibBuilder.importSymbols("SNMPv2-TC", "TestAndIncr", "RowStatus", "TextualConvention", "DisplayString", "StorageType") snmpVacmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 16)) if mibBuilder.loadTexts: snmpVacmMIB.setRevisions(('2002-10-16 00:00', '1999-01-20 00:00', '1997-11-20 00:00',)) if mibBuilder.loadTexts: snmpVacmMIB.setLastUpdated('200210160000Z') if mibBuilder.loadTexts: snmpVacmMIB.setOrganization('SNMPv3 Working Group') if mibBuilder.loadTexts: snmpVacmMIB.setContactInfo('WG-email: snmpv3@lists.tislabs.com Subscribe: majordomo@lists.tislabs.com In message body: subscribe snmpv3 Co-Chair: Russ Mundy Network Associates Laboratories postal: 15204 Omega Drive, Suite 300 Rockville, MD 20850-4601 USA email: mundy@tislabs.com phone: +1 301-947-7107 Co-Chair: David Harrington Enterasys Networks Postal: 35 Industrial Way P. O. Box 5004 Rochester, New Hampshire 03866-5005 USA EMail: dbh@enterasys.com Phone: +1 603-337-2614 Co-editor: Bert Wijnen Lucent Technologies postal: Schagen 33 3461 GL Linschoten Netherlands email: bwijnen@lucent.com phone: +31-348-480-685 Co-editor: Randy Presuhn BMC Software, Inc. postal: 2141 North First Street San Jose, CA 95131 USA email: randy_presuhn@bmc.com phone: +1 408-546-1006 Co-editor: Keith McCloghrie Cisco Systems, Inc. postal: 170 West Tasman Drive San Jose, CA 95134-1706 USA email: kzm@cisco.com phone: +1-408-526-5260 ') if mibBuilder.loadTexts: snmpVacmMIB.setDescription('The management information definitions for the View-based Access Control Model for SNMP. Copyright (C) The Internet Society (2002). This version of this MIB module is part of RFC 3415; see the RFC itself for full legal notices. ') vacmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1)) vacmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2)) vacmContextTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 1), ) if mibBuilder.loadTexts: vacmContextTable.setStatus('current') if mibBuilder.loadTexts: vacmContextTable.setDescription('The table of locally available contexts. This table provides information to SNMP Command Generator applications so that they can properly configure the vacmAccessTable to control access to all contexts at the SNMP entity. This table may change dynamically if the SNMP entity allows that contexts are added/deleted dynamically (for instance when its configuration changes). Such changes would happen only if the management instrumentation at that SNMP entity recognizes more (or fewer) contexts. The presence of entries in this table and of entries in the vacmAccessTable are independent. That is, a context identified by an entry in this table is not necessarily referenced by any entries in the vacmAccessTable; and the context(s) referenced by an entry in the vacmAccessTable does not necessarily currently exist and thus need not be identified by an entry in this table. This table must be made accessible via the default context so that Command Responder applications have a standard way of retrieving the information. This table is read-only. It cannot be configured via SNMP. ') vacmContextEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 1, 1), ).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmContextName")) if mibBuilder.loadTexts: vacmContextEntry.setStatus('current') 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.setStatus('current') if mibBuilder.loadTexts: vacmContextName.setDescription('A human readable name identifying a particular context at a particular SNMP entity. The empty contextName (zero length) represents the default context. ') # The RowStatus column is not present in the MIB vacmContextStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 1, 1, 2), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmContextStatus.setStatus('current') if mibBuilder.loadTexts: vacmContextStatus.setDescription("The status of this conceptual row. Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the vacmContextTableStatus column is 'notReady'. In particular, a newly created row cannot be made active until a value has been set for vacmContextName. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ") vacmSecurityToGroupTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 2), ) if mibBuilder.loadTexts: vacmSecurityToGroupTable.setStatus('current') if mibBuilder.loadTexts: vacmSecurityToGroupTable.setDescription('This table maps a combination of securityModel and securityName into a groupName which is used to define an 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.setStatus('current') if mibBuilder.loadTexts: vacmSecurityToGroupEntry.setDescription('An entry in this table maps the combination of a securityModel and securityName into a groupName. ') vacmSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 1), SnmpSecurityModel().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: vacmSecurityModel.setStatus('current') if mibBuilder.loadTexts: vacmSecurityModel.setDescription("The Security Model, by which the vacmSecurityName referenced by this entry is provided. Note, 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))) if mibBuilder.loadTexts: vacmSecurityName.setStatus('current') if mibBuilder.loadTexts: vacmSecurityName.setDescription('The securityName for the principal, represented in a Security Model independent format, which is mapped by this 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.setStatus('current') if mibBuilder.loadTexts: vacmGroupName.setDescription('The name of the group to which this entry (e.g., the combination of securityModel and securityName) belongs. This groupName is used as index into the vacmAccessTable to select an access control policy. However, a value in this table does not imply that an instance 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.setStatus('current') if mibBuilder.loadTexts: vacmSecurityToGroupStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: vacmSecurityToGroupStatus.setDescription("The status of this conceptual row. Until instances of all corresponding columns are appropriately configured, the value of the corresponding instance of the vacmSecurityToGroupStatus column is 'notReady'. In particular, a newly created row cannot be made active until a value has been set for vacmGroupName. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ") vacmAccessTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 4), ) if mibBuilder.loadTexts: vacmAccessTable.setStatus('current') if mibBuilder.loadTexts: vacmAccessTable.setDescription("The table of access rights for groups. Each entry is indexed by a groupName, a contextPrefix, a securityModel and a securityLevel. To determine whether access is allowed, one entry from this table needs to be selected and the proper viewName from that entry must be used for access control checking. To select the proper entry, follow these steps: 1) the set of possible matches is formed by the intersection of the following sets of entries: the set of entries with identical vacmGroupName the union of these two sets: - the set with identical vacmAccessContextPrefix - the set of entries with vacmAccessContextMatch value of 'prefix' and matching vacmAccessContextPrefix intersected with the union of these two sets: - the set of entries with identical vacmSecurityModel - the set of entries with vacmSecurityModel value of 'any' intersected with the set of entries with vacmAccessSecurityLevel value less than or equal to the requested securityLevel 2) if this set has only one member, we're done otherwise, it comes down to deciding how to weight the preferences between ContextPrefixes, SecurityModels, and SecurityLevels as follows: a) if the subset of entries with securityModel matching the securityModel in the message is not empty, then discard the rest. b) if the subset of entries with vacmAccessContextPrefix matching the contextName in the message is not empty, then discard the rest c) discard all entries with ContextPrefixes shorter than the longest one remaining in the set d) select the entry with the highest securityLevel Please note that for securityLevel noAuthNoPriv, all groups are really equivalent since the assumption that the 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.setStatus('current') if mibBuilder.loadTexts: vacmAccessEntry.setDescription('An access right configured in the Local Configuration Datastore (LCD) authorizing access to an SNMP context. Entries in this table can use an instance value for object vacmGroupName even if no entry in table vacmAccessSecurityToGroupTable has a corresponding value for object vacmGroupName. ') vacmAccessContextPrefix = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))) if mibBuilder.loadTexts: vacmAccessContextPrefix.setStatus('current') if mibBuilder.loadTexts: vacmAccessContextPrefix.setDescription("In order to gain the access rights allowed by this conceptual row, a contextName must match exactly (if the value of vacmAccessContextMatch is 'exact') or partially (if the value of vacmAccessContextMatch is 'prefix') to the value of the instance of this object. ") vacmAccessSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 2), SnmpSecurityModel()) if mibBuilder.loadTexts: vacmAccessSecurityModel.setStatus('current') if mibBuilder.loadTexts: vacmAccessSecurityModel.setDescription('In order to gain the access rights allowed by this conceptual row, this securityModel must be in use. ') vacmAccessSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 3), SnmpSecurityLevel()) if mibBuilder.loadTexts: vacmAccessSecurityLevel.setStatus('current') if mibBuilder.loadTexts: vacmAccessSecurityLevel.setDescription('The minimum level of security required in order to gain the access rights allowed by this conceptual row. A securityLevel of noAuthNoPriv is less than authNoPriv which in turn is less than authPriv. If multiple entries are equally indexed except for this vacmAccessSecurityLevel index, then the entry which has the highest value for vacmAccessSecurityLevel is selected. ') vacmAccessContextMatch = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("exact", 1), ("prefix", 2))).clone('exact')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessContextMatch.setStatus('current') if mibBuilder.loadTexts: vacmAccessContextMatch.setDescription('If the value of this object is exact(1), then all rows where the contextName exactly matches vacmAccessContextPrefix are selected. If the value of this object is prefix(2), then all rows where the contextName whose starting octets exactly match vacmAccessContextPrefix are selected. This 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(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessReadViewName.setStatus('current') if mibBuilder.loadTexts: vacmAccessReadViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes read access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ') vacmAccessWriteViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessWriteViewName.setStatus('current') if mibBuilder.loadTexts: vacmAccessWriteViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes write access. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ') vacmAccessNotifyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessNotifyViewName.setStatus('current') if mibBuilder.loadTexts: vacmAccessNotifyViewName.setDescription('The value of an instance of this object identifies the MIB view of the SNMP context to which this conceptual row authorizes access for notifications. The identified MIB view is that one for which the vacmViewTreeFamilyViewName has the same value as the instance of this object; if the value is the empty string or if there is no active MIB view having this value of vacmViewTreeFamilyViewName, then no access is granted. ') vacmAccessStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessStorageType.setStatus('current') if mibBuilder.loadTexts: vacmAccessStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: vacmAccessStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other 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.setStatus('current') if mibBuilder.loadTexts: vacmViewSpinLock.setDescription("An advisory lock used to allow cooperating SNMP Command Generator applications to coordinate their use of the Set operation in creating or modifying views. When creating a new view or altering an existing view, it is important to understand the potential interactions with other uses of the view. The vacmViewSpinLock should be retrieved. The name of the view to be created should be determined to be unique by the SNMP Command Generator application by consulting the vacmViewTreeFamilyTable. Finally, the named view may be created (Set), including the advisory lock. If another SNMP Command Generator application has altered the views in the meantime, then the spin lock's value will have changed, and so this creation will fail because it will specify the wrong value for the spin lock. Since this is an advisory lock, the use of this lock is not enforced. ") vacmViewTreeFamilyTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 5, 2), ) if mibBuilder.loadTexts: vacmViewTreeFamilyTable.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilyTable.setDescription("Locally held information about families of subtrees within MIB views. Each MIB view is defined by two sets of view subtrees: - the included view subtrees, and - the excluded view subtrees. Every such view subtree, both the included and the excluded ones, is defined in this table. To determine if a particular object instance is in a particular MIB view, compare the object instance's OBJECT IDENTIFIER with each of the MIB view's active entries in this table. If none match, then the object instance is not in the MIB view. If one or more match, then the object instance is included in, or excluded from, the MIB view according to the value of vacmViewTreeFamilyType in the entry whose value of vacmViewTreeFamilySubtree has the most sub-identifiers. If multiple entries match and have the same number of sub-identifiers (when wildcarding is specified with the value of vacmViewTreeFamilyMask), then the lexicographically greatest instance of vacmViewTreeFamilyType determines the inclusion or exclusion. An object instance's OBJECT IDENTIFIER X matches an active entry in this table when the number of sub-identifiers in X is at least as many as in the value of vacmViewTreeFamilySubtree for the entry, and each sub-identifier in the value of vacmViewTreeFamilySubtree matches its corresponding sub-identifier in X. Two sub-identifiers match either if the corresponding bit of the value of vacmViewTreeFamilyMask for the entry is zero (the 'wild card' value), or if they are equal. A 'family' of subtrees is the set of subtrees defined by a particular combination of values of vacmViewTreeFamilySubtree and vacmViewTreeFamilyMask. In the case where no 'wild card' is defined in the vacmViewTreeFamilyMask, the family of subtrees reduces to a single subtree. When creating or changing MIB views, an SNMP Command Generator application should utilize the vacmViewSpinLock to try to avoid collisions. See DESCRIPTION clause of vacmViewSpinLock. When creating MIB views, it is strongly advised that first the 'excluded' vacmViewTreeFamilyEntries are created and then the 'included' entries. When deleting MIB views, it is strongly advised that first the 'included' vacmViewTreeFamilyEntries are deleted and then the 'excluded' entries. If a create for an entry for instance-level access control is received and the implementation does not support instance-level granularity, then an inconsistentName 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.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilyEntry.setDescription("Information on a particular family of view subtrees included in or excluded from a particular SNMP context's MIB view. Implementations must not restrict the number of families of view subtrees for a given MIB view, except as dictated by resource constraints on the overall number of entries in the vacmViewTreeFamilyTable. If no conceptual rows exist in this table for a given MIB view (viewName), that view may be thought of as consisting 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))) if mibBuilder.loadTexts: vacmViewTreeFamilyViewName.setStatus('current') 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()) if mibBuilder.loadTexts: vacmViewTreeFamilySubtree.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilySubtree.setDescription('The MIB subtree which when combined with the corresponding instance of vacmViewTreeFamilyMask defines 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(hexValue="")).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmViewTreeFamilyMask.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilyMask.setDescription("The bit mask which, in combination with the corresponding instance of vacmViewTreeFamilySubtree, defines a family of view subtrees. Each bit of this bit mask corresponds to a sub-identifier of vacmViewTreeFamilySubtree, with the most significant bit of the i-th octet of this octet string value (extended if necessary, see below) corresponding to the (8*i - 7)-th sub-identifier, and the least significant bit of the i-th octet of this octet string corresponding to the (8*i)-th sub-identifier, where i is in the range 1 through 16. Each bit of this bit mask specifies whether or not the corresponding sub-identifiers must match when determining if an OBJECT IDENTIFIER is in this family of view subtrees; a '1' indicates that an exact match must occur; a '0' indicates 'wild card', i.e., any sub-identifier value matches. Thus, the OBJECT IDENTIFIER X of an object instance is contained in a family of view subtrees if, for each sub-identifier of the value of vacmViewTreeFamilySubtree, either: the i-th bit of vacmViewTreeFamilyMask is 0, or the i-th sub-identifier of X is equal to the i-th sub-identifier of the value of vacmViewTreeFamilySubtree. If the value of this bit mask is M bits long and there are more than M sub-identifiers in the corresponding instance of vacmViewTreeFamilySubtree, then the bit mask is extended with 1's to be the required length. Note that when the value of this object is the zero-length string, this extension rule results in a mask of all-1's being used (i.e., no 'wild card'), and the family of view subtrees is the one view subtree uniquely identified by the corresponding instance of vacmViewTreeFamilySubtree. Note that masks of length greater than zero length do not need to be supported. In this case this object is made read-only. ") vacmViewTreeFamilyType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("included", 1), ("excluded", 2))).clone('included')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmViewTreeFamilyType.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilyType.setDescription('Indicates whether the corresponding instances of vacmViewTreeFamilySubtree and vacmViewTreeFamilyMask define a family of view subtrees which is included in or 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.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilyStorageType.setDescription("The storage type for this conceptual row. Conceptual rows having the value 'permanent' need not allow 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.setStatus('current') if mibBuilder.loadTexts: vacmViewTreeFamilyStatus.setDescription('The status of this conceptual row. The RowStatus TC [RFC2579] requires that this DESCRIPTION clause states under which circumstances other objects in this row can be modified: The value of this object has no effect on whether other objects in this conceptual row can be modified. ') vacmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 1)) vacmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 2)) 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 implement the SNMP View-based Access Control Model configuration MIB. ') vacmBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 16, 2, 2, 1)).setObjects(("SNMP-VIEW-BASED-ACM-MIB", "vacmContextName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextMatch"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessReadViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessWriteViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessNotifyViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewSpinLock"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyMask"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStatus")) if mibBuilder.loadTexts: vacmBasicGroup.setDescription('A collection of objects providing for remote configuration of an SNMP engine which implements the SNMP View-based Access Control Model. ') mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmSecurityModel=vacmSecurityModel, vacmSecurityToGroupEntry=vacmSecurityToGroupEntry, vacmMIBConformance=vacmMIBConformance, vacmAccessReadViewName=vacmAccessReadViewName, vacmViewTreeFamilyMask=vacmViewTreeFamilyMask, snmpVacmMIB=snmpVacmMIB, vacmViewTreeFamilyType=vacmViewTreeFamilyType, vacmMIBGroups=vacmMIBGroups, vacmAccessContextMatch=vacmAccessContextMatch, vacmAccessNotifyViewName=vacmAccessNotifyViewName, vacmViewSpinLock=vacmViewSpinLock, vacmAccessWriteViewName=vacmAccessWriteViewName, vacmContextTable=vacmContextTable, PYSNMP_MODULE_ID=snmpVacmMIB, vacmViewTreeFamilyViewName=vacmViewTreeFamilyViewName, vacmMIBObjects=vacmMIBObjects, vacmViewTreeFamilyStatus=vacmViewTreeFamilyStatus, vacmSecurityName=vacmSecurityName, vacmGroupName=vacmGroupName, vacmAccessSecurityLevel=vacmAccessSecurityLevel, vacmBasicGroup=vacmBasicGroup, vacmContextName=vacmContextName, vacmContextStatus=vacmContextStatus, vacmSecurityToGroupStatus=vacmSecurityToGroupStatus, vacmAccessEntry=vacmAccessEntry, vacmMIBViews=vacmMIBViews, vacmAccessStorageType=vacmAccessStorageType, vacmMIBCompliances=vacmMIBCompliances, vacmViewTreeFamilyEntry=vacmViewTreeFamilyEntry, vacmViewTreeFamilyTable=vacmViewTreeFamilyTable, vacmSecurityToGroupStorageType=vacmSecurityToGroupStorageType, vacmAccessTable=vacmAccessTable, vacmAccessContextPrefix=vacmAccessContextPrefix, vacmViewTreeFamilyStorageType=vacmViewTreeFamilyStorageType, vacmMIBCompliance=vacmMIBCompliance, vacmAccessSecurityModel=vacmAccessSecurityModel, vacmAccessStatus=vacmAccessStatus, vacmContextEntry=vacmContextEntry, vacmSecurityToGroupTable=vacmSecurityToGroupTable, vacmViewTreeFamilySubtree=vacmViewTreeFamilySubtree) pysnmp-4.4.12/pysnmp/smi/mibs/SNMPv2-CONF.py000066400000000000000000000077461354244100700203400ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMPv2-CONF (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMPv2-CONF # Produced by pysmi-0.1.3 at Tue Apr 18 00:51:39 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # MibNode, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibNode') class ObjectGroup(MibNode): status = 'current' objects = () description = '' def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args, **kwargs): if kwargs.get('append'): self.objects += args else: 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 OBJECTS { %s } DESCRIPTION "%s" """ % (', '.join([x for x in self.getObjects()]), self.getDescription()) class NotificationGroup(MibNode): status = 'current' objects = () description = '' def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args, **kwargs): if kwargs.get('append'): self.objects += args else: 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 NOTIFICATIONS { %s } DESCRIPTION "%s" """ % (', '.join([x for x in self.getObjects()]), self.getDescription()) class ModuleCompliance(MibNode): status = 'current' objects = () description = '' def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args, **kwargs): if kwargs.get('append'): self.objects += args else: 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 OBJECT { %s } DESCRIPTION "%s" """ % (', '.join([x for x in self.getObjects()]), self.getDescription()) class AgentCapabilities(MibNode): status = 'current' description = '' reference = '' productRelease = '' def getStatus(self): return self.status 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 self.reference def setReference(self, v): self.reference = v return self def getProductRelease(self): return self.productRelease def setProductRelease(self, v): self.productRelease = v return self # TODO: implement the rest of properties def asn1Print(self): return """\ AGENT-CAPABILITIES STATUS "%s" PRODUCT-RELEASE "%s" DESCRIPTION "%s" """ % (self.getStatus(), self.getProductRelease(), self.getDescription()) mibBuilder.exportSymbols('SNMPv2-CONF', ObjectGroup=ObjectGroup, NotificationGroup=NotificationGroup, ModuleCompliance=ModuleCompliance, AgentCapabilities=AgentCapabilities) pysnmp-4.4.12/pysnmp/smi/mibs/SNMPv2-MIB.py000066400000000000000000000746331354244100700202210ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMPv2-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMPv2-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 00:52:45 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") mib_2, snmpModules, ModuleIdentity, Counter64, ObjectIdentity, Integer32, NotificationType, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Bits, IpAddress, Gauge32, Unsigned32, TimeTicks, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "mib-2", "snmpModules", "ModuleIdentity", "Counter64", "ObjectIdentity", "Integer32", "NotificationType", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Bits", "IpAddress", "Gauge32", "Unsigned32", "TimeTicks", "MibIdentifier") TextualConvention, TestAndIncr, TimeStamp, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TestAndIncr", "TimeStamp", "DisplayString") snmpMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 1)) if mibBuilder.loadTexts: snmpMIB.setRevisions(('2000-08-09 20:17', '1995-11-09 00:00', '1993-04-01 00:00',)) if mibBuilder.loadTexts: snmpMIB.setLastUpdated('200008092017Z') if mibBuilder.loadTexts: snmpMIB.setOrganization('IETF SNMPv3 Working Group') if mibBuilder.loadTexts: snmpMIB.setContactInfo('WG-EMail: snmpv3@tis.com Subscribe: majordomo@tis.com In message body: subscribe snmpv3 Chair: Russ Mundy TIS Labs at Network Associates postal: 3060 Washington Rd Glenwood MD 21738 USA EMail: mundy@tislabs.com phone: +1 301 854-6889 Editor: Randy Presuhn BMC Software, Inc. postal: 2141 North First Street San Jose, CA 95131 USA EMail: randy_presuhn@bmc.com phone: +1 408 546-1006') if mibBuilder.loadTexts: snmpMIB.setDescription('The MIB module for SNMP entities.') snmpMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1)) 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.setStatus('current') if mibBuilder.loadTexts: sysDescr.setDescription("A textual description of the entity. This value should include the full name and version identification of the system's hardware type, software operating-system, and networking software.") sysObjectID = MibScalar((1, 3, 6, 1, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysObjectID.setStatus('current') if mibBuilder.loadTexts: sysObjectID.setDescription("The vendor's authoritative identification of the network management subsystem contained in the entity. This value is allocated within the SMI enterprises subtree (1.3.6.1.4.1) and provides an easy and unambiguous means for determining `what kind of box' is being managed. For example, if vendor `Flintstones, Inc.' was assigned the subtree 1.3.6.1.4.1.424242, it could assign the identifier 1.3.6.1.4.1.424242.1.1 to its `Fred Router'.") sysUpTime = MibScalar((1, 3, 6, 1, 2, 1, 1, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysUpTime.setStatus('current') if mibBuilder.loadTexts: sysUpTime.setDescription('The time (in hundredths of a second) since the network management portion of the system was last re-initialized.') sysContact = MibScalar((1, 3, 6, 1, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysContact.setStatus('current') if mibBuilder.loadTexts: sysContact.setDescription('The textual identification of the contact person for this managed node, together with information on how to contact this person. If no contact information is known, 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.setStatus('current') if mibBuilder.loadTexts: sysName.setDescription("An administratively-assigned name for this managed node. By convention, this is the node's fully-qualified domain name. If the name is unknown, the value is the 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.setStatus('current') if mibBuilder.loadTexts: sysLocation.setDescription("The physical location of this node (e.g., 'telephone closet, 3rd floor'). If the location is unknown, the value 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.setStatus('current') if mibBuilder.loadTexts: sysServices.setDescription('A value which indicates the set of services that this entity may potentially offer. The value is a sum. This sum initially takes the value zero. Then, for each layer, L, in the range 1 through 7, that this node performs transactions for, 2 raised to (L - 1) is added to the sum. For example, a node which performs only routing functions would have a value of 4 (2^(3-1)). In contrast, a node which is a host offering application services would have a value of 72 (2^(4-1) + 2^(7-1)). Note that in the context of the Internet suite of protocols, values should be calculated accordingly: layer functionality 1 physical (e.g., repeaters) 2 datalink/subnetwork (e.g., bridges) 3 internet (e.g., supports the IP) 4 end-to-end (e.g., supports the TCP) 7 applications (e.g., supports the SMTP) For systems including OSI protocols, layers 5 and 6 may also be counted.') sysORLastChange = MibScalar((1, 3, 6, 1, 2, 1, 1, 8), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORLastChange.setStatus('current') if mibBuilder.loadTexts: sysORLastChange.setDescription('The value of sysUpTime at the time of the most recent change in state or value of any instance of sysORID.') sysORTable = MibTable((1, 3, 6, 1, 2, 1, 1, 9), ) if mibBuilder.loadTexts: sysORTable.setStatus('current') if mibBuilder.loadTexts: sysORTable.setDescription('The (conceptual) table listing the capabilities of the local SNMP application acting as a command responder with respect to various MIB modules. SNMP entities having dynamically-configurable support of MIB modules will have a dynamically-varying number of conceptual rows.') sysOREntry = MibTableRow((1, 3, 6, 1, 2, 1, 1, 9, 1), ).setIndexNames((0, "SNMPv2-MIB", "sysORIndex")) if mibBuilder.loadTexts: sysOREntry.setStatus('current') 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))) if mibBuilder.loadTexts: sysORIndex.setStatus('current') if mibBuilder.loadTexts: sysORIndex.setDescription('The auxiliary variable used for identifying instances of 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.setStatus('current') if mibBuilder.loadTexts: sysORID.setDescription('An authoritative identification of a capabilities statement with respect to various MIB modules supported by the local SNMP application acting as a command responder.') sysORDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORDescr.setStatus('current') if mibBuilder.loadTexts: sysORDescr.setDescription('A textual description of the capabilities identified by the corresponding instance of sysORID.') sysORUpTime = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORUpTime.setStatus('current') if mibBuilder.loadTexts: sysORUpTime.setDescription('The value of sysUpTime at the time this conceptual row 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.setStatus('current') if mibBuilder.loadTexts: snmpInPkts.setDescription('The total number of messages delivered to the SNMP entity from the transport service.') snmpInBadVersions = MibScalar((1, 3, 6, 1, 2, 1, 11, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadVersions.setStatus('current') if mibBuilder.loadTexts: snmpInBadVersions.setDescription('The total number of SNMP messages which were delivered to the SNMP entity and were for an unsupported SNMP version.') snmpInBadCommunityNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadCommunityNames.setStatus('current') if mibBuilder.loadTexts: snmpInBadCommunityNames.setDescription('The total number of community-based SNMP messages (for example, SNMPv1) delivered to the SNMP entity which used an SNMP community name not known to said entity. Also, implementations which authenticate community-based SNMP messages using check(s) in addition to matching the community name (for example, by also checking whether the message originated from a transport address allowed to use a specified community name) MAY include in this value the number of messages which failed the additional check(s). It is strongly RECOMMENDED that the documentation for any security model which is used to authenticate community-based SNMP messages specify the precise conditions that contribute to this value.') snmpInBadCommunityUses = MibScalar((1, 3, 6, 1, 2, 1, 11, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadCommunityUses.setStatus('current') if mibBuilder.loadTexts: snmpInBadCommunityUses.setDescription('The total number of community-based SNMP messages (for example, SNMPv1) delivered to the SNMP entity which represented an SNMP operation that was not allowed for the SNMP community named in the message. The precise conditions under which this counter is incremented (if at all) depend on how the SNMP entity implements its access control mechanism and how its applications interact with that access control mechanism. It is strongly RECOMMENDED that the documentation for any access control mechanism which is used to control access to and visibility of MIB instrumentation specify the precise conditions that contribute to this value.') snmpInASNParseErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInASNParseErrs.setStatus('current') if mibBuilder.loadTexts: snmpInASNParseErrs.setDescription('The total number of ASN.1 or BER errors encountered by the SNMP entity when decoding received SNMP messages.') snmpEnableAuthenTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpEnableAuthenTraps.setStatus('current') if mibBuilder.loadTexts: snmpEnableAuthenTraps.setDescription('Indicates whether the SNMP entity is permitted to generate authenticationFailure traps. The value of this object overrides any configuration information; as such, it provides a means whereby all authenticationFailure traps may be disabled. Note that it is strongly recommended that this object be stored in non-volatile memory so that it remains constant across re-initializations of the network management system.') snmpSilentDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 31), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpSilentDrops.setStatus('current') if mibBuilder.loadTexts: snmpSilentDrops.setDescription('The total number of Confirmed Class PDUs (such as GetRequest-PDUs, GetNextRequest-PDUs, GetBulkRequest-PDUs, SetRequest-PDUs, and InformRequest-PDUs) delivered to the SNMP entity which were silently dropped because the size of a reply containing an alternate Response Class PDU (such as a Response-PDU) with an empty variable-bindings field was greater than either a local constraint or the maximum message size associated with the originator of the request.') snmpProxyDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 32), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpProxyDrops.setStatus('current') if mibBuilder.loadTexts: snmpProxyDrops.setDescription('The total number of Confirmed Class PDUs (such as GetRequest-PDUs, GetNextRequest-PDUs, GetBulkRequest-PDUs, SetRequest-PDUs, and InformRequest-PDUs) delivered to the SNMP entity which were silently dropped because the transmission of the (possibly translated) message to a proxy target failed in a manner (other than a time-out) such that no Response Class PDU (such as a Response-PDU) could be returned.') 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("accessiblefornotify") if mibBuilder.loadTexts: snmpTrapOID.setStatus('current') if mibBuilder.loadTexts: snmpTrapOID.setDescription('The authoritative identification of the notification currently being sent. This variable occurs as the second varbind in every SNMPv2-Trap-PDU and InformRequest-PDU.') snmpTrapEnterprise = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 3), ObjectIdentifier()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: snmpTrapEnterprise.setStatus('current') if mibBuilder.loadTexts: snmpTrapEnterprise.setDescription('The authoritative identification of the enterprise associated with the trap currently being sent. When an SNMP proxy agent is mapping an RFC1157 Trap-PDU into a SNMPv2-Trap-PDU, this variable occurs as the last varbind.') snmpTraps = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5)) coldStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)).setObjects() if mibBuilder.loadTexts: coldStart.setStatus('current') if mibBuilder.loadTexts: coldStart.setDescription('A coldStart trap signifies that the SNMP entity, supporting a notification originator application, is reinitializing itself and that its configuration may have been altered.') warmStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 2)).setObjects() if mibBuilder.loadTexts: warmStart.setStatus('current') if mibBuilder.loadTexts: warmStart.setDescription('A warmStart trap signifies that the SNMP entity, supporting a notification originator application, is reinitializing itself such that its configuration is unaltered.') authenticationFailure = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 5)).setObjects() if mibBuilder.loadTexts: authenticationFailure.setStatus('current') if mibBuilder.loadTexts: authenticationFailure.setDescription('An authenticationFailure trap signifies that the SNMP entity has received a protocol message that is not properly authenticated. While all implementations of SNMP entities MAY be capable of generating this trap, the snmpEnableAuthenTraps object indicates whether this trap will be generated.') 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.setStatus('current') if mibBuilder.loadTexts: snmpSetSerialNo.setDescription('An advisory lock used to allow several cooperating command generator applications to coordinate their use of the SNMP set operation. This object is used for coarse-grain coordination. To achieve fine-grain coordination, one or more similar objects might be defined within each MIB group, as appropriate.') 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)) snmpBasicCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 1, 2, 1, 2)).setObjects(("SNMPv2-MIB", "snmpGroup"), ("SNMPv2-MIB", "snmpSetGroup"), ("SNMPv2-MIB", "systemGroup"), ("SNMPv2-MIB", "snmpBasicNotificationsGroup"), ("SNMPv2-MIB", "snmpCommunityGroup")) if mibBuilder.loadTexts: snmpBasicCompliance.setDescription('The compliance statement for SNMPv2 entities which implement the SNMPv2 MIB. This compliance statement is replaced by snmpBasicComplianceRev2.') snmpBasicComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 6, 3, 1, 2, 1, 3)).setObjects(("SNMPv2-MIB", "snmpGroup"), ("SNMPv2-MIB", "snmpSetGroup"), ("SNMPv2-MIB", "systemGroup"), ("SNMPv2-MIB", "snmpBasicNotificationsGroup"), ("SNMPv2-MIB", "snmpCommunityGroup"), ("SNMPv2-MIB", "snmpWarmStartNotificationGroup")) if mibBuilder.loadTexts: snmpBasicComplianceRev2.setDescription('The compliance statement for SNMP entities which implement this MIB module.') snmpGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 8)).setObjects(("SNMPv2-MIB", "snmpInPkts"), ("SNMPv2-MIB", "snmpInBadVersions"), ("SNMPv2-MIB", "snmpInASNParseErrs"), ("SNMPv2-MIB", "snmpSilentDrops"), ("SNMPv2-MIB", "snmpProxyDrops"), ("SNMPv2-MIB", "snmpEnableAuthenTraps")) if mibBuilder.loadTexts: snmpGroup.setDescription('A collection of objects providing basic instrumentation and 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 of a SNMP entity which supports community-based authentication.') 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 command generator applications to coordinate their use of the set operation.') systemGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 6)).setObjects(("SNMPv2-MIB", "sysDescr"), ("SNMPv2-MIB", "sysObjectID"), ("SNMPv2-MIB", "sysUpTime"), ("SNMPv2-MIB", "sysContact"), ("SNMPv2-MIB", "sysName"), ("SNMPv2-MIB", "sysLocation"), ("SNMPv2-MIB", "sysServices"), ("SNMPv2-MIB", "sysORLastChange"), ("SNMPv2-MIB", "sysORID"), ("SNMPv2-MIB", "sysORUpTime"), ("SNMPv2-MIB", "sysORDescr")) if mibBuilder.loadTexts: systemGroup.setDescription('The system group defines objects which are common to all managed systems.') snmpBasicNotificationsGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 7)).setObjects(("SNMPv2-MIB", "coldStart"), ("SNMPv2-MIB", "authenticationFailure")) if mibBuilder.loadTexts: snmpBasicNotificationsGroup.setDescription('The basic notifications implemented by an SNMP entity supporting command responder applications.') 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 command responder applications, if it is able to reinitialize itself such that its configuration is unaltered.') snmpNotificationGroup = ObjectGroup((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 which support notification originator applications.') snmpOutPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutPkts.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutPkts.setDescription('The total number of SNMP Messages which were passed from the SNMP protocol entity to the transport service.') snmpInTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTooBigs.setStatus('obsolete') if mibBuilder.loadTexts: snmpInTooBigs.setDescription("The total number of SNMP PDUs which were delivered to the SNMP protocol entity and for which the value of the error-status field was `tooBig'.") snmpInNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInNoSuchNames.setStatus('obsolete') if mibBuilder.loadTexts: snmpInNoSuchNames.setDescription("The total number of SNMP PDUs which were delivered to the SNMP protocol entity and for which the value of the error-status field was `noSuchName'.") snmpInBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadValues.setStatus('obsolete') if mibBuilder.loadTexts: snmpInBadValues.setDescription("The total number of SNMP PDUs which were delivered to the SNMP protocol entity and for which the value of the error-status field was `badValue'.") snmpInReadOnlys = MibScalar((1, 3, 6, 1, 2, 1, 11, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInReadOnlys.setStatus('obsolete') if mibBuilder.loadTexts: snmpInReadOnlys.setDescription("The total number valid SNMP PDUs which were delivered to the SNMP protocol entity and for which the value of the error-status field was `readOnly'. It should be noted that it is a protocol error to generate an SNMP PDU which contains the value `readOnly' in the error-status field, as such this object is provided as a means of detecting incorrect implementations of the SNMP.") snmpInGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGenErrs.setStatus('obsolete') if mibBuilder.loadTexts: snmpInGenErrs.setDescription("The total number of SNMP PDUs which were delivered to the SNMP protocol entity and for which the value of the error-status field was `genErr'.") snmpInTotalReqVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTotalReqVars.setStatus('obsolete') if mibBuilder.loadTexts: snmpInTotalReqVars.setDescription('The total number of MIB objects which have been retrieved successfully by the SNMP protocol entity as the result of receiving valid SNMP Get-Request and Get-Next PDUs.') snmpInTotalSetVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTotalSetVars.setStatus('obsolete') if mibBuilder.loadTexts: snmpInTotalSetVars.setDescription('The total number of MIB objects which have been altered successfully by the SNMP protocol entity as the 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.setStatus('obsolete') if mibBuilder.loadTexts: snmpInGetRequests.setDescription('The total number of SNMP Get-Request PDUs which have been accepted and processed by the SNMP protocol entity.') snmpInGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGetNexts.setStatus('obsolete') if mibBuilder.loadTexts: snmpInGetNexts.setDescription('The total number of SNMP Get-Next PDUs which have been accepted and processed by the SNMP protocol entity.') snmpInSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInSetRequests.setStatus('obsolete') if mibBuilder.loadTexts: snmpInSetRequests.setDescription('The total number of SNMP Set-Request PDUs which have been accepted and processed by the SNMP protocol entity.') snmpInGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGetResponses.setStatus('obsolete') if mibBuilder.loadTexts: snmpInGetResponses.setDescription('The total number of SNMP Get-Response PDUs which have been accepted and processed by the SNMP protocol entity.') snmpInTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTraps.setStatus('obsolete') if mibBuilder.loadTexts: snmpInTraps.setDescription('The total number of SNMP Trap PDUs which have been accepted and processed by the SNMP protocol entity.') snmpOutTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutTooBigs.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutTooBigs.setDescription("The total number of SNMP PDUs which were generated by the SNMP protocol entity and for which the value of the error-status field was `tooBig.'") snmpOutNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 21), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutNoSuchNames.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutNoSuchNames.setDescription("The total number of SNMP PDUs which were generated by the SNMP protocol entity and for which the value of the error-status was `noSuchName'.") snmpOutBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 22), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutBadValues.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutBadValues.setDescription("The total number of SNMP PDUs which were generated by the SNMP protocol entity and for which the value of the error-status field was `badValue'.") snmpOutGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 24), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGenErrs.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutGenErrs.setDescription("The total number of SNMP PDUs which were generated by the SNMP protocol entity and for which the value of the error-status field was `genErr'.") snmpOutGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 25), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGetRequests.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutGetRequests.setDescription('The total number of SNMP Get-Request PDUs which have been generated by the SNMP protocol entity.') snmpOutGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 26), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGetNexts.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutGetNexts.setDescription('The total number of SNMP Get-Next PDUs which have been generated by the SNMP protocol entity.') snmpOutSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 27), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutSetRequests.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutSetRequests.setDescription('The total number of SNMP Set-Request PDUs which have been generated by the SNMP protocol entity.') snmpOutGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 28), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGetResponses.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutGetResponses.setDescription('The total number of SNMP Get-Response PDUs which have been generated by the SNMP protocol entity.') snmpOutTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 29), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutTraps.setStatus('obsolete') if mibBuilder.loadTexts: snmpOutTraps.setDescription('The total number of SNMP Trap PDUs which have been generated by the SNMP protocol entity.') snmpObsoleteGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 10)).setObjects(("SNMPv2-MIB", "snmpOutPkts"), ("SNMPv2-MIB", "snmpInTooBigs"), ("SNMPv2-MIB", "snmpInNoSuchNames"), ("SNMPv2-MIB", "snmpInBadValues"), ("SNMPv2-MIB", "snmpInReadOnlys"), ("SNMPv2-MIB", "snmpInGenErrs"), ("SNMPv2-MIB", "snmpInTotalReqVars"), ("SNMPv2-MIB", "snmpInTotalSetVars"), ("SNMPv2-MIB", "snmpInGetRequests"), ("SNMPv2-MIB", "snmpInGetNexts"), ("SNMPv2-MIB", "snmpInSetRequests"), ("SNMPv2-MIB", "snmpInGetResponses"), ("SNMPv2-MIB", "snmpInTraps"), ("SNMPv2-MIB", "snmpOutTooBigs"), ("SNMPv2-MIB", "snmpOutNoSuchNames"), ("SNMPv2-MIB", "snmpOutBadValues"), ("SNMPv2-MIB", "snmpOutGenErrs"), ("SNMPv2-MIB", "snmpOutGetRequests"), ("SNMPv2-MIB", "snmpOutGetNexts"), ("SNMPv2-MIB", "snmpOutSetRequests"), ("SNMPv2-MIB", "snmpOutGetResponses"), ("SNMPv2-MIB", "snmpOutTraps")) if mibBuilder.loadTexts: snmpObsoleteGroup.setDescription('A collection of objects from RFC 1213 made obsolete by this MIB module.') mibBuilder.exportSymbols("SNMPv2-MIB", snmpOutBadValues=snmpOutBadValues, coldStart=coldStart, snmpOutPkts=snmpOutPkts, snmpSilentDrops=snmpSilentDrops, snmpCommunityGroup=snmpCommunityGroup, sysORLastChange=sysORLastChange, sysName=sysName, snmpBasicNotificationsGroup=snmpBasicNotificationsGroup, systemGroup=systemGroup, snmpInNoSuchNames=snmpInNoSuchNames, snmpInTotalSetVars=snmpInTotalSetVars, snmpOutTooBigs=snmpOutTooBigs, snmpInBadCommunityNames=snmpInBadCommunityNames, snmpInASNParseErrs=snmpInASNParseErrs, snmpProxyDrops=snmpProxyDrops, snmpInPkts=snmpInPkts, snmpInSetRequests=snmpInSetRequests, snmpInTraps=snmpInTraps, sysORIndex=sysORIndex, snmpOutGetRequests=snmpOutGetRequests, PYSNMP_MODULE_ID=snmpMIB, snmpMIB=snmpMIB, snmpTrap=snmpTrap, sysOREntry=sysOREntry, snmp=snmp, snmpSet=snmpSet, warmStart=warmStart, snmpOutGetNexts=snmpOutGetNexts, snmpOutGetResponses=snmpOutGetResponses, snmpGroup=snmpGroup, sysLocation=sysLocation, snmpOutSetRequests=snmpOutSetRequests, snmpMIBGroups=snmpMIBGroups, snmpTrapOID=snmpTrapOID, system=system, snmpWarmStartNotificationGroup=snmpWarmStartNotificationGroup, snmpInBadCommunityUses=snmpInBadCommunityUses, snmpBasicComplianceRev2=snmpBasicComplianceRev2, sysContact=sysContact, snmpInGetNexts=snmpInGetNexts, sysORUpTime=sysORUpTime, snmpInGetResponses=snmpInGetResponses, snmpTraps=snmpTraps, snmpInGenErrs=snmpInGenErrs, snmpInReadOnlys=snmpInReadOnlys, snmpMIBCompliances=snmpMIBCompliances, snmpMIBObjects=snmpMIBObjects, snmpOutTraps=snmpOutTraps, snmpEnableAuthenTraps=snmpEnableAuthenTraps, snmpSetSerialNo=snmpSetSerialNo, snmpInTotalReqVars=snmpInTotalReqVars, snmpInBadVersions=snmpInBadVersions, snmpMIBConformance=snmpMIBConformance, sysORTable=sysORTable, sysORID=sysORID, snmpInTooBigs=snmpInTooBigs, sysORDescr=sysORDescr, sysUpTime=sysUpTime, sysDescr=sysDescr, snmpBasicCompliance=snmpBasicCompliance, snmpInGetRequests=snmpInGetRequests, snmpInBadValues=snmpInBadValues, snmpSetGroup=snmpSetGroup, sysServices=sysServices, snmpOutNoSuchNames=snmpOutNoSuchNames, sysObjectID=sysObjectID, authenticationFailure=authenticationFailure, snmpObsoleteGroup=snmpObsoleteGroup, snmpOutGenErrs=snmpOutGenErrs, snmpTrapEnterprise=snmpTrapEnterprise, snmpNotificationGroup=snmpNotificationGroup) pysnmp-4.4.12/pysnmp/smi/mibs/SNMPv2-SMI.py000066400000000000000000001334061354244100700202340ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys import traceback from pysnmp.smi.indices import OidOrderedDict from pysnmp.smi import exval, error from pysnmp.proto import rfc1902 from pysnmp import cache, debug from pyasn1.type import univ 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(object): 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): status = 'current' lastUpdated = '' organization = '' contactInfo = '' description = '' revisions = () revisionsDescriptions = () def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getLastUpdated(self): return self.lastUpdated def setLastUpdated(self, v): self.lastUpdated = v return self def getOrganization(self): return self.organization def setOrganization(self, v): self.organization = v return self def getContactInfo(self): return self.contactInfo def setContactInfo(self, v): self.contactInfo = v return self def getDescription(self): return self.description def setDescription(self, v): self.description = v return self def getRevisions(self): return self.revisions def setRevisions(self, args): self.revisions = args return self def getRevisionsDescriptions(self): return self.revisionsDescriptions def setRevisionsDescriptions(self, args): self.revisionsDescriptions = args return self def asn1Print(self): return """\ MODULE-IDENTITY LAST-UPDATED %s ORGANIZATION "%s" CONTACT-INFO "%s" DESCRIPTION "%s" %s""" % (self.getLastUpdated(), self.getOrganization(), self.getContactInfo(), self.getDescription(), ''.join(['REVISION "%s"\n' % x for x in self.getRevisions()])) class ObjectIdentity(MibNode): status = 'current' description = '' reference = '' def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getDescription(self): return self.description def setDescription(self, v): self.description = v return self def getReference(self): return self.reference def setReference(self, v): self.reference = v return self def asn1Print(self): return """\ OBJECT-IDENTITY STATUS %s DESCRIPTION "%s" REFERENCE "%s" """ % (self.getStatus(), self.getDescription(), self.getReference()) # definition for objects class NotificationType(MibNode): objects = () status = 'current' description = '' reference = '' # retained for compatibility revisions = () def getObjects(self): return self.objects def setObjects(self, *args, **kwargs): if kwargs.get('append'): self.objects += args else: self.objects = args return self def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getDescription(self): return self.description def setDescription(self, v): self.description = v return self def getReference(self): return self.reference def setReference(self, v): self.reference = v return self # This should not be here. Retained for compatibility. def getRevisions(self): return self.revisions def setRevisions(self, v): self.revisions = v return self def asn1Print(self): return """\ NOTIFICATION-TYPE OBJECTS { %s } STATUS %s DESCRIPTION "%s" REFERENCE "%s" """ % (', '.join([x for x in self.getObjects()]), self.getStatus(), self.getDescription(), self.getReference()) class MibIdentifier(MibNode): @staticmethod def asn1Print(): return 'OBJECT IDENTIFIER' class ObjectType(MibNode): units = '' maxAccess = 'not-accessible' status = 'current' description = '' reference = '' 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 setSyntax(self, v): self.syntax = v return self def getUnits(self): return self.units def setUnits(self, v): self.units = v return self def getMaxAccess(self): return self.maxAccess def setMaxAccess(self, v): self.maxAccess = v return self def getStatus(self): return self.status def setStatus(self, v): self.status = v return self def getDescription(self): return self.description def setDescription(self, v): self.description = v return self def getReference(self): return self.reference def setReference(self, v): self.reference = v return self def asn1Print(self): return """ OBJECT-TYPE SYNTAX %s UNITS "%s" MAX-ACCESS %s STATUS %s DESCRIPTION "%s" REFERENCE "%s" """ % (self.getSyntax().__class__.__name__, self.getUnits(), self.getMaxAccess(), self.getStatus(), self.getDescription(), self.getReference()) class MibTree(ObjectType): branchVersionId = 0 # cnanges on tree structure change maxAccess = 'not-accessible' def __init__(self, name, syntax=None): ObjectType.__init__(self, name, syntax) self._vars = OidOrderedDict() # Subtrees registration def registerSubtrees(self, *subTrees): self.branchVersionId += 1 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 def unregisterSubtrees(self, *names): self.branchVersionId += 1 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] # # Tree traversal # # Missing branches are indicated by the NoSuchObjectError exception. # Although subtrees may indicate their missing branches by the # NoSuchInstanceError exception. # 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 getNextBranch(self, name, idx=None): # Start from the beginning if self._vars: first = list(self._vars.keys())[0] else: first = () if self._vars and name < first: return self._vars[first] else: try: return self._vars[self._vars.nextKey(name)] except KeyError: raise error.NoSuchObjectError(idx=idx, name=name) 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.NoSuchInstanceError, error.NoSuchObjectError): return self.getNextBranch(name, idx) else: try: return nextNode.getNextNode(name, idx) except (error.NoSuchInstanceError, 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.NoSuchInstanceError, error.NoSuchObjectError): return # missing object is not an error here else: node.readTest(name, val, idx, acInfo) def readGet(self, name, val, idx, acInfo): try: node = self.getBranch(name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): return name, exval.noSuchObject else: return node.readGet(name, val, idx, acInfo) # Read next operation is subtree-specific depthFirst, breadthFirst = 0, 1 def readTestNext(self, name, val, idx, acInfo, oName=None): if oName is None: oName = name topOfTheMib = True else: topOfTheMib = False nextName = name direction = self.depthFirst while 1: # XXX linear search here if direction == self.depthFirst: direction = self.breadthFirst try: node = self.getBranch(nextName, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): continue else: try: node = self.getNextBranch(nextName, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): if topOfTheMib: return raise direction = self.depthFirst nextName = node.name try: return node.readTestNext(nextName, val, idx, acInfo, oName) except (error.NoAccessError, error.NoSuchInstanceError, error.NoSuchObjectError): pass def readGetNext(self, name, val, idx, acInfo, oName=None): if oName is None: oName = name topOfTheMib = True else: topOfTheMib = False nextName = name direction = self.depthFirst while True: # XXX linear search ahead! if direction == self.depthFirst: direction = self.breadthFirst try: node = self.getBranch(nextName, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): continue else: try: node = self.getNextBranch(nextName, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): if topOfTheMib: return name, exval.endOfMib raise direction = self.depthFirst nextName = node.name try: return node.readGetNext(nextName, val, idx, acInfo, oName) except (error.NoAccessError, error.NoSuchInstanceError, error.NoSuchObjectError): pass # 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, acInfo) def writeCommit(self, name, val, idx, acInfo): self.getBranch(name, idx).writeCommit(name, val, idx, acInfo) def writeCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 self.getBranch(name, idx).writeCleanup(name, val, idx, acInfo) def writeUndo(self, name, val, idx, acInfo): self.getBranch(name, idx).writeUndo(name, val, idx, acInfo) class MibScalar(MibTree): """Scalar MIB variable. Implements access control checking.""" maxAccess = 'readonly' # # Subtree traversal # # Missing branches are indicated by the NoSuchInstanceError exception. # def getBranch(self, name, idx): try: return MibTree.getBranch(self, name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): raise error.NoSuchInstanceError(idx=idx, name=name) def getNextBranch(self, name, idx=None): try: return MibTree.getNextBranch(self, name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): raise error.NoSuchInstanceError(idx=idx, name=name) def getNode(self, name, idx=None): try: return MibTree.getNode(self, name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): raise error.NoSuchInstanceError(idx=idx, name=name) def getNextNode(self, name, idx=None): try: return MibTree.getNextNode(self, name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): raise error.NoSuchInstanceError(idx=idx, name=name) # 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) 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) MibTree.readTest(self, name, val, idx, acInfo) def readGet(self, name, val, idx, acInfo): try: node = self.getBranch(name, idx) except error.NoSuchInstanceError: return name, exval.noSuchInstance else: return node.readGet(name, val, idx, acInfo) def readTestNext(self, name, val, idx, acInfo, oName=None): (acFun, acCtx) = acInfo 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) MibTree.readTestNext(self, name, val, idx, acInfo, oName) def readGetNext(self, name, val, idx, acInfo, oName=None): (acFun, acCtx) = acInfo # have to duplicate AC here as *Next code above treats # noAccess as a noSuchObject at the Test stage, goes on # to Reading 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) return MibTree.readGetNext(self, name, val, idx, acInfo, oName) # 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) if acFun: if self.maxAccess not in ('readwrite', 'readcreate') or \ acFun(name, self.syntax, idx, 'write', acCtx): raise error.NotWritableError(idx=idx, name=name) MibTree.writeTest(self, name, val, idx, acInfo) 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 # # Managed object value access methods # # noinspection PyUnusedLocal def getValue(self, name, idx): debug.logger & debug.flagIns and debug.logger('getValue: returning %r for %s' % (self.syntax, self.name)) return self.syntax.clone() def setValue(self, value, name, idx): if value is None: value = univ.noValue try: if hasattr(self.syntax, 'setValue'): return self.syntax.setValue(value) else: return self.syntax.clone(value) except PyAsn1Error: exc_t, exc_v, exc_tb = sys.exc_info() debug.logger & debug.flagIns and debug.logger('setValue: %s=%r failed with traceback %s' % ( self.name, value, traceback.format_exception(exc_t, exc_v, exc_tb))) if isinstance(exc_v, error.TableRowManagement): raise exc_v else: raise error.WrongValueError(idx=idx, name=name, msg=exc_v) # # Subtree traversal # # Missing branches are indicated by the NoSuchInstanceError exception. # def getBranch(self, name, idx): try: return MibTree.getBranch(self, name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): raise error.NoSuchInstanceError(idx=idx, name=name) def getNextBranch(self, name, idx=None): try: return MibTree.getNextBranch(self, name, idx) except (error.NoSuchInstanceError, error.NoSuchObjectError): raise error.NoSuchInstanceError(idx=idx, name=name) 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.NoSuchInstanceError(idx=idx, name=name) def readGet(self, name, val, idx, acInfo): # Return current variable (name, value) if name == self.name: debug.logger & debug.flagIns and debug.logger('readGet: %s=%r' % (self.name, self.syntax)) return self.name, self.getValue(name, idx) else: raise error.NoSuchInstanceError(idx=idx, name=name) def readTestNext(self, name, val, idx, acInfo, oName=None): if name != self.name or name <= oName: raise error.NoSuchInstanceError(idx=idx, name=name) def readGetNext(self, name, val, idx, acInfo, oName=None): if name == self.name and name > oName: debug.logger & debug.flagIns and debug.logger('readGetNext: %s=%r' % (self.name, self.syntax)) return self.readGet(name, val, idx, acInfo) else: raise error.NoSuchInstanceError(idx=idx, name=name) # Write operation: two-phase commit # noinspection PyAttributeOutsideInit def writeTest(self, name, val, idx, acInfo): # Make sure write's allowed if name == self.name: try: self.__newSyntax = self.setValue(val, name, idx) except error.MibOperationError: # SMI exceptions may carry additional content why = sys.exc_info()[1] if 'syntax' in why: self.__newSyntax = why['syntax'] raise why else: raise error.WrongValueError(idx=idx, name=name, msg=sys.exc_info()[1]) else: raise error.NoSuchInstanceError(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 # noinspection PyAttributeOutsideInit def writeCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 debug.logger & debug.flagIns and debug.logger('writeCleanup: %s=%r' % (name, val)) # Drop previous value self.__newSyntax = self.__oldSyntax = None # noinspection PyAttributeOutsideInit 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 # noinspection PyUnusedLocal,PyAttributeOutsideInit def createTest(self, name, val, idx, acInfo): if name == self.name: try: self.__newSyntax = self.setValue(val, name, idx) except error.MibOperationError: # SMI exceptions may carry additional content why = sys.exc_info()[1] if 'syntax' in why: self.__newSyntax = why['syntax'] else: raise error.WrongValueError(idx=idx, name=name, msg=sys.exc_info()[1]) else: raise error.NoSuchInstanceError(idx=idx, name=name) def createCommit(self, name, val, idx, acInfo): if val is not None: self.writeCommit(name, val, idx, acInfo) def createCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 debug.logger & debug.flagIns and debug.logger('createCleanup: %s=%r' % (name, val)) if val is not None: self.writeCleanup(name, val, idx, acInfo) def createUndo(self, name, val, idx, acInfo): if val is not None: self.writeUndo(name, val, idx, acInfo) # Destroy operation # noinspection PyUnusedLocal,PyAttributeOutsideInit def destroyTest(self, name, val, idx, acInfo): if name == self.name: try: self.__newSyntax = self.setValue(val, name, idx) except error.MibOperationError: # SMI exceptions may carry additional content why = sys.exc_info()[1] if 'syntax' in why: self.__newSyntax = why['syntax'] else: raise error.NoSuchInstanceError(idx=idx, name=name) def destroyCommit(self, name, val, idx, acInfo): pass # noinspection PyUnusedLocal def destroyCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 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 = {} # # Subtree traversal # # Missing leaves are indicated by the NoSuchInstanceError exception. # def getBranch(self, name, idx): if name in self._vars: return self._vars[name] raise error.NoSuchInstanceError(name=name, idx=idx) 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, 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, acInfo) def createCommit(self, name, val, idx, acInfo): # Commit new instance value if name in self._vars: # XXX if name in self.__createdInstances: self._vars[name].createCommit(name, val, idx, acInfo) return self.__createdInstances[name].createCommit(name, val, idx, acInfo) # ...commit new column instance self._vars[name], self.__createdInstances[name] = \ self.__createdInstances[name], self._vars.get(name) def createCleanup(self, name, val, idx, acInfo): # Drop previous column instance self.branchVersionId += 1 if name in self.__createdInstances: if self.__createdInstances[name] is not None: self.__createdInstances[name].createCleanup(name, val, idx, acInfo) del self.__createdInstances[name] elif name in self._vars: self._vars[name].createCleanup(name, val, idx, acInfo) def createUndo(self, name, val, idx, 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, acInfo) # 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, acInfo) def destroyCommit(self, name, val, idx, 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, acInfo) self.__destroyedInstances[name] = self._vars[name] del self._vars[name] def destroyCleanup(self, name, val, idx, acInfo): # Drop instance copy self.branchVersionId += 1 if name in self.__destroyedInstances: self.__destroyedInstances[name].destroyCleanup(name, val, idx, acInfo) debug.logger & debug.flagIns and debug.logger('destroyCleanup: %s=%r' % (name, val)) del self.__destroyedInstances[name] def destroyUndo(self, name, val, idx, acInfo): # Set back column instance if name in self.__destroyedInstances: self._vars[name] = self.__destroyedInstances[name] self._vars[name].destroyUndo(name, val, idx, acInfo) del self.__destroyedInstances[name] # Set/modify column def writeTest(self, name, val, idx, acInfo): # Besides common checks, request row creation on no-instance try: # First try the instance MibScalar.writeTest(self, name, val, idx, acInfo) # ...otherwise proceed with creating new column except (error.NoSuchInstanceError, error.RowCreationWanted): excValue = sys.exc_info()[1] if isinstance(excValue, error.RowCreationWanted): self.__rowOpWanted[name] = excValue else: self.__rowOpWanted[name] = error.RowCreationWanted() self.createTest(name, val, idx, acInfo) except error.RowDestructionWanted: self.__rowOpWanted[name] = error.RowDestructionWanted() self.destroyTest(name, val, idx, acInfo) if name in self.__rowOpWanted: debug.logger & debug.flagIns and debug.logger( '%s flagged by %s=%r, exception %s' % (self.__rowOpWanted[name], name, val, sys.exc_info()[1])) raise self.__rowOpWanted[name] def __delegateWrite(self, subAction, name, val, idx, acInfo): if name not in self.__rowOpWanted: getattr(MibScalar, 'write' + subAction)(self, name, val, idx, acInfo) return if isinstance(self.__rowOpWanted[name], error.RowCreationWanted): getattr(self, 'create' + subAction)(name, val, idx, acInfo) if isinstance(self.__rowOpWanted[name], error.RowDestructionWanted): getattr(self, 'destroy' + subAction)(name, val, idx, acInfo) def writeCommit(self, name, val, idx, acInfo): self.__delegateWrite('Commit', name, val, idx, acInfo) if name in self.__rowOpWanted: raise self.__rowOpWanted[name] def writeCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 self.__delegateWrite('Cleanup', name, val, idx, acInfo) 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): if name in self.__rowOpWanted: self.__rowOpWanted[name] = error.RowDestructionWanted() self.__delegateWrite('Undo', name, val, idx, acInfo) 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, parentIndices=None): if not value: raise error.SmiError('Short OID for index %r' % (obj,)) if hasattr(obj, 'cloneFromName'): return obj.cloneFromName(value, impliedFlag, parentRow=self, parentIndices=parentIndices) 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(tuple(value)), () elif obj.isFixedLength(): l = obj.getFixedLength() return obj.clone(tuple(value[:l])), value[l:] else: return obj.clone(tuple(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(tuple(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, parentIndices=None): if hasattr(obj, 'cloneAsName'): return obj.cloneAsName(impliedFlag, parentRow=self, parentIndices=parentIndices) baseTag = obj.getTagSet().getBaseTag() if baseTag == self.__intBaseTag: # noinspection PyRedundantParentheses 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(obj),) + 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): # Convert OID suffix into index vals instId = name[len(self.name) + 1:] baseIndices = [] indices = [] for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag, indices) if self.name == mibObj.name[:-1]: baseIndices.append((mibObj.name, syntax)) indices.append(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, acInfo ) def receiveManagementEvent(self, action, baseIndices, val, idx, 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) parentIndices = [] for name, syntax in baseIndices: if name == mibObj.name: newSuffix += self.getAsName(syntax, impliedFlag, parentIndices) parentIndices.append(syntax) if newSuffix: debug.logger & debug.flagIns and debug.logger( 'receiveManagementEvent %s for suffix %s' % (action, newSuffix)) self.__manageColumns(action, (), newSuffix, val, idx, acInfo) 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 += (name,) return self def getIndexNames(self): return self.indexNames def __manageColumns(self, action, excludeName, nameSuffix, val, idx, acInfo): # Build a map of index names and values for automatic initialization indexVals = {} instId = nameSuffix indices = [] for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag, indices) indexVals[mibObj.name] = syntax indices.append(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, acInfo) 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): # Relay operation request to column, expect row operation request. rowIsActive = False try: getattr(self.getBranch(name, idx), 'write' + subAction)( name, val, idx, acInfo ) except error.RowCreationWanted: self.__manageColumns( 'create' + subAction, name[:len(self.name) + 1], name[len(self.name) + 1:], None, idx, acInfo ) self.announceManagementEvent( 'create' + subAction, name, None, idx, acInfo ) # watch for RowStatus == 'stActive' rowIsActive = sys.exc_info()[1].get('syntax', 0) == 1 except error.RowDestructionWanted: self.__manageColumns( 'destroy' + subAction, name[:len(self.name) + 1], name[len(self.name) + 1:], None, idx, acInfo ) self.announceManagementEvent( 'destroy' + subAction, name, None, idx, acInfo ) return rowIsActive def writeTest(self, name, val, idx, acInfo): self.__delegate('Test', name, val, idx, acInfo) def writeCommit(self, name, val, idx, acInfo): rowIsActive = self.__delegate('Commit', name, val, idx, acInfo) if rowIsActive: for mibNode in self._vars.values(): colNode = mibNode.getNode(mibNode.name + name[len(self.name) + 1:]) if not colNode.syntax.hasValue(): raise error.InconsistentValueError(msg='Row consistency check failed for %r' % colNode) def writeCleanup(self, name, val, idx, acInfo): self.branchVersionId += 1 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) try: syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag, indices) except PyAsn1Error: debug.logger & debug.flagIns and debug.logger('error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, sys.exc_info()[1])) indices = [instId] instId = () break 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""" try: return self.__idxToIdCache[indices] except TypeError: cacheable = False except KeyError: cacheable = True idx = 0 instId = () parentIndices = [] for impliedFlag, modName, symName in self.indexNames: if idx >= len(indices): break mibObj, = mibBuilder.importSymbols(modName, symName) syntax = mibObj.syntax.clone(indices[idx]) instId += self.getAsName(syntax, impliedFlag, parentIndices) parentIndices.append(syntax) idx += 1 if cacheable: 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)) # OID tree itu_t = MibTree((0,)).setLabel('itu-t') iso = MibTree((1,)) joint_iso_itu_t = MibTree((2,)).setLabel('joint-iso-itu-t') 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, itu_t=itu_t, iso=iso, joint_iso_itu_t=joint_iso_itu_t, 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 pysnmp-4.4.12/pysnmp/smi/mibs/SNMPv2-TC.py000066400000000000000000000704651354244100700201170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys import inspect import string from pysnmp.smi.error import * from pysnmp import debug from pyasn1.type import univ from pyasn1.compat import octets from pyasn1.type.base import Asn1Item 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(object): displayHint = '' status = 'current' description = '' reference = '' bits = () __integer = Integer() __unsigned32 = Unsigned32() __timeticks = TimeTicks() __octetString = OctetString() 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 getValue(self): return self.clone() def setValue(self, value): if value is None: value = univ.noValue return self.clone(value) def prettyOut(self, value): # override asn1 type method """Implements DISPLAY-HINT evaluation""" if self.displayHint and (self.__integer.isSuperTypeOf(self, matchConstraints=False) and not self.getNamedValues() or self.__unsigned32.isSuperTypeOf(self, matchConstraints=False) or self.__timeticks.isSuperTypeOf(self, matchConstraints=False)): _ = lambda t, f=0: (t, f) displayHintType, decimalPrecision = _(*self.displayHint.split('-')) if displayHintType == 'x': return '0x%x' % value elif displayHintType == 'd': try: return '%.*f' % (int(decimalPrecision), float(value) / pow(10, int(decimalPrecision))) except Exception: raise SmiError( 'float evaluation error: %s' % sys.exc_info()[1] ) elif displayHintType == 'o': return '0%o' % value elif displayHintType == 'b': runningValue = value outputValue = ['B'] while runningValue: outputValue.insert(0, '%d' % (runningValue & 0x01)) runningValue >>= 1 return ''.join(outputValue) else: raise SmiError( 'Unsupported numeric type spec "%s" at %s' % (displayHintType, self.__class__.__name__) ) elif self.displayHint and self.__octetString.isSuperTypeOf(self, matchConstraints=False): outputValue = '' runningValue = OctetString(value).asOctets() displayHint = self.displayHint while runningValue and displayHint: # 1 if displayHint[0] == '*': repeatIndicator = repeatCount = octets.oct2int(runningValue[0]) displayHint = displayHint[1:] runningValue = runningValue[1:] else: repeatCount = 1 repeatIndicator = None # 2 octetLength = '' while displayHint and displayHint[0] in string.digits: octetLength += displayHint[0] displayHint = displayHint[1:] # length is manatory, but people ignore that if not octetLength: octetLength = len(runningValue) try: octetLength = int(octetLength) except Exception: raise SmiError( 'Bad octet length: %s' % octetLength ) if not displayHint: raise SmiError( 'Short octet length: %s' % self.displayHint ) # 3 displayFormat = displayHint[0] displayHint = displayHint[1:] # 4 if displayHint and displayHint[0] not in string.digits and displayHint[0] != '*': displaySep = displayHint[0] displayHint = displayHint[1:] else: displaySep = '' # 5 if displayHint and displaySep and repeatIndicator is not None: repeatTerminator = displayHint[0] displaySep = '' displayHint = displayHint[1:] else: repeatTerminator = None while repeatCount: repeatCount -= 1 if displayFormat == 'a': outputValue += runningValue[:octetLength].decode('ascii', 'ignore') elif displayFormat == 't': outputValue += runningValue[:octetLength].decode('utf-8', 'ignore') elif displayFormat in ('x', 'd', 'o'): number = 0 numberString = runningValue[:octetLength] while numberString: number <<= 8 try: number |= octets.oct2int(numberString[0]) numberString = numberString[1:] except Exception: raise SmiError( 'Display format eval failure: %s: %s' % (numberString, sys.exc_info()[1]) ) if displayFormat == 'x': outputValue += '%02x' % number elif displayFormat == 'o': outputValue += '%03o' % number else: outputValue += '%d' % number else: raise SmiError( 'Unsupported display format char: %s' % displayFormat ) if runningValue and repeatTerminator: outputValue += repeatTerminator runningValue = runningValue[octetLength:] if runningValue and displaySep: outputValue += displaySep if not displayHint: displayHint = self.displayHint return outputValue for base in inspect.getmro(self.__class__): if not issubclass(base, TextualConvention) and issubclass(base, Asn1Item): return base.prettyOut(self, value) raise SmiError('TEXTUAL-CONVENTION has no underlying SNMP base type') def prettyIn(self, value): # override asn1 type method """Implements DISPLAY-HINT parsing into base SNMP value Proper parsing seems impossible due to ambiguities. Here we are trying to do our best, but be prepared for failures on complicated DISPLAY-HINTs. Keep in mind that this parser only works with "text" input meaning `unicode` (Py2) or `str` (Py3). """ for base in inspect.getmro(self.__class__): if not issubclass(base, TextualConvention) and issubclass(base, Asn1Item): break else: raise SmiError('TEXTUAL-CONVENTION has no underlying SNMP base type') if self.displayHint and (self.__integer.isSuperTypeOf(self, matchConstraints=False) and self.getNamedValues() or self.__unsigned32.isSuperTypeOf(self, matchConstraints=False) or self.__timeticks.isSuperTypeOf(self, matchConstraints=False)): value = str(value) _ = lambda t, f=0: (t, f) displayHintType, decimalPrecision = _(*self.displayHint.split('-')) if displayHintType == 'x' and (value.startswith('0x') or value.startswith('-0x')): try: if value.startswith('-'): return base.prettyIn(self, -int(value[3:], 16)) else: return base.prettyIn(self, int(value[2:], 16)) except Exception: raise SmiError( 'integer evaluation error: %s' % sys.exc_info()[1] ) elif displayHintType == 'd': try: return base.prettyIn(self, int(float(value) * 10**int(decimalPrecision))) except Exception: raise SmiError( 'float evaluation error: %s' % sys.exc_info()[1] ) elif displayHintType == 'o' and (value.startswith('0') or value.startswith('-0')): try: return base.prettyIn(self, int(value, 8)) except Exception: raise SmiError( 'octal evaluation error: %s' % sys.exc_info()[1] ) elif displayHintType == 'b' and (value.startswith('B') or value.startswith('-B')): negative = value.startswith('-') if negative: value = value[2:] else: value = value[1:] value = [x != '0' and 1 or 0 for x in value] binValue = 0 while value: binValue <<= value[0] del value[0] return base.prettyIn(self, binValue) else: raise SmiError( 'Unsupported numeric type spec "%s" at %s' % (displayHintType, self.__class__.__name__) ) elif self.displayHint and self.__octetString.isSuperTypeOf(self, matchConstraints=False): numBase = { 'x': 16, 'd': 10, 'o': 8 } numDigits = { 'x': octets.str2octs(string.hexdigits), 'o': octets.str2octs(string.octdigits), 'd': octets.str2octs(string.digits) } # how do we know if object is initialized with display-hint # formatted text? based on "text" input maybe? # That boils down to `str` object on Py3 or `unicode` on Py2. if octets.isStringType(value) and not octets.isOctetsType(value): value = base.prettyIn(self, value) else: return base.prettyIn(self, value) outputValue = octets.str2octs('') runningValue = value displayHint = self.displayHint while runningValue and displayHint: # 1 this information is totally lost, just fail explicitly if displayHint[0] == '*': raise SmiError( 'Can\'t parse "*" in DISPLAY-HINT (%s)' % self.__class__.__name__ ) # 2 this becomes ambiguous when it comes to rendered value octetLength = '' while displayHint and displayHint[0] in string.digits: octetLength += displayHint[0] displayHint = displayHint[1:] # length is mandatory but people ignore that if not octetLength: octetLength = len(runningValue) try: octetLength = int(octetLength) except Exception: raise SmiError( 'Bad octet length: %s' % octetLength ) if not displayHint: raise SmiError( 'Short octet length: %s' % self.displayHint ) # 3 displayFormat = displayHint[0] displayHint = displayHint[1:] # 4 this is the lifesaver -- we could use it as an anchor if displayHint and displayHint[0] not in string.digits and displayHint[0] != '*': displaySep = displayHint[0] displayHint = displayHint[1:] else: displaySep = '' # 5 is probably impossible to support if displayFormat in ('a', 't'): outputValue += runningValue[:octetLength] elif displayFormat in numBase: if displaySep: guessedOctetLength = runningValue.find(octets.str2octs(displaySep)) if guessedOctetLength == -1: guessedOctetLength = len(runningValue) else: for idx in range(len(runningValue)): if runningValue[idx] not in numDigits[displayFormat]: guessedOctetLength = idx break else: guessedOctetLength = len(runningValue) try: num = int(octets.octs2str(runningValue[:guessedOctetLength]), numBase[displayFormat]) except Exception: raise SmiError( 'Display format eval failure: %s: %s' % (runningValue[:guessedOctetLength], sys.exc_info()[1]) ) num_as_bytes = [] if num: while num: num_as_bytes.append(num & 0xFF) num >>= 8 else: num_as_bytes = [0] while len(num_as_bytes) < octetLength: num_as_bytes.append(0) num_as_bytes.reverse() outputValue += octets.ints2octs(num_as_bytes) if displaySep: guessedOctetLength += 1 octetLength = guessedOctetLength else: raise SmiError( 'Unsupported display format char: %s' % displayFormat ) runningValue = runningValue[octetLength:] if not displayHint: displayHint = self.displayHint return base.prettyIn(self, outputValue) else: return base.prettyIn(self, value) class DisplayString(TextualConvention, OctetString): description = "Represents textual information taken from the NVT ASCII character set, as defined in pages 4, 10-11 of RFC 854. To summarize RFC 854, the NVT ASCII repertoire specifies: - the use of character codes 0-127 (decimal) - the graphics characters (32-126) are interpreted as US ASCII - NUL, LF, CR, BEL, BS, HT, VT and FF have the special meanings specified in RFC 854 - the other 25 codes have no standard interpretation - the sequence 'CR LF' means newline - the sequence 'CR NUL' means carriage-return - an 'LF' not preceded by a 'CR' means moving to the same column on the next line. - the sequence 'CR x' for any x other than LF or NUL is illegal. (Note that this also means that a string may end with either 'CR LF' or 'CR NUL', but not with CR.) Any object defined using this syntax may not exceed 255 characters in length." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) displayHint = "255a" class PhysAddress(TextualConvention, OctetString): description = "Represents textual information taken from the NVT ASCII character set, as defined in pages 4, 10-11 of RFC 854. To summarize RFC 854, the NVT ASCII repertoire specifies: - the use of character codes 0-127 (decimal) - the graphics characters (32-126) are interpreted as US ASCII - NUL, LF, CR, BEL, BS, HT, VT and FF have the special meanings specified in RFC 854 - the other 25 codes have no standard interpretation - the sequence 'CR LF' means newline - the sequence 'CR NUL' means carriage-return - an 'LF' not preceded by a 'CR' means moving to the same column on the next line. - the sequence 'CR x' for any x other than LF or NUL is illegal. (Note that this also means that a string may end with either 'CR LF' or 'CR NUL', but not with CR.) Any object defined using this syntax may not exceed 255 characters in length." status = 'current' displayHint = "1x:" class MacAddress(TextualConvention, OctetString): description = "Represents an 802 MAC address represented in the `canonical' order defined by IEEE 802.1a, i.e., as if it were transmitted least significant bit first, even though 802.5 (in contrast to other 802.x protocols) requires MAC addresses to be transmitted most significant bit first." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6) displayHint = "1x:" fixedLength = 6 class TruthValue(TextualConvention, Integer): description = 'Represents a boolean value.' status = 'current' subtypeSpec = Integer.subtypeSpec + SingleValueConstraint(1, 2) namedValues = NamedValues(('true', 1), ('false', 2)) class TestAndIncr(TextualConvention, Integer): description = "Represents integer-valued information used for atomic operations. When the management protocol is used to specify that an object instance having this syntax is to be modified, the new value supplied via the management protocol must precisely match the value presently held by the instance. If not, the management protocol set operation fails with an error of `inconsistentValue'. Otherwise, if the current value is the maximum value of 2^31-1 (2147483647 decimal), then the value held by the instance is wrapped to zero; otherwise, the value held by the instance is incremented by one. (Note that regardless of whether the management protocol set operation succeeds, the variable- binding in the request and response PDUs are identical.) The value of the ACCESS clause for objects having this syntax is either `read-write' or `read-create'. When an instance of a columnar object having this syntax is created, any value may be supplied via the management protocol. When the network management portion of the system is re- initialized, the value of every object instance having this syntax must either be incremented from its value prior to the re-initialization, or (if the value prior to the re- initialization is unknown) be set to a pseudo-randomly generated value." status = 'current' subtypeSpec = Integer.subtypeSpec + ValueRangeConstraint(0, 2147483647) defaultValue = 0 def setValue(self, value): if value is not None: if value != self: raise InconsistentValueError() value += 1 if value > 2147483646: value = 0 if value is None: value = univ.noValue return self.clone(value) class AutonomousType(TextualConvention, ObjectIdentifier): description = 'Represents an independently extensible type identification value. It may, for example, indicate a particular sub-tree with further MIB definitions, or define a particular type of protocol or hardware.' status = 'current' class InstancePointer(TextualConvention, ObjectIdentifier): description = 'A pointer to either a specific instance of a MIB object or a conceptual row of a MIB table in the managed device. In the latter case, by convention, it is the name of the particular instance of the first accessible columnar object in the conceptual row. The two uses of this textual convention are replaced by VariablePointer and RowPointer, respectively.' status = 'obsolete' class VariablePointer(TextualConvention, ObjectIdentifier): description = 'A pointer to a specific object instance. For example, sysContact.0 or ifInOctets.3.' status = 'current' class RowPointer(TextualConvention, ObjectIdentifier): description = 'Represents a pointer to a conceptual row. The value is the name of the instance of the first accessible columnar object in the conceptual row. For example, ifIndex.3 would point to the 3rd row in the ifTable (note that if ifIndex were not-accessible, then ifDescr.3 would be used instead).' status = 'current' class RowStatus(TextualConvention, Integer): """A special kind of scalar MIB variable responsible for MIB table row creation/destruction. """ description = "The RowStatus textual convention is used to manage the creation and deletion of conceptual rows, and is used as the value of the SYNTAX clause for the status column of a conceptual row (as described in Section 7.7.1 of [2].)..." status = 'current' 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): (RowCreationWanted, stActive), (stCreateAndGo, stNotReady): (InconsistentValueError, stNotReady), (stCreateAndGo, stNotInService): (InconsistentValueError, stNotInService), (stCreateAndGo, stActive): (InconsistentValueError, stActive), # (stCreateAndWait, stNotExists): (RowCreationWanted, stActive), (stCreateAndWait, stNotReady): (InconsistentValueError, stNotReady), (stCreateAndWait, stNotInService): (InconsistentValueError, stNotInService), (stCreateAndWait, stActive): (InconsistentValueError, stActive), # (stActive, stNotExists): (InconsistentValueError, stNotExists), (stActive, stNotReady): (InconsistentValueError, stNotReady), (stActive, stNotInService): (None, stActive), (stActive, stActive): (None, stActive), # (stNotInService, stNotExists): (InconsistentValueError, stNotExists), (stNotInService, stNotReady): (InconsistentValueError, stNotReady), (stNotInService, stNotInService): (None, stNotInService), (stNotInService, stActive): (None, stActive), # (stDestroy, stNotExists): (RowDestructionWanted, stNotExists), (stDestroy, stNotReady): (RowDestructionWanted, stNotExists), (stDestroy, stNotInService): (RowDestructionWanted, stNotExists), (stDestroy, stActive): (RowDestructionWanted, stNotExists), # This is used on instantiation (stNotExists, stNotExists): (None, stNotExists) } def setValue(self, value): if value is None: value = univ.noValue value = self.clone(value) # Run through states transition matrix, # resolve new instance value excValue, newState = self.stateMatrix.get( (value.hasValue() and value or self.stNotExists, self.hasValue() and self or self.stNotExists), (MibOperationError, None) ) if newState is None: newState = univ.noValue newState = self.clone(newState) debug.logger & debug.flagIns and debug.logger( 'RowStatus state change from %r to %r produced new state %r, error indication %r' % ( self, value, newState, excValue)) if excValue is not None: excValue = excValue( msg='Exception at row state transition from %r to %r yields state %r and exception' % ( self, value, newState), syntax=newState ) raise excValue return newState class TimeStamp(TextualConvention, TimeTicks): description = 'The value of the sysUpTime object at which a specific occurrence happened. The specific occurrence must be defined in the description of any object defined using this type. If sysUpTime is reset to zero as a result of a re- initialization of the network management (sub)system, then the values of all TimeStamp objects are also reset. However, after approximately 497 days without a re- initialization, the sysUpTime object will reach 2^^32-1 and then increment around to zero; in this case, existing values of TimeStamp objects do not change. This can lead to ambiguities in the value of TimeStamp objects.' status = 'current' class TimeInterval(TextualConvention, Integer): description = 'A period of time, measured in units of 0.01 seconds.' status = 'current' subtypeSpec = Integer.subtypeSpec + ValueRangeConstraint(0, 2147483647) class DateAndTime(TextualConvention, OctetString): description = "A date-time specification. field octets contents range ----- ------ -------- ----- 1 1-2 year* 0..65536 2 3 month 1..12 3 4 day 1..31 4 5 hour 0..23 5 6 minutes 0..59 6 7 seconds 0..60 (use 60 for leap-second) 7 8 deci-seconds 0..9 8 9 direction from UTC '+' / '-' 9 10 hours from UTC* 0..13 10 11 minutes from UTC 0..59 * Notes: - the value of year is in network-byte order - daylight saving time in New Zealand is +13 For example, Tuesday May 26, 1992 at 1:30:15 PM EDT would be displayed as: 1992-5-26,13:30:15.0,-4:0 Note that if only local time is known, then timezone information (fields 8-10) is not present." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 11) displayHint = "2d-1d-1d,1d:1d:1d.1d,1a1d:1d" class StorageType(TextualConvention, Integer): description = "Describes the memory realization of a conceptual row. A row which is volatile(2) is lost upon reboot. A row which is either nonVolatile(3), permanent(4) or readOnly(5), is backed up by stable storage. A row which is permanent(4) can be changed but not deleted. A row which is readOnly(5) cannot be changed nor deleted. If the value of an object with this syntax is either permanent(4) or readOnly(5), it cannot be written. Conversely, if the value is either other(1), volatile(2) or nonVolatile(3), it cannot be modified to be permanent(4) or readOnly(5). (All illegal modifications result in a 'wrongValue' error.) Every usage of this textual convention is required to specify the columnar objects which a permanent(4) row must at a minimum allow to be writable." status = 'current' subtypeSpec = Integer.subtypeSpec + SingleValueConstraint(1, 2, 3, 4, 5) namedValues = NamedValues( ('other', 1), ('volatile', 2), ('nonVolatile', 3), ('permanent', 4), ('readOnly', 5) ) class TDomain(TextualConvention, ObjectIdentifier): reference = 'The SNMPv2-TM MIB module is defined in RFC 1906.' description = 'Denotes a kind of transport service. Some possible values, such as snmpUDPDomain, are defined in the SNMPv2-TM MIB module. Other possible values are defined in other MIB modules.' status = 'current' class TAddress(TextualConvention, OctetString): reference = 'The SNMPv2-TM MIB module is defined in RFC 1906.' description = 'Denotes a transport service address. A TAddress value is always interpreted within the context of a TDomain value. Thus, each definition of a TDomain value must be accompanied by a definition of a textual convention for use with that TDomain. Some possible textual conventions, such as SnmpUDPAddress for snmpUDPDomain, are defined in the SNMPv2-TM MIB module. Other possible textual conventions are defined in other MIB modules.' status = 'current' 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/SNMPv2-TM.py000066400000000000000000000154051354244100700201220ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module SNMPv2-TM (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/SNMPv2-TM # Produced by pysmi-0.1.3 at Tue Apr 18 01:01:19 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # try: from socket import inet_ntop, inet_pton, AF_INET except ImportError: from socket import inet_ntoa, inet_aton, AF_INET inet_ntop = lambda x, y: inet_ntoa(y) inet_pton = lambda x, y: inet_aton(y) from pyasn1.compat.octets import int2oct, oct2int 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((1, 3, 6, 1, 6, 3, 19)) if mibBuilder.loadTexts: snmpv2tm.setRevisions(('2000-08-09 19:58', '1996-01-01 00:00', '1993-04-01 00:00',)) if mibBuilder.loadTexts: snmpv2tm.setLastUpdated('200008091958Z') if mibBuilder.loadTexts: snmpv2tm.setOrganization('IETF SNMPv3 Working Group') if mibBuilder.loadTexts: snmpv2tm.setContactInfo('WG-EMail: snmpv3@tis.com Subscribe: majordomo@tis.com In message body: subscribe snmpv3 Chair: Russ Mundy TIS Labs at Network Associates postal: 3060 Washington Rd Glenwood MD 21738 USA EMail: mundy@tislabs.com phone: +1 301 854-6889 Editor: Randy Presuhn BMC Software, Inc. postal: 2141 North First Street San Jose, CA 95131 USA EMail: randy-presuhn@bmc.com phone: +1 408 546-1006') if mibBuilder.loadTexts: snmpv2tm.setDescription('The MIB module for SNMP transport mappings.') snmpUDPDomain = ObjectIdentity((1, 3, 6, 1, 6, 1, 1)) if mibBuilder.loadTexts: snmpUDPDomain.setStatus('current') if mibBuilder.loadTexts: snmpUDPDomain.setDescription('The SNMP over UDP over IPv4 transport domain. The corresponding transport address is of type SnmpUDPAddress.') class SnmpUDPAddress(TextualConvention, OctetString): description = 'Represents a UDP over IPv4 address: octets contents encoding 1-4 IP-address network-byte order 5-6 UDP-port network-byte order ' status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6) displayHint = "1d.1d.1d.1d/2d" fixedLength = 6 def prettyIn(self, value): if isinstance(value, tuple): # Wild hack -- need to implement TextualConvention.prettyIn value = inet_pton(AF_INET, value[0]) + int2oct((value[1] >> 8) & 0xff) + int2oct(value[1] & 0xff) return OctetString.prettyIn(self, value) # Socket address syntax coercion def __asSocketAddress(self): if not hasattr(self, '__tuple_value'): v = self.asOctets() self.__tuple_value = ( inet_ntop(AF_INET, v[:4]), oct2int(v[4]) << 8 | oct2int(v[5]) ) return self.__tuple_value def __iter__(self): return iter(self.__asSocketAddress()) def __getitem__(self, item): return self.__asSocketAddress()[item] snmpCLNSDomain = ObjectIdentity((1, 3, 6, 1, 6, 1, 2)) if mibBuilder.loadTexts: snmpCLNSDomain.setStatus('current') if mibBuilder.loadTexts: snmpCLNSDomain.setDescription('The SNMP over CLNS transport domain. The corresponding transport address is of type SnmpOSIAddress.') snmpCONSDomain = ObjectIdentity((1, 3, 6, 1, 6, 1, 3)) if mibBuilder.loadTexts: snmpCONSDomain.setStatus('current') if mibBuilder.loadTexts: snmpCONSDomain.setDescription('The SNMP over CONS transport domain. The corresponding transport address is of type SnmpOSIAddress.') class SnmpOSIAddress(TextualConvention, OctetString): description = "Represents an OSI transport-address: octets contents encoding 1 length of NSAP 'n' as an unsigned-integer (either 0 or from 3 to 20) 2..(n+1) NSAP concrete binary representation (n+2)..m TSEL string of (up to 64) octets " status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 85) displayHint = "*1x:/1x:" snmpDDPDomain = ObjectIdentity((1, 3, 6, 1, 6, 1, 4)) if mibBuilder.loadTexts: snmpDDPDomain.setStatus('current') if mibBuilder.loadTexts: snmpDDPDomain.setDescription('The SNMP over DDP transport domain. The corresponding transport address is of type SnmpNBPAddress.') class SnmpNBPAddress(OctetString, TextualConvention): description = "Represents an NBP name: octets contents encoding 1 length of object 'n' as an unsigned integer 2..(n+1) object string of (up to 32) octets n+2 length of type 'p' as an unsigned integer (n+3)..(n+2+p) type string of (up to 32) octets n+3+p length of zone 'q' as an unsigned integer (n+4+p)..(n+3+p+q) zone string of (up to 32) octets For comparison purposes, strings are case-insensitive. All strings may contain any octet other than 255 (hex ff)." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(3, 99) snmpIPXDomain = ObjectIdentity((1, 3, 6, 1, 6, 1, 5)) if mibBuilder.loadTexts: snmpIPXDomain.setStatus('current') if mibBuilder.loadTexts: snmpIPXDomain.setDescription('The SNMP over IPX transport domain. The corresponding transport address is of type SnmpIPXAddress.') class SnmpIPXAddress(TextualConvention, OctetString): description = 'Represents an IPX address: octets contents encoding 1-4 network-number network-byte order 5-10 physical-address network-byte order 11-12 socket-number network-byte order ' status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(12, 12) displayHint = "4x.1x:1x:1x:1x:1x:1x.2d" fixedLength = 12 rfc1157Proxy = MibIdentifier((1, 3, 6, 1, 6, 2, 1)) rfc1157Domain = ObjectIdentity((1, 3, 6, 1, 6, 2, 1, 1)) if mibBuilder.loadTexts: rfc1157Domain.setStatus('deprecated') if mibBuilder.loadTexts: rfc1157Domain.setDescription('The transport domain for SNMPv1 over UDP over IPv4. The corresponding transport address is of type SnmpUDPAddress.') mibBuilder.exportSymbols("SNMPv2-TM", SnmpNBPAddress=SnmpNBPAddress, rfc1157Domain=rfc1157Domain, SnmpIPXAddress=SnmpIPXAddress, snmpUDPDomain=snmpUDPDomain, snmpCLNSDomain=snmpCLNSDomain, SnmpOSIAddress=SnmpOSIAddress, rfc1157Proxy=rfc1157Proxy, PYSNMP_MODULE_ID=snmpv2tm, snmpIPXDomain=snmpIPXDomain, snmpCONSDomain=snmpCONSDomain, snmpDDPDomain=snmpDDPDomain, SnmpUDPAddress=SnmpUDPAddress, snmpv2tm=snmpv2tm) pysnmp-4.4.12/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py000066400000000000000000000575571354244100700216610ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module TRANSPORT-ADDRESS-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/TRANSPORT-ADDRESS-MIB # Produced by pysmi-0.1.3 at Tue Apr 18 01:08:18 2017 # On host grommit.local platform Darwin version 16.4.0 by user ilya # Using Python version 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22) # from pyasn1.compat.octets import int2oct, oct2int from pysnmp import error from pysnmp.carrier import sockfix import socket has_ipv6 = socket.has_ipv6 if hasattr(socket, 'inet_ntop') and hasattr(socket, 'inet_pton'): inet_ntop = socket.inet_ntop inet_pton = socket.inet_pton else: import sys if sys.platform != "win32": from socket import inet_ntoa, inet_aton inet_ntop = lambda x, y: inet_ntoa(y) inet_pton = lambda x, y: inet_aton(y) has_ipv6 = False elif has_ipv6: import struct # The case of old Python at old Windows def inet_pton(address_family, ip_string): if address_family == socket.AF_INET: return socket.inet_aton(ip_string) elif address_family != socket.AF_INET6: raise socket.error( 'Unknown address family %s' % (address_family,) ) groups = ip_string.split(":") spaces = groups.count('') if '.' in groups[-1]: groups[-1:] = ["%x" % x for x in struct.unpack("!HH", socket.inet_aton(groups[-1]))] if spaces == 1: idx = groups.index('') groups[idx:idx + 1] = ['0'] * (8 - len(groups) + 1) elif spaces == 2: zeros = ['0'] * (8 - len(groups) + 2) if ip_string.startswith('::'): groups[:2] = zeros elif ip_string.endswith('::'): groups[-2:] = zeros else: raise socket.error( 'Invalid IPv6 address: "%s"' % (ip_string,) ) elif spaces == 3: if ip_string != '::': raise socket.error( 'Invalid IPv6 address: "%s"' % (ip_string,) ) return '\x00' * 16 elif spaces > 3: raise socket.error( 'Invalid IPv6 address: "%s"' % (ip_string,) ) groups = [t for t in [int(t, 16) for t in groups] if t & 0xFFFF == t] if len(groups) != 8: raise socket.error( 'Invalid IPv6 address: "%s"' % (ip_string,) ) return struct.pack('!8H', *groups) def inet_ntop(address_family, packed_ip): if address_family == socket.AF_INET: return socket.inet_ntop(packed_ip) elif address_family != socket.AF_INET6: raise socket.error( 'Unknown address family %s' % (address_family,) ) if len(packed_ip) != 16: raise socket.error( 'incorrect address length: %s' % len(packed_ip) ) groups = list(struct.unpack('!8H', packed_ip)) cur_base = best_base = cur_len = best_len = -1 for idx in range(8): if groups[idx]: if cur_base != -1: if best_base == -1 or cur_len > best_len: best_base, best_len = cur_base, cur_len cur_base = -1 else: if cur_base == -1: cur_base, cur_len = idx, 1 else: cur_len += 1 if cur_base != -1: if best_base == -1 or cur_len > best_len: best_base, best_len = cur_base, cur_len if best_base != -1 and best_len > 1: groups[best_base:best_base + best_len] = [':'] if groups[0] == ':': groups.insert(0, ':') if groups[-1] == ':': groups.append(':') f = lambda x: x != ':' and '%x' % x or '' return ':'.join([f(x) for x in groups]) Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, Unsigned32, MibIdentifier, Counter32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, TimeTicks, ObjectIdentity, Counter64, Gauge32, IpAddress, iso, mib_2 = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Unsigned32", "MibIdentifier", "Counter32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "TimeTicks", "ObjectIdentity", "Counter64", "Gauge32", "IpAddress", "iso", "mib-2") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") transportAddressMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 100)) if mibBuilder.loadTexts: transportAddressMIB.setRevisions(('2002-11-01 00:00',)) if mibBuilder.loadTexts: transportAddressMIB.setLastUpdated('200211010000Z') if mibBuilder.loadTexts: transportAddressMIB.setOrganization('IETF Operations and Management Area') if mibBuilder.loadTexts: transportAddressMIB.setContactInfo('Juergen Schoenwaelder (Editor) TU Braunschweig Bueltenweg 74/75 38106 Braunschweig, Germany Phone: +49 531 391-3289 EMail: schoenw@ibr.cs.tu-bs.de Send comments to .') if mibBuilder.loadTexts: transportAddressMIB.setDescription('This MIB module provides commonly used transport address definitions. Copyright (C) The Internet Society (2002). This version of this MIB module is part of RFC 3419; see the RFC itself for full 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.setStatus('current') if mibBuilder.loadTexts: transportDomainUdpIpv4.setDescription('The UDP over IPv4 transport domain. The corresponding transport address is of type TransportAddressIPv4 for global IPv4 addresses.') transportDomainUdpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 2)) if mibBuilder.loadTexts: transportDomainUdpIpv6.setStatus('current') if mibBuilder.loadTexts: transportDomainUdpIpv6.setDescription('The UDP over IPv6 transport domain. The corresponding transport address is of type TransportAddressIPv6 for global IPv6 addresses.') transportDomainUdpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 3)) if mibBuilder.loadTexts: transportDomainUdpIpv4z.setStatus('current') if mibBuilder.loadTexts: transportDomainUdpIpv4z.setDescription('The UDP over IPv4 transport domain. The corresponding transport address is of type TransportAddressIPv4z for scoped IPv4 addresses with a zone index.') transportDomainUdpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 4)) if mibBuilder.loadTexts: transportDomainUdpIpv6z.setStatus('current') if mibBuilder.loadTexts: transportDomainUdpIpv6z.setDescription('The UDP over IPv6 transport domain. The corresponding transport address is of type TransportAddressIPv6z for scoped IPv6 addresses with a zone index.') transportDomainTcpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 5)) if mibBuilder.loadTexts: transportDomainTcpIpv4.setStatus('current') if mibBuilder.loadTexts: transportDomainTcpIpv4.setDescription('The TCP over IPv4 transport domain. The corresponding transport address is of type TransportAddressIPv4 for global IPv4 addresses.') transportDomainTcpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 6)) if mibBuilder.loadTexts: transportDomainTcpIpv6.setStatus('current') if mibBuilder.loadTexts: transportDomainTcpIpv6.setDescription('The TCP over IPv6 transport domain. The corresponding transport address is of type TransportAddressIPv6 for global IPv6 addresses.') transportDomainTcpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 7)) if mibBuilder.loadTexts: transportDomainTcpIpv4z.setStatus('current') if mibBuilder.loadTexts: transportDomainTcpIpv4z.setDescription('The TCP over IPv4 transport domain. The corresponding transport address is of type TransportAddressIPv4z for scoped IPv4 addresses with a zone index.') transportDomainTcpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 8)) if mibBuilder.loadTexts: transportDomainTcpIpv6z.setStatus('current') if mibBuilder.loadTexts: transportDomainTcpIpv6z.setDescription('The TCP over IPv6 transport domain. The corresponding transport address is of type TransportAddressIPv6z for scoped IPv6 addresses with a zone index.') transportDomainSctpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 9)) if mibBuilder.loadTexts: transportDomainSctpIpv4.setStatus('current') if mibBuilder.loadTexts: transportDomainSctpIpv4.setDescription('The SCTP over IPv4 transport domain. The corresponding transport address is of type TransportAddressIPv4 for global IPv4 addresses. This transport domain usually represents the primary address on multihomed SCTP endpoints.') transportDomainSctpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 10)) if mibBuilder.loadTexts: transportDomainSctpIpv6.setStatus('current') if mibBuilder.loadTexts: transportDomainSctpIpv6.setDescription('The SCTP over IPv6 transport domain. The corresponding transport address is of type TransportAddressIPv6 for global IPv6 addresses. This transport domain usually represents the primary address on multihomed SCTP endpoints.') transportDomainSctpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 11)) if mibBuilder.loadTexts: transportDomainSctpIpv4z.setStatus('current') if mibBuilder.loadTexts: transportDomainSctpIpv4z.setDescription('The SCTP over IPv4 transport domain. The corresponding transport address is of type TransportAddressIPv4z for scoped IPv4 addresses with a zone index. This transport domain usually represents the primary address on multihomed SCTP endpoints.') transportDomainSctpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 12)) if mibBuilder.loadTexts: transportDomainSctpIpv6z.setStatus('current') if mibBuilder.loadTexts: transportDomainSctpIpv6z.setDescription('The SCTP over IPv6 transport domain. The corresponding transport address is of type TransportAddressIPv6z for scoped IPv6 addresses with a zone index. This transport domain usually represents the primary address on multihomed SCTP endpoints.') transportDomainLocal = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 13)) if mibBuilder.loadTexts: transportDomainLocal.setStatus('current') if mibBuilder.loadTexts: transportDomainLocal.setDescription('The Posix Local IPC transport domain. The corresponding transport address is of type TransportAddressLocal. The Posix Local IPC transport domain incorporates the well-known UNIX domain sockets.') transportDomainUdpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 14)) if mibBuilder.loadTexts: transportDomainUdpDns.setStatus('current') if mibBuilder.loadTexts: transportDomainUdpDns.setDescription('The UDP transport domain using fully qualified domain names. The corresponding transport address is of type TransportAddressDns.') transportDomainTcpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 15)) if mibBuilder.loadTexts: transportDomainTcpDns.setStatus('current') if mibBuilder.loadTexts: transportDomainTcpDns.setDescription('The TCP transport domain using fully qualified domain names. The corresponding transport address is of type TransportAddressDns.') transportDomainSctpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 16)) if mibBuilder.loadTexts: transportDomainSctpDns.setStatus('current') if mibBuilder.loadTexts: transportDomainSctpDns.setDescription('The SCTP transport domain using fully qualified domain names. The corresponding transport address is of type TransportAddressDns.') class TransportDomain(TextualConvention, ObjectIdentifier): description = 'A value that represents a transport domain. Some possible values, such as transportDomainUdpIpv4, are defined in this module. Other possible values can be defined in other MIB modules.' status = 'current' class TransportAddressType(TextualConvention, Integer32): description = 'A value that represents a transport domain. This is the enumerated version of the transport domain registrations in this MIB module. The enumerated values have the following meaning: unknown(0) unknown transport address type udpIpv4(1) transportDomainUdpIpv4 udpIpv6(2) transportDomainUdpIpv6 udpIpv4z(3) transportDomainUdpIpv4z udpIpv6z(4) transportDomainUdpIpv6z tcpIpv4(5) transportDomainTcpIpv4 tcpIpv6(6) transportDomainTcpIpv6 tcpIpv4z(7) transportDomainTcpIpv4z tcpIpv6z(8) transportDomainTcpIpv6z sctpIpv4(9) transportDomainSctpIpv4 sctpIpv6(10) transportDomainSctpIpv6 sctpIpv4z(11) transportDomainSctpIpv4z sctpIpv6z(12) transportDomainSctpIpv6z local(13) transportDomainLocal udpDns(14) transportDomainUdpDns tcpDns(15) transportDomainTcpDns sctpDns(16) transportDomainSctpDns This textual convention can be used to represent transport domains in situations where a syntax of TransportDomain is unwieldy (for example, when used as an index). The usage of this textual convention implies that additional transport domains can only be supported by updating this MIB module. This extensibility restriction does not apply for the TransportDomain textual convention which allows MIB authors to define additional transport domains independently in other MIB modules.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)) namedValues = NamedValues(("unknown", 0), ("udpIpv4", 1), ("udpIpv6", 2), ("udpIpv4z", 3), ("udpIpv6z", 4), ("tcpIpv4", 5), ("tcpIpv6", 6), ("tcpIpv4z", 7), ("tcpIpv6z", 8), ("sctpIpv4", 9), ("sctpIpv6", 10), ("sctpIpv4z", 11), ("sctpIpv6z", 12), ("local", 13), ("udpDns", 14), ("tcpDns", 15), ("sctpDns", 16)) class TransportAddress(TextualConvention, OctetString): description = "Denotes a generic transport address. A TransportAddress value is always interpreted within the context of a TransportAddressType or TransportDomain value. Every usage of the TransportAddress textual convention MUST specify the TransportAddressType or TransportDomain object which provides the context. Furthermore, MIB authors SHOULD define a separate TransportAddressType or TransportDomain object for each TransportAddress object. It is suggested that the TransportAddressType or TransportDomain is logically registered before the object(s) which use the TransportAddress textual convention if they appear in the same logical row. The value of a TransportAddress object must always be consistent with the value of the associated TransportAddressType or TransportDomain object. Attempts to set a TransportAddress object to a value which is inconsistent with the associated TransportAddressType or TransportDomain must fail with an inconsistentValue error. When this textual convention is used as a syntax of an index object, there may be issues with the limit of 128 sub-identifiers specified in SMIv2, STD 58. In this case, the OBJECT-TYPE declaration MUST include a 'SIZE' clause to limit the number of potential instance sub-identifiers." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) class TransportAddressIPv4(TextualConvention, OctetString): description = 'Represents a transport address consisting of an IPv4 address and a port number (as used for example by UDP, TCP and SCTP): octets contents encoding 1-4 IPv4 address network-byte order 5-6 port number network-byte order This textual convention SHOULD NOT be used directly in object definitions since it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with TransportAddressType or TransportDomain as a pair.' status = 'current' 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 = inet_pton(socket.AF_INET, value[0]) + int2oct((value[1] >> 8) & 0xff) + int2oct(value[1] & 0xff) return OctetString.prettyIn(self, value) # Socket address syntax coercion def __asSocketAddress(self): if not hasattr(self, '__tuple_value'): v = self.asOctets() self.__tuple_value = ( inet_ntop(socket.AF_INET, v[:4]), oct2int(v[4]) << 8 | oct2int(v[5]), ) return self.__tuple_value def __iter__(self): return iter(self.__asSocketAddress()) def __getitem__(self, item): return self.__asSocketAddress()[item] class TransportAddressIPv6(TextualConvention, OctetString): description = 'Represents a transport address consisting of an IPv6 address and a port number (as used for example by UDP, TCP and SCTP): octets contents encoding 1-16 IPv6 address network-byte order 17-18 port number network-byte order This textual convention SHOULD NOT be used directly in object definitions since it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with TransportAddressType or TransportDomain as a pair.' status = 'current' 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 not has_ipv6: raise error.PySnmpError('IPv6 not supported by platform') if isinstance(value, tuple): value = inet_pton(socket.AF_INET6, value[0]) + int2oct((value[1] >> 8) & 0xff) + int2oct(value[1] & 0xff) return OctetString.prettyIn(self, value) # Socket address syntax coercion def __asSocketAddress(self): if not hasattr(self, '__tuple_value'): if not has_ipv6: raise error.PySnmpError('IPv6 not supported by platform') v = self.asOctets() self.__tuple_value = ( inet_ntop(socket.AF_INET6, v[:16]), oct2int(v[16]) << 8 | oct2int(v[17]), 0, # flowinfo 0) # scopeid return self.__tuple_value def __iter__(self): return iter(self.__asSocketAddress()) def __getitem__(self, item): return self.__asSocketAddress()[item] class TransportAddressIPv4z(TextualConvention, OctetString): description = 'Represents a transport address consisting of an IPv4 address, a zone index and a port number (as used for example by UDP, TCP and SCTP): octets contents encoding 1-4 IPv4 address network-byte order 5-8 zone index network-byte order 9-10 port number network-byte order This textual convention SHOULD NOT be used directly in object definitions since it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with TransportAddressType or TransportDomain as a pair.' status = 'current' displayHint = '1d.1d.1d.1d%4d:2d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(10, 10) fixedLength = 10 class TransportAddressIPv6z(TextualConvention, OctetString): description = 'Represents a transport address consisting of an IPv6 address, a zone index and a port number (as used for example by UDP, TCP and SCTP): octets contents encoding 1-16 IPv6 address network-byte order 17-20 zone index network-byte order 21-22 port number network-byte order This textual convention SHOULD NOT be used directly in object definitions since it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with TransportAddressType or TransportDomain as a pair.' status = 'current' 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): reference = 'Protocol Independent Interfaces (IEEE POSIX 1003.1g)' description = "Represents a POSIX Local IPC transport address: octets contents encoding all POSIX Local IPC address string The Posix Local IPC transport domain subsumes UNIX domain sockets. This textual convention SHOULD NOT be used directly in object definitions since it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with TransportAddressType or TransportDomain as a pair. When this textual convention is used as a syntax of an index object, there may be issues with the limit of 128 sub-identifiers specified in SMIv2, STD 58. In this case, the OBJECT-TYPE declaration MUST include a 'SIZE' clause to limit the number of potential instance sub-identifiers." status = 'current' displayHint = '1a' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 255) class TransportAddressDns(TextualConvention, OctetString): description = "Represents a DNS domain name followed by a colon ':' (ASCII character 0x3A) and a port number in ASCII. The name SHOULD be fully qualified whenever possible. Values of this textual convention are not directly useable as transport-layer addressing information, and require runtime resolution. As such, applications that write them must be prepared for handling errors if such values are not supported, or cannot be resolved (if resolution occurs at the time of the management operation). The DESCRIPTION clause of TransportAddress objects that may have TransportAddressDns values must fully describe how (and when) such names are to be resolved to IP addresses and vice versa. This textual convention SHOULD NOT be used directly in object definitions since it restricts addresses to a specific format. However, if it is used, it MAY be used either on its own or in conjunction with TransportAddressType or TransportDomain as a pair. When this textual convention is used as a syntax of an index object, there may be issues with the limit of 128 sub-identifiers specified in SMIv2, STD 58. In this case, the OBJECT-TYPE declaration MUST include a 'SIZE' clause to limit the number of potential instance sub-identifiers." status = 'current' displayHint = '1a' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 255) mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", transportDomainUdpIpv6=transportDomainUdpIpv6, TransportDomain=TransportDomain, transportDomainSctpDns=transportDomainSctpDns, PYSNMP_MODULE_ID=transportAddressMIB, TransportAddressType=TransportAddressType, transportDomainTcpIpv4=transportDomainTcpIpv4, TransportAddressIPv6z=TransportAddressIPv6z, transportDomainLocal=transportDomainLocal, TransportAddressLocal=TransportAddressLocal, transportDomainUdpIpv4=transportDomainUdpIpv4, transportDomainUdpIpv4z=transportDomainUdpIpv4z, transportDomains=transportDomains, transportDomainSctpIpv4=transportDomainSctpIpv4, TransportAddressIPv6=TransportAddressIPv6, TransportAddressDns=TransportAddressDns, transportDomainSctpIpv6z=transportDomainSctpIpv6z, transportAddressMIB=transportAddressMIB, transportDomainTcpIpv6z=transportDomainTcpIpv6z, transportDomainSctpIpv6=transportDomainSctpIpv6, transportDomainUdpDns=transportDomainUdpDns, transportDomainTcpIpv6=transportDomainTcpIpv6, transportDomainUdpIpv6z=transportDomainUdpIpv6z, TransportAddressIPv4=TransportAddressIPv4, transportDomainSctpIpv4z=transportDomainSctpIpv4z, transportDomainTcpIpv4z=transportDomainTcpIpv4z, TransportAddress=TransportAddress, transportDomainTcpDns=transportDomainTcpDns, TransportAddressIPv4z=TransportAddressIPv4z) pysnmp-4.4.12/pysnmp/smi/mibs/__init__.py000066400000000000000000000000731354244100700203110ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/smi/mibs/instances/000077500000000000000000000000001354244100700201675ustar00rootroot00000000000000pysnmp-4.4.12/pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py000066400000000000000000000016331354244100700231370ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # MibScalarInstance, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalarInstance') (pysnmpUsmDiscoverable, pysnmpUsmDiscovery, pysnmpUsmKeyType) = mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable', 'pysnmpUsmDiscovery', 'pysnmpUsmKeyType' ) __pysnmpUsmDiscoverable = MibScalarInstance(pysnmpUsmDiscoverable.name, (0,), pysnmpUsmDiscoverable.syntax) __pysnmpUsmDiscovery = MibScalarInstance(pysnmpUsmDiscovery.name, (0,), pysnmpUsmDiscovery.syntax) __pysnmpUsmKeyType = MibScalarInstance(pysnmpUsmKeyType.name, (0,), pysnmpUsmKeyType.syntax) mibBuilder.exportSymbols( "__PYSNMP-USM-MIB", pysnmpUsmDiscoverable=__pysnmpUsmDiscoverable, pysnmpUsmDiscovery=__pysnmpUsmDiscovery, pysnmpUsmKeyType=__pysnmpUsmKeyType ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py000066400000000000000000000022231354244100700235530ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py000066400000000000000000000020241354244100700226350ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py000066400000000000000000000020231354244100700232020ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py000066400000000000000000000042651354244100700241350ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py000066400000000000000000000010171354244100700242020ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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 ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py000066400000000000000000000166561354244100700225070ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # from sys import version from time import time from pysnmp import __version__ (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" % (__version__, version.replace('\n', ' ').replace('\r', ' ')))) __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 ) pysnmp-4.4.12/pysnmp/smi/mibs/instances/__init__.py000066400000000000000000000000731354244100700223000ustar00rootroot00000000000000# This file is necessary to make this directory a package. pysnmp-4.4.12/pysnmp/smi/rfc1902.py000066400000000000000000001275311354244100700167170ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # import sys from pysnmp.proto import rfc1902, rfc1905 from pysnmp.proto.api import v2c from pysnmp.smi.builder import ZipMibSource from pysnmp.smi.compiler import addMibCompiler from pysnmp.smi.error import SmiError from pyasn1.type.base import AbstractSimpleAsn1Item from pyasn1.error import PyAsn1Error from pysnmp import debug __all__ = ['ObjectIdentity', 'ObjectType', 'NotificationType'] class ObjectIdentity(object): """Create an object representing MIB variable ID. At the protocol level, MIB variable is only identified by an OID. However, when interacting with humans, MIB variable can also be referred to by its MIB name. The *ObjectIdentity* class supports various forms of MIB variable identification, providing automatic conversion from one to others. At the same time *ObjectIdentity* objects behave like :py:obj:`tuples` of py:obj:`int` sub-OIDs. See :RFC:`1902#section-2` for more information on OBJECT-IDENTITY SMI definitions. Parameters ---------- args initial MIB variable identity. Recognized variants: * single :py:obj:`tuple` or integers representing OID * single :py:obj:`str` representing OID in dot-separated integers form * single :py:obj:`str` representing MIB variable in dot-separated labels form * single :py:obj:`str` representing MIB name. First variable defined in MIB is assumed. * pair of :py:obj:`str` representing MIB name and variable name * pair of :py:obj:`str` representing MIB name and variable name followed by an arbitrary number of :py:obj:`str` and/or :py:obj:`int` values representing MIB variable instance identification. Other parameters ---------------- kwargs MIB resolution options(object): * whenever only MIB name is given, resolve into last variable defined in MIB if last=True. Otherwise resolves to first variable (default). Notes ----- Actual conversion between MIB variable representation formats occurs upon :py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` invocation. Examples -------- >>> from pysnmp.smi.rfc1902 import ObjectIdentity >>> ObjectIdentity((1, 3, 6, 1, 2, 1, 1, 1, 0)) ObjectIdentity((1, 3, 6, 1, 2, 1, 1, 1, 0)) >>> ObjectIdentity('1.3.6.1.2.1.1.1.0') ObjectIdentity('1.3.6.1.2.1.1.1.0') >>> ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0') ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0') >>> ObjectIdentity('SNMPv2-MIB', 'system') ObjectIdentity('SNMPv2-MIB', 'system') >>> ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> ObjectIdentity('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123) ObjectIdentity('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123) """ stDirty, stClean = 1, 2 def __init__(self, *args, **kwargs): self.__args = args self.__kwargs = kwargs self.__mibSourcesToAdd = self.__modNamesToLoad = None self.__asn1SourcesToAdd = self.__asn1SourcesOptions = None self.__state = self.stDirty self.__indices = self.__oid = self.__label = () self.__modName = self.__symName = '' self.__mibNode = None def getMibSymbol(self): """Returns MIB variable symbolic identification. Returns ------- str MIB module name str MIB variable symbolic name : :py:class:`~pysnmp.proto.rfc1902.ObjectName` class instance representing MIB variable instance index. Raises ------ SmiError If MIB variable conversion has not been performed. Examples -------- >>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0') >>> objectIdentity.resolveWithMib(mibViewController) >>> objectIdentity.getMibSymbol() ('SNMPv2-MIB', 'sysDescr', (0,)) >>> """ if self.__state & self.stClean: return self.__modName, self.__symName, self.__indices else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def getOid(self): """Returns OID identifying MIB variable. Returns ------- : :py:class:`~pysnmp.proto.rfc1902.ObjectName` full OID identifying MIB variable including possible index part. Raises ------ SmiError If MIB variable conversion has not been performed. Examples -------- >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.resolveWithMib(mibViewController) >>> objectIdentity.getOid() ObjectName('1.3.6.1.2.1.1.1.0') >>> """ if self.__state & self.stClean: return self.__oid else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def getLabel(self): """Returns symbolic path to this MIB variable. Meaning a sequence of symbolic identifications for each of parent MIB objects in MIB tree. Returns ------- tuple sequence of names of nodes in a MIB tree from the top of the tree towards this MIB variable. Raises ------ SmiError If MIB variable conversion has not been performed. Notes ----- Returned sequence may not contain full path to this MIB variable if some symbols are now known at the moment of MIB look up. Examples -------- >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.resolveWithMib(mibViewController) >>> objectIdentity.getOid() ('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr') >>> """ if self.__state & self.stClean: return self.__label else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def getMibNode(self): if self.__state & self.stClean: return self.__mibNode else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def isFullyResolved(self): return self.__state & self.stClean # # A gateway to MIBs manipulation routines # def addAsn1MibSource(self, *asn1Sources, **kwargs): """Adds path to a repository to search ASN.1 MIB files. Parameters ---------- *asn1Sources : one or more URL in form of :py:obj:`str` identifying local or remote ASN.1 MIB repositories. Path must include the *@mib@* component which will be replaced with MIB module name at the time of search. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` reference to itself Notes ----- Please refer to :py:class:`~pysmi.reader.localfile.FileReader`, :py:class:`~pysmi.reader.httpclient.HttpReader` and :py:class:`~pysmi.reader.ftpclient.FtpReader` classes for in-depth information on ASN.1 MIB lookup. Examples -------- >>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addAsn1Source('http://mibs.snmplabs.com/asn1/@mib@') ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> """ if self.__asn1SourcesToAdd is None: self.__asn1SourcesToAdd = asn1Sources else: self.__asn1SourcesToAdd += asn1Sources if self.__asn1SourcesOptions: self.__asn1SourcesOptions.update(kwargs) else: self.__asn1SourcesOptions = kwargs return self def addMibSource(self, *mibSources): """Adds path to repository to search PySNMP MIB files. Parameters ---------- *mibSources : one or more paths to search or Python package names to import and search for PySNMP MIB modules. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` reference to itself Notes ----- Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the `mibdump.py `_ tool. Examples -------- >>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs') ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> """ if self.__mibSourcesToAdd is None: self.__mibSourcesToAdd = mibSources else: self.__mibSourcesToAdd += mibSources return self # provides deferred MIBs load def loadMibs(self, *modNames): """Schedules search and load of given MIB modules. Parameters ---------- *modNames: one or more MIB module names to load up and use for MIB variables resolution purposes. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` reference to itself Examples -------- >>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB') ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> """ if self.__modNamesToLoad is None: self.__modNamesToLoad = modNames else: self.__modNamesToLoad += modNames return self # this would eventually be called by an entity which posses a # reference to MibViewController def resolveWithMib(self, mibViewController): """Perform MIB variable ID conversion. Parameters ---------- mibViewController : :py:class:`~pysnmp.smi.view.MibViewController` class instance representing MIB browsing functionality. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` reference to itself Raises ------ SmiError In case of fatal MIB hanling errora Notes ----- Calling this method might cause the following sequence of events (exact details depends on many factors): * ASN.1 MIB file downloaded and handed over to :py:class:`~pysmi.compiler.MibCompiler` for conversion into Python MIB module (based on pysnmp classes) * Python MIB module is imported by SNMP engine, internal indices created * :py:class:`~pysnmp.smi.view.MibViewController` looks up the rest of MIB identification information based on whatever information is already available, :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` class instance gets updated and ready for further use. Examples -------- >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> objectIdentity.resolveWithMib(mibViewController) ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> """ if self.__mibSourcesToAdd is not None: debug.logger & debug.flagMIB and debug.logger('adding MIB sources %s' % ', '.join(self.__mibSourcesToAdd)) mibViewController.mibBuilder.addMibSources( *[ZipMibSource(x) for x in self.__mibSourcesToAdd] ) self.__mibSourcesToAdd = None if self.__asn1SourcesToAdd is None: addMibCompiler(mibViewController.mibBuilder, ifAvailable=True, ifNotAdded=True) else: debug.logger & debug.flagMIB and debug.logger( 'adding MIB compiler with source paths %s' % ', '.join(self.__asn1SourcesToAdd)) addMibCompiler( mibViewController.mibBuilder, sources=self.__asn1SourcesToAdd, searchers=self.__asn1SourcesOptions.get('searchers'), borrowers=self.__asn1SourcesOptions.get('borrowers'), destination=self.__asn1SourcesOptions.get('destination'), ifAvailable=self.__asn1SourcesOptions.get('ifAvailable'), ifNotAdded=self.__asn1SourcesOptions.get('ifNotAdded') ) self.__asn1SourcesToAdd = self.__asn1SourcesOptions = None if self.__modNamesToLoad is not None: debug.logger & debug.flagMIB and debug.logger('loading MIB modules %s' % ', '.join(self.__modNamesToLoad)) mibViewController.mibBuilder.loadModules(*self.__modNamesToLoad) self.__modNamesToLoad = None if self.__state & self.stClean: return self MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTableColumn') self.__indices = () if isinstance(self.__args[0], ObjectIdentity): self.__args[0].resolveWithMib(mibViewController) if len(self.__args) == 1: # OID or label or MIB module debug.logger & debug.flagMIB and debug.logger('resolving %s as OID or label' % self.__args) try: # pyasn1 ObjectIdentifier or sequence of ints or string OID self.__oid = rfc1902.ObjectName(self.__args[0]) # OID except PyAsn1Error: # sequence of sub-OIDs and labels if isinstance(self.__args[0], (list, tuple)): prefix, label, suffix = mibViewController.getNodeName( self.__args[0] ) # string label elif '.' in self.__args[0]: prefix, label, suffix = mibViewController.getNodeNameByOid( tuple(self.__args[0].split('.')) ) # MIB module name else: modName = self.__args[0] mibViewController.mibBuilder.loadModules(modName) if self.__kwargs.get('last'): prefix, label, suffix = mibViewController.getLastNodeName(modName) else: prefix, label, suffix = mibViewController.getFirstNodeName(modName) if suffix: try: suffix = tuple([int(x) for x in suffix]) except ValueError: raise SmiError('Unknown object name component %r' % (suffix,)) self.__oid = rfc1902.ObjectName(prefix + suffix) else: prefix, label, suffix = mibViewController.getNodeNameByOid( self.__oid ) debug.logger & debug.flagMIB and debug.logger( 'resolved %r into prefix %r and suffix %r' % (self.__args, prefix, suffix)) modName, symName, _ = mibViewController.getNodeLocation(prefix) self.__modName = modName self.__symName = symName self.__label = label mibNode, = mibViewController.mibBuilder.importSymbols( modName, symName ) self.__mibNode = mibNode debug.logger & debug.flagMIB and debug.logger('resolved prefix %r into MIB node %r' % (prefix, mibNode)) if isinstance(mibNode, MibTableColumn): # table column if suffix: rowModName, rowSymName, _ = mibViewController.getNodeLocation( mibNode.name[:-1] ) rowNode, = mibViewController.mibBuilder.importSymbols( rowModName, rowSymName ) self.__indices = rowNode.getIndicesFromInstId(suffix) elif isinstance(mibNode, MibScalar): # scalar if suffix: self.__indices = (rfc1902.ObjectName(suffix),) else: if suffix: self.__indices = (rfc1902.ObjectName(suffix),) self.__state |= self.stClean debug.logger & debug.flagMIB and debug.logger('resolved indices are %r' % (self.__indices,)) return self elif len(self.__args) > 1: # MIB, symbol[, index, index ...] # MIB, symbol, index, index if self.__args[0] and self.__args[1]: self.__modName = self.__args[0] self.__symName = self.__args[1] # MIB, '' elif self.__args[0]: mibViewController.mibBuilder.loadModules(self.__args[0]) if self.__kwargs.get('last'): prefix, label, suffix = mibViewController.getLastNodeName(self.__args[0]) else: prefix, label, suffix = mibViewController.getFirstNodeName(self.__args[0]) self.__modName, self.__symName, _ = mibViewController.getNodeLocation(prefix) # '', symbol, index, index else: prefix, label, suffix = mibViewController.getNodeName(self.__args[1:]) self.__modName, self.__symName, _ = mibViewController.getNodeLocation(prefix) mibNode, = mibViewController.mibBuilder.importSymbols( self.__modName, self.__symName ) self.__mibNode = mibNode self.__oid = rfc1902.ObjectName(mibNode.getName()) prefix, label, suffix = mibViewController.getNodeNameByOid( self.__oid ) self.__label = label debug.logger & debug.flagMIB and debug.logger( 'resolved %r into prefix %r and suffix %r' % (self.__args, prefix, suffix)) if isinstance(mibNode, MibTableColumn): # table rowModName, rowSymName, _ = mibViewController.getNodeLocation( mibNode.name[:-1] ) rowNode, = mibViewController.mibBuilder.importSymbols( rowModName, rowSymName ) if self.__args[2:]: try: instIds = rowNode.getInstIdFromIndices(*self.__args[2:]) self.__oid += instIds self.__indices = rowNode.getIndicesFromInstId(instIds) except PyAsn1Error: raise SmiError('Instance index %r to OID conversion failure at object %r: %s' % ( self.__args[2:], mibNode.getLabel(), sys.exc_info()[1])) elif self.__args[2:]: # any other kind of MIB node with indices if self.__args[2:]: instId = rfc1902.ObjectName( '.'.join([str(x) for x in self.__args[2:]]) ) self.__oid += instId self.__indices = (instId,) self.__state |= self.stClean debug.logger & debug.flagMIB and debug.logger('resolved indices are %r' % (self.__indices,)) return self else: raise SmiError('Non-OID, label or MIB symbol') def prettyPrint(self): if self.__state & self.stClean: s = rfc1902.OctetString() return '%s::%s%s%s' % ( self.__modName, self.__symName, self.__indices and '.' or '', '.'.join([x.isSuperTypeOf(s, matchConstraints=False) and '"%s"' % x.prettyPrint() or x.prettyPrint() for x in self.__indices]) ) else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join([repr(x) for x in self.__args])) # Redirect some attrs access to the OID object to behave alike def __str__(self): if self.__state & self.stClean: return str(self.__oid) else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __eq__(self, other): if self.__state & self.stClean: return self.__oid == other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __ne__(self, other): if self.__state & self.stClean: return self.__oid != other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __lt__(self, other): if self.__state & self.stClean: return self.__oid < other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __le__(self, other): if self.__state & self.stClean: return self.__oid <= other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __gt__(self, other): if self.__state & self.stClean: return self.__oid > other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __ge__(self, other): if self.__state & self.stClean: return self.__oid > other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __nonzero__(self): if self.__state & self.stClean: return self.__oid != 0 else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __bool__(self): if self.__state & self.stClean: return bool(self.__oid) else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __getitem__(self, i): if self.__state & self.stClean: return self.__oid[i] else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __len__(self): if self.__state & self.stClean: return len(self.__oid) else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __add__(self, other): if self.__state & self.stClean: return self.__oid + other else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __radd__(self, other): if self.__state & self.stClean: return other + self.__oid else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __hash__(self): if self.__state & self.stClean: return hash(self.__oid) else: raise SmiError('%s object not properly initialized' % self.__class__.__name__) def __getattr__(self, attr): if self.__state & self.stClean: if attr in ('asTuple', 'clone', 'subtype', 'isPrefixOf', 'isSameTypeWith', 'isSuperTypeOf', 'getTagSet', 'getEffectiveTagSet', 'getTagMap', 'tagSet', 'index'): return getattr(self.__oid, attr) raise AttributeError(attr) else: raise SmiError('%s object not properly initialized for accessing %s' % (self.__class__.__name__, attr)) # A two-element sequence of ObjectIdentity and SNMP data type object class ObjectType(object): """Create an object representing MIB variable. Instances of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class are containers incorporating :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` class instance (identifying MIB variable) and optional value belonging to one of SNMP types (:RFC:`1902`). Typical MIB variable is defined like this (from *SNMPv2-MIB.txt*): .. code-block:: bash sysDescr OBJECT-TYPE SYNTAX DisplayString (SIZE (0..255)) MAX-ACCESS read-only STATUS current DESCRIPTION "A textual description of the entity. This value should..." ::= { system 1 } Corresponding ObjectType instantiation would look like this: .. code-block:: python ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386 box') In order to behave like SNMP variable-binding (:RFC:`1157#section-4.1.1`), :py:class:`~pysnmp.smi.rfc1902.ObjectType` objects also support sequence protocol addressing `objectIdentity` as its 0-th element and `objectSyntax` as 1-st. See :RFC:`1902#section-2` for more information on OBJECT-TYPE SMI definitions. Parameters ---------- objectIdentity : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` Class instance representing MIB variable identification. objectSyntax : Represents a value associated with this MIB variable. Values of built-in Python types will be automatically converted into SNMP object as specified in OBJECT-TYPE->SYNTAX field. Notes ----- Actual conversion between MIB variable representation formats occurs upon :py:meth:`~pysnmp.smi.rfc1902.ObjectType.resolveWithMib` invocation. Examples -------- >>> from pysnmp.smi.rfc1902 import * >>> ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')) ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), Null('')) >>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386') ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386') """ stDirty, stClean = 1, 2 def __init__(self, objectIdentity, objectSyntax=rfc1905.unSpecified): if not isinstance(objectIdentity, ObjectIdentity): raise SmiError('initializer should be ObjectIdentity instance, not %r' % (objectIdentity,)) self.__args = [objectIdentity, objectSyntax] self.__state = self.stDirty def __getitem__(self, i): if self.__state & self.stClean: return self.__args[i] else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def __str__(self): return self.prettyPrint() def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join([repr(x) for x in self.__args])) def isFullyResolved(self): return self.__state & self.stClean def addAsn1MibSource(self, *asn1Sources, **kwargs): """Adds path to a repository to search ASN.1 MIB files. Parameters ---------- *asn1Sources : one or more URL in form of :py:obj:`str` identifying local or remote ASN.1 MIB repositories. Path must include the *@mib@* component which will be replaced with MIB module name at the time of search. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectType` reference to itself Notes ----- Please refer to :py:class:`~pysmi.reader.localfile.FileReader`, :py:class:`~pysmi.reader.httpclient.HttpReader` and :py:class:`~pysmi.reader.ftpclient.FtpReader` classes for in-depth information on ASN.1 MIB lookup. Examples -------- >>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).addAsn1Source('http://mibs.snmplabs.com/asn1/@mib@') ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')) >>> """ self.__args[0].addAsn1MibSource(*asn1Sources, **kwargs) return self def addMibSource(self, *mibSources): """Adds path to repository to search PySNMP MIB files. Parameters ---------- *mibSources : one or more paths to search or Python package names to import and search for PySNMP MIB modules. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectType` reference to itself Notes ----- Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the `mibdump.py `_ tool. Examples -------- >>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs') ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')) >>> """ self.__args[0].addMibSource(*mibSources) return self def loadMibs(self, *modNames): """Schedules search and load of given MIB modules. Parameters ---------- *modNames: one or more MIB module names to load up and use for MIB variables resolution purposes. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectType` reference to itself Examples -------- >>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).loadMibs('IF-MIB', 'TCP-MIB') ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')) >>> """ self.__args[0].loadMibs(*modNames) return self def resolveWithMib(self, mibViewController, ignoreErrors=True): """Perform MIB variable ID and associated value conversion. Parameters ---------- mibViewController : :py:class:`~pysnmp.smi.view.MibViewController` class instance representing MIB browsing functionality. Other Parameters ---------------- ignoreErrors: :py:class:`bool` If `True` (default), ignore MIB object name or value casting failures if possible. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.ObjectType` reference to itself Raises ------ SmiError In case of fatal MIB hanling errora Notes ----- Calling this method involves :py:meth:`~pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` method invocation. Examples -------- >>> from pysmi.hlapi import varbinds >>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine ) >>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386') >>> objectType.resolveWithMib(mibViewController) ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386')) >>> str(objectType) 'SNMPv2-MIB::sysDescr."0" = Linux i386' >>> """ if self.__state & self.stClean: return self self.__args[0].resolveWithMib(mibViewController) MibScalar, MibTableColumn = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTableColumn') if not isinstance(self.__args[0].getMibNode(), (MibScalar, MibTableColumn)): if (ignoreErrors and not isinstance(self.__args[1], AbstractSimpleAsn1Item)): raise SmiError('MIB object %r is not OBJECT-TYPE (MIB not loaded?)' % (self.__args[0],)) self.__state |= self.stClean return self if isinstance(self.__args[1], (rfc1905.UnSpecified, rfc1905.NoSuchObject, rfc1905.NoSuchInstance, rfc1905.EndOfMibView)): self.__state |= self.stClean return self try: self.__args[1] = self.__args[0].getMibNode().getSyntax().clone(self.__args[1]) except PyAsn1Error: err = ('MIB object %r having type %r failed to cast value ' '%r: %s' % (self.__args[0].prettyPrint(), self.__args[0].getMibNode().getSyntax().__class__.__name__, self.__args[1], sys.exc_info()[1])) if (not ignoreErrors or not isinstance(self.__args[1], AbstractSimpleAsn1Item)): raise SmiError(err) if rfc1902.ObjectIdentifier().isSuperTypeOf(self.__args[1], matchConstraints=False): self.__args[1] = ObjectIdentity(self.__args[1]).resolveWithMib(mibViewController) self.__state |= self.stClean debug.logger & debug.flagMIB and debug.logger('resolved %r syntax is %r' % (self.__args[0], self.__args[1])) return self def prettyPrint(self): if self.__state & self.stClean: return '%s = %s' % (self.__args[0].prettyPrint(), self.__args[1].prettyPrint()) else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) class NotificationType(object): """Create an object representing SNMP Notification. Instances of :py:class:`~pysnmp.smi.rfc1902.NotificationType` class are containers incorporating :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` class instance (identifying particular notification) and a collection of MIB variables IDs that :py:class:`~pysnmp.entity.rfc3413.oneliner.cmdgen.NotificationOriginator` should gather and put into notification message. Typical notification is defined like this (from *IF-MIB.txt*): .. code-block:: bash linkDown NOTIFICATION-TYPE OBJECTS { ifIndex, ifAdminStatus, ifOperStatus } STATUS current DESCRIPTION "A linkDown trap signifies that the SNMP entity..." ::= { snmpTraps 3 } Corresponding NotificationType instantiation would look like this: .. code-block:: python NotificationType(ObjectIdentity('IF-MIB', 'linkDown')) To retain similarity with SNMP variable-bindings, :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects behave like a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances. See :RFC:`1902#section-2` for more information on NOTIFICATION-TYPE SMI definitions. Parameters ---------- objectIdentity : :py:class:`~pysnmp.smi.rfc1902.ObjectIdentity` Class instance representing MIB notification type identification. instanceIndex : :py:class:`~pysnmp.proto.rfc1902.ObjectName` Trailing part of MIB variables OID identification that represents concrete instance of a MIB variable. When notification is prepared, `instanceIndex` is appended to each MIB variable identification listed in NOTIFICATION-TYPE->OBJECTS clause. objects : dict Dictionary-like object that may return values by OID key. The `objects` dictionary is consulted when notification is being prepared. OIDs are taken from MIB variables listed in NOTIFICATION-TYPE->OBJECTS with `instanceIndex` part appended. Notes ----- Actual notification type and MIB variables look up occurs upon :py:meth:`~pysnmp.smi.rfc1902.NotificationType.resolveWithMib` invocation. Examples -------- >>> from pysnmp.smi.rfc1902 import * >>> NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3')) NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3'), (), {}) >>> NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), ObjectName('3.5')) NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3'), ObjectName('3.5'), {}) """ stDirty, stClean = 1, 2 def __init__(self, objectIdentity, instanceIndex=(), objects={}): if not isinstance(objectIdentity, ObjectIdentity): raise SmiError('initializer should be ObjectIdentity instance, not %r' % (objectIdentity,)) self.__objectIdentity = objectIdentity self.__instanceIndex = instanceIndex self.__objects = objects self.__varBinds = [] self.__additionalVarBinds = [] self.__state = self.stDirty def __getitem__(self, i): if self.__state & self.stClean: return self.__varBinds[i] else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.__objectIdentity, self.__instanceIndex, self.__objects) def addVarBinds(self, *varBinds): """Appends variable-binding to notification. Parameters ---------- *varBinds : :py:class:`~pysnmp.smi.rfc1902.ObjectType` One or more :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.NotificationType` reference to itself Notes ----- This method can be used to add custom variable-bindings to notification message in addition to MIB variables specified in NOTIFICATION-TYPE->OBJECTS clause. Examples -------- >>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown')) >>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0))) NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {}) >>> """ debug.logger & debug.flagMIB and debug.logger('additional var-binds: %r' % (varBinds,)) if self.__state & self.stClean: raise SmiError('%s object is already sealed' % self.__class__.__name__) else: self.__additionalVarBinds.extend(varBinds) return self def addAsn1MibSource(self, *asn1Sources, **kwargs): """Adds path to a repository to search ASN.1 MIB files. Parameters ---------- *asn1Sources : one or more URL in form of :py:obj:`str` identifying local or remote ASN.1 MIB repositories. Path must include the *@mib@* component which will be replaced with MIB module name at the time of search. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.NotificationType` reference to itself Notes ----- Please refer to :py:class:`~pysmi.reader.localfile.FileReader`, :py:class:`~pysmi.reader.httpclient.HttpReader` and :py:class:`~pysmi.reader.ftpclient.FtpReader` classes for in-depth information on ASN.1 MIB lookup. Examples -------- >>> NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}).addAsn1Source('http://mibs.snmplabs.com/asn1/@mib@') NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}) >>> """ self.__objectIdentity.addAsn1MibSource(*asn1Sources, **kwargs) return self def addMibSource(self, *mibSources): """Adds path to repository to search PySNMP MIB files. Parameters ---------- *mibSources : one or more paths to search or Python package names to import and search for PySNMP MIB modules. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.NotificationType` reference to itself Notes ----- Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the `mibdump.py `_ tool. Examples -------- >>> NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}).addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs') NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}) >>> """ self.__objectIdentity.addMibSource(*mibSources) return self def loadMibs(self, *modNames): """Schedules search and load of given MIB modules. Parameters ---------- *modNames: one or more MIB module names to load up and use for MIB variables resolution purposes. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.NotificationType` reference to itself Examples -------- >>> NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}).loadMibs('IF-MIB', 'TCP-MIB') NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}) >>> """ self.__objectIdentity.loadMibs(*modNames) return self def isFullyResolved(self): return self.__state & self.stClean def resolveWithMib(self, mibViewController, ignoreErrors=True): """Perform MIB variable ID conversion and notification objects expansion. Parameters ---------- mibViewController : :py:class:`~pysnmp.smi.view.MibViewController` class instance representing MIB browsing functionality. Other Parameters ---------------- ignoreErrors: :py:class:`bool` If `True` (default), ignore MIB object name or value casting failures if possible. Returns ------- : :py:class:`~pysnmp.smi.rfc1902.NotificationType` reference to itself Raises ------ SmiError In case of fatal MIB hanling errora Notes ----- Calling this method might cause the following sequence of events (exact details depends on many factors): * :py:meth:`pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib` is called * MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause, :py:class:`~pysnmp.smi.rfc1902.ObjectType` instances are created from MIB variable OID and `indexInstance` suffix. * `objects` dictionary is queried for each MIB variable OID, acquired values are added to corresponding MIB variable Examples -------- >>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown')) >>> notificationType.resolveWithMib(mibViewController) NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}) >>> """ if self.__state & self.stClean: return self self.__objectIdentity.resolveWithMib(mibViewController) self.__varBinds.append( ObjectType(ObjectIdentity(v2c.apiTrapPDU.snmpTrapOID), self.__objectIdentity).resolveWithMib(mibViewController, ignoreErrors) ) SmiNotificationType, = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType') mibNode = self.__objectIdentity.getMibNode() varBindsLocation = {} if isinstance(mibNode, SmiNotificationType): for notificationObject in mibNode.getObjects(): objectIdentity = ObjectIdentity(*notificationObject + self.__instanceIndex).resolveWithMib( mibViewController, ignoreErrors) self.__varBinds.append( ObjectType(objectIdentity, self.__objects.get(notificationObject, rfc1905.unSpecified)).resolveWithMib( mibViewController, ignoreErrors) ) varBindsLocation[objectIdentity] = len(self.__varBinds) - 1 else: debug.logger & debug.flagMIB and debug.logger( 'WARNING: MIB object %r is not NOTIFICATION-TYPE (MIB not loaded?)' % (self.__objectIdentity,)) for varBinds in self.__additionalVarBinds: if not isinstance(varBinds, ObjectType): varBinds = ObjectType(ObjectIdentity(varBinds[0]), varBinds[1]) varBinds.resolveWithMib(mibViewController, ignoreErrors) if varBinds[0] in varBindsLocation: self.__varBinds[varBindsLocation[varBinds[0]]] = varBinds else: self.__varBinds.append(varBinds) self.__additionalVarBinds = [] self.__state |= self.stClean debug.logger & debug.flagMIB and debug.logger('resolved %r into %r' % (self.__objectIdentity, self.__varBinds)) return self def prettyPrint(self): if self.__state & self.stClean: return ' '.join(['%s = %s' % (x[0].prettyPrint(), x[1].prettyPrint()) for x in self.__varBinds]) else: raise SmiError('%s object not fully initialized' % self.__class__.__name__) pysnmp-4.4.12/pysnmp/smi/view.py000066400000000000000000000303001354244100700165660ustar00rootroot00000000000000# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof # License: http://snmplabs.com/pysnmp/license.html # 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(object): def __init__(self, mibBuilder): self.mibBuilder = mibBuilder self.lastBuildId = -1 self.__mibSymbolsIdx = OrderedDict() # 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.clear() # Oid <-> label indices # This is potentially 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] 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'] prevOid = () baseLabel = () for key in oidToLabelIdx.keys(): keydiff = len(key) - len(prevOid) if keydiff > 0: if prevOid: if keydiff == 1: baseLabel = oidToLabelIdx[prevOid] else: baseLabel += key[-keydiff:-1] else: baseLabel = () elif keydiff < 0: baseLabel = () keyLen = len(key) i = keyLen - 1 while i: k = key[:i] if k in oidToLabelIdx: baseLabel = oidToLabelIdx[k] if i != keyLen - 1: baseLabel += key[i:-1] break 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 getOrderedModuleName(self, index): self.indexMib() modNames = self.__mibSymbolsIdx.keys() if modNames: return modNames[index] raise error.SmiError('No modules loaded at %s' % self) def getFirstModuleName(self): return self.getOrderedModuleName(0) def getLastModuleName(self): return self.getOrderedModuleName(-1) 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.%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 getOrderedNodeName(self, index, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError('No module %s at %s' % (modName, self)) if not mibMod['oidToLabelIdx']: raise error.NoSuchObjectError( str='No variables at MIB module %s at %s' % (modName, self) ) try: oid, label = mibMod['oidToLabelIdx'].items()[index] except KeyError: raise error.NoSuchObjectError( str='No symbol at position %s in MIB module %s at %s' % (index, modName, self) ) return oid, label, () def getFirstNodeName(self, modName=''): return self.getOrderedNodeName(0, modName) def getLastNodeName(self, modName=''): return self.getOrderedNodeName(-1, modName) 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 getOrderedTypeName(self, index, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError('No module %s at %s' % (modName, self)) if not mibMod['typeToModIdx']: raise error.NoSuchObjectError( str='No types at MIB module %s at %s' % (modName, self) ) t = mibMod['typeToModIdx'].keys()[index] return mibMod['typeToModIdx'][t], t def getFirstTypeName(self, modName=''): return self.getOrderedTypeName(0, modName) def getLastTypeName(self, modName=''): return self.getOrderedTypeName(-1, modName) 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) ) pysnmp-4.4.12/requirements.txt000066400000000000000000000000421354244100700164100ustar00rootroot00000000000000pysmi pycryptodomex pyasn1>=0.2.3 pysnmp-4.4.12/runtests.sh000077500000000000000000000013301354244100700153530ustar00rootroot00000000000000#!/usr/bin/env sh set -e PYTHON=${1:-python} for x in examples/hlapi/asyncore/sync/manager/cmdgen/*.py \ examples/hlapi/asyncore/sync/agent/ntforg/*.py \ examples/hlapi/asyncore/manager/cmdgen/*.py \ examples/hlapi/asyncore/agent/ntforg/*.py \ examples/v3arch/asyncore/manager/cmdgen/*.py \ examples/v3arch/asyncore/agent/ntforg/*.py \ examples/v1arch/asyncore/manager/cmdgen/*.py \ examples/v1arch/asyncore/agent/ntforg/*.py \ examples/smi/manager/*py \ examples/smi/agent/*.py do case "${x}" in *spoof*|*ipv6*) echo "skipping ${x}" continue ;; *) $PYTHON "${x}" | tail -50 ;; esac done pysnmp-4.4.12/setup.cfg000066400000000000000000000001031354244100700147430ustar00rootroot00000000000000[bdist_wheel] universal = 1 [metadata] license_file = LICENSE.rst pysnmp-4.4.12/setup.py000066400000000000000000000116711354244100700146500ustar00rootroot00000000000000#!/usr/bin/env python """SNMP library for Python SNMP v1/v2c/v3 engine and Standard Applications suite written in pure-Python. Supports Manager/Agent/Proxy roles, Manager/Agent-side MIBs, asynchronous operation and multiple network transports. """ import sys import os import re classifiers = """\ Development Status :: 5 - Production/Stable Environment :: Console Intended Audience :: Developers Intended Audience :: Education Intended Audience :: Information Technology Intended Audience :: System Administrators Intended Audience :: Telecommunications Industry License :: OSI Approved :: BSD License Natural Language :: English Operating System :: OS Independent Programming Language :: Python :: 2 Programming Language :: Python :: 2.4 Programming Language :: Python :: 2.5 Programming Language :: Python :: 2.6 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.2 Programming Language :: Python :: 3.3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Topic :: Communications Topic :: System :: Monitoring Topic :: System :: Networking :: Monitoring Topic :: Software Development :: Libraries :: Python Modules """ def howto_install_setuptools(): print(""" Error: You need setuptools Python package! It's very easy to install it, just type: wget https://bootstrap.pypa.io/ez_setup.py python ez_setup.py Then you could make eggs from this package. """) if sys.version_info[:2] < (2, 4): print("ERROR: this package requires Python 2.4 or later!") sys.exit(1) requires = [ln.strip() for ln in open('requirements.txt').readlines()] try: import setuptools setup, Command = setuptools.setup, setuptools.Command observed_version = [int(x) for x in setuptools.__version__.split('.')] required_version = [36, 2, 0] # NOTE(etingof): require fresh setuptools to build proper wheels # See also: https://hynek.me/articles/conditional-python-dependencies/ if ('bdist_wheel' in sys.argv and observed_version < required_version): print("ERROR: your wheels won't come out round with setuptools %s! " "Upgrade to %s and try again." % ( '.'.join([str(x) for x in observed_version]), '.'.join([str(x) for x in required_version]))) sys.exit(1) params = { 'install_requires': requires, 'zip_safe': True } except ImportError: if 'bdist_wheel' in sys.argv or 'bdist_egg' in sys.argv: howto_install_setuptools() sys.exit(1) from distutils.core import setup params = {} if sys.version_info[:2] > (2, 4): params['requires'] = [ re.sub(r'(.*?)([<>=!~]+)(.*)', r'\g<1>\g<2>(\g<3>)', r) for r in requires ] doclines = [x.strip() for x in (__doc__ or '').split('\n')] params.update({ 'name': 'pysnmp', 'version': open(os.path.join('pysnmp', '__init__.py')).read().split('\'')[1], 'description': doclines[0], 'long_description': '\n'.join(doclines[1:]), 'maintainer': 'Ilya Etingof ', 'author': 'Ilya Etingof', 'author_email': 'etingof@gmail.com', 'url': 'https://github.com/etingof/pysnmp', 'classifiers': [x for x in classifiers.split('\n') if x], 'platforms': ['any'], 'license': 'BSD', 'packages': ['pysnmp', 'pysnmp.smi', 'pysnmp.smi.mibs', 'pysnmp.smi.mibs.instances', 'pysnmp.carrier', 'pysnmp.carrier.asynsock', 'pysnmp.carrier.asynsock.dgram', 'pysnmp.carrier.asyncore', 'pysnmp.carrier.asyncore.dgram', 'pysnmp.carrier.twisted', 'pysnmp.carrier.twisted.dgram', 'pysnmp.carrier.asyncio', 'pysnmp.carrier.asyncio.dgram', 'pysnmp.entity', 'pysnmp.entity.rfc3413', 'pysnmp.entity.rfc3413.oneliner', 'pysnmp.hlapi', 'pysnmp.hlapi.asyncio', 'pysnmp.hlapi.asyncore', 'pysnmp.hlapi.asyncore.sync', 'pysnmp.hlapi.asyncore.sync.compat', 'pysnmp.hlapi.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.rfc7860', 'pysnmp.proto.secmod.rfc7860.auth', 'pysnmp.proto.secmod.eso', 'pysnmp.proto.secmod.eso.priv', 'pysnmp.proto.acmod', 'pysnmp.proto.proxy', 'pysnmp.proto.api'] }) setup(**params) pysnmp-4.4.12/tox.ini000066400000000000000000000001471354244100700144450ustar00rootroot00000000000000[envlist] envlist = py{26,27,33,34,35,36,37} [testenv] commands = {toxinidir}/runtests.sh {envpython}