pysnmp-4.2.5/0000755000076400001440000000000012222743671013177 5ustar ilyausers00000000000000pysnmp-4.2.5/TODO0000644000076400001440000000320212015432770013657 0ustar ilyausers00000000000000Sparse 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 'oneliner' API for v1arch, possibly compatible with v3arch API * 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. pysnmp-4.2.5/THANKS0000644000076400001440000000111711467346126014116 0ustar ilyausers00000000000000Many 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 Thanks to Python Software Foundation for granting financial support for the project. pysnmp-4.2.5/docs/0000755000076400001440000000000012222743671014127 5ustar ilyausers00000000000000pysnmp-4.2.5/docs/net-snmpd.conf0000644000076400001440000000331212133460700016670 0ustar ilyausers00000000000000# 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.2.5/docs/net-snmptrapd.conf0000755000076400001440000000413512044722501017567 0ustar ilyausers00000000000000# 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.2.5/docs/pysnmp-arch.gif0000644000076400001440000001574310317004222017052 0ustar ilyausers00000000000000GIF87aA,Aڋ޼H扦ʶ L ĢL*̦ JԪjܮ N (8HXhx)9IYiy *:JZjz `z0 Zk;KK+|[,l{L L]=l},],=\흮N*_;o1NhB# k0ĉ+Z1%;z)"K iʔ,1l9 _!UO+ YAf?a"t&,tt UҧSL֭/1YϜFug wWȖ%uPY_@{lW_w&Wlq Q,Zf*0s_sw{S/%6Ӡ/]=5C] z^VxdL}"~*{(^ښ;w{F}t[-Sjɫ>?_ݯ%]`fwW_d-^lE%Y u_0{"!lӘ7rvb~R0a#o9BA#*;Ə [lB$j$?L6iƓPNIeV^eHe^W)&(d9řhrOfr5gvމg{yɧ pğ*"=j!&â 5D*i^iVB+t)z¨ h$6㜫ʊjN֊c_ Бl&qJRϺԥD;γ-ftҸ~[;"X̄t)EֵEInȞU%U̢ pA[aG\`2 6찖OaE`ɅbZá!LZ hdVi'ΌſH~ݮ7ҋ2|LzE?x4^zڙigi{κ;C`|6W/FM;on>s~~W0)E_]{$$q2$Y A])xA1/p`7 x#C CpY'Wz!"lx>Jm`3 j"b($f,$JL&BR̤Cr\0qd,cD,O2@=q;kH;@x\'(uvcAJ4")qAh$$#y+YPraD&U8 o)u3*M4&Rws\v܉ @u`.uਘfKɊa=1EI>їcPBVA±by!f3N5a'oMLg `yϙ 8Ό';5ZЍLh҂d%5OѦ8*3L1 OezԨS0XBq@Qq99ma԰XGQ ||C֓uT*7WָtW00EVj0,6ߙXQ-ec;Wz>d#`q q^MVFU iϵ#[$`3g@s[d@ Cd]XӴMjqPӴrԭu{Zbnx6M:ժ2]me~HWr{}a(Acwsܶ.-/wRD8O ~wo-A’mp.|TVՙqZ iŠƕ EТA_hpœ5K<& fR4p]#֠DM>w nj`Ɂ|^RbsUh' .brE "qH9uQeŴ| ݕNI!CUcӧ/ A[JM<)h"J.u}C:a?i8UqB,v-(͚>b%:SU6 g-XFA½cfߺX&n#0iR7 -GޖvuYn-[}݃zpw/z;ݚ?Jcg|x(_''1N`Tu]=WpBd%ZH3T-8l^WCNSO\yB.fz3oL&⇀>K^mVVPm-]Q>glooq!6Rk=g x+frƙU,OPIGx~yqGay^<$;:ۣ8OkG _ :qoO_6ߍW}kO##(O;8{ [?, 藟}wMip8~/Qaq:x-N+fQ]5%_(KdȁXx)5 w$Hm)G,_t>09W;D1o-ȃ3Z96iDXUF UcKJ8_CD6OxYPhZ&(R׃~kg8;@؆YqxtGt(gw{d'h|.s36D8HqC.Ĉ[3H Hc]Ɖ.S:>Z1؊HxeBX AXpᇋHS#rXk!&ňv|wҸy^?Œ֨X<<8`#+UqH?88HXZXA%Z[)}8HE* iGEY@s9`@$0 - !)#))p&kӐ,*DӒ3e>5::(7UÓc?C7H )Ei/ɔ5O (FUf棔^Y_ip()c)=]93hebȖJoẓ S'su$|/M)]c+d'NYsPY V bG(iKBx90zx&yI1g1NT2fe_=}jњFU'52C 3P$)UA8TBwoQV}awY1ttCMe"@g׉CbяKUѢ7:Piwp 3 yfR}'&oNw8%sٚt1ǘ%DacYTCUI ph(ui +jed 9.ڠ wx\v::UIjw}K rNUd2` q)^1uQfT)58^ l aFOsI&f]@ f[U*t<[6SEBGRʘ .;$aq9UiW8JV7}jnJʧL: vZ<3UZڞi}22*x׶yiՖ1 A6f4Ac5rNUďJwhcty5ng bIIŧ0=*Av_f)KkMIJevSYDz3 نt͊[$F)҄Za9!w(qAnj(k6Fk:I=y+;k^y5)HK;aL&䨴Q7{[Uk㴗[Xjz͊N]'xob^@c-S$5yZkRx5ٷk;+wHhӸ A:9ٸıKYO ~kkk5ħ3v(?bsȵWYBKo+4ynqVnuʕ|dD;O 0ػ_a Eh%q܋2.ù5f;nxB[`,龷{}| @+Of)ܿa۝ (=:`ȅ [[L;ȧ79, ܗlD̂eF>RETK+K'1f,,* ۼL~"ͬ6\,b|͵ 77z`I.̳ l,L,aI|:Т;[M"ϳӫѥ"Hj6Hډ󦌀)"ҕc[9Uj( z} :?f*dD76/<Օ$]?URV}v>< iUT# N[x8ƮwÁz:PMO1Miyw7]W@f;xFMl5_]DRv؜B$L"Q5U 5 ȰzLip~ݙSj7iï*}KZ9>"v=ӂűK8\Wծhu*b*5b|WZs*)g,[Ms-h:޿S,k]Nb\w%NS MOJ}՗o!Zm֝T"j1f٠g*q}MB*]<)<.T$&Rʝ|ax@>=U=ԐGNէrс}@h6N,BfUjLTP(a JRйlYn;MVcB}f~ͼ"n N4y}eqXf7RKMX/4^Uꏞ >`ÉְNo-݀݀4O{QnM19t!-uu۞Bvׄt䙞g}ӽmW낋^ݳG䴾6ͨ *[iKŞ련I/ ʎ>R~/.l1n42/m!q.S)NW~ bhz.Ծ:?"/[.^B>&W`Y]dO`ӨӋ.= H[:[ܾ=O@P;MZOWN?{$S ?}?O?jaśo^?8; dޓBP \p>)+0̐DtP3 P9\oB D'[Ap0N8lqAG4ϢNlH!XO {4q {Y1' ME 'rF'\SA P*CO^-OIӅ/E?iIs}l` wQm$asiR䊩cb[⊿L`(;YRz+!7Wf(~8gw@gG~ᣋR׋UץzC8W[ܐͩ[tɮf;{N[d"0sY6_ ZXHT\[+IV` \ 7ꯧZ1r VBbWL2gVxWoySgrsu3~eWxkFLJ,7: evȂnjۡ: dKYl' ]KDGAs訖3HG xaN~B, F A0De݋]@0|.Dbx>dKUtC q{x4aRبEQ(R̂u7Iۇ(4B*r\lc5&e܁cψF1Q{[8 *K 9HBj.L6^''Pr\4)QJUt+aKYΒ-qK]/La41Le.t3MiNc;pysnmp-4.2.5/docs/pysnmp-tutorial.html0000644000076400001440000034316012023344175020206 0ustar ilyausers00000000000000 PySNMP tutorial

PySNMP tutorial

by Ilya Etingof, 2007-2012

Table of contents

Applicable to PySNMP 4.2.3 and later.

1. Network management basics

As networks become more complex, in terms of device population, topology and distances, it has been getting more and more important for network administrators to have some easy and convenient way for controlling all pieces of the whole network.

Basic features of a network management system include device information retrieval and device remote control. Former often takes shape of gathering device operation statistics, while latter can be seen in device remote configuration facilities.

For any information to be exchanged between entities, some agreement on information format and transmission procedure needs to be settled beforehand. This is what is conventionally called a Protocol.

Large networks nowdays, may host thousands of different devices. To benefit network manager's interoperability and simplicity, any device on the network should carry out most common and important management operations in a well known, unified way. Therefore, an important feature of a network management system would be a Convention on management information naming and presentation.

Sometimes, management operations should be performed on large number of managed devices. For a network manager to complete such a management round in a reasonably short period of time, an important feature of a network management software would be Performance.

Some of network devices may run on severely limited resources what invokes another property of a proper network management facility: Low resource consumption.

In practice, the latter requirement translates into low CPU cycles and memory footprint for management software aboard device being managed.

As networking becomes a more crucial part of our daily lives, security issues have become more apparent. As a side note, even Internet technologies, having military roots, did not pay much attention to security initially. So, the last key feature of network management appears to be Security.

Data passed back and forth through the course of management operations should be at least authentic and sometimes hidden from possible observers.

All these problems were approached many times through about three decades of networking history. Some solutions collapsed over time for one reason or another, while others, such as Simple Network Management Protocol (SNMP), evolve into an industry standard.

1.1 SNMP management architecture

The SNMP management model includes three distinct entities -- Agent, Manager and Proxy talking to each other over network.

Agent entity is basically a software running somewhere in a networked device and having the following distinguishing properties:

  • SNMP protocol support
  • Access to managed device's internals

The latter feature is a source of management information for Agent, as well as a target for remote control operations.

Modern SNMP standards suggest splitting Agent functionality on two parts. Such Agents may run SNMP for local processes called Subagents, which interface with managed devices internals. Communication between Master Agent and its Subagents is performed using a simplified version of original SNMP protocol, known as AgentX, which is designed to run only within a single host.

Manager entity is usually an application used by humans (or daemons) for performing various network management tasks, such as device statistics retrieval or remote control.

Sometimes, Agents and Managers may run peer-to-peer within a single entity that is called Proxy. Proxies can often be seen in application-level firewalling or may serve as SNMP protocol translators between otherwise SNMP version-incompatible Managers and Agents.

For Manager to request Agent for an operation on a particular part of managed device, some convention on device's components naming is needed. Once some components are identified, Manager and Agent would have to agree upon possible components' states and their semantics.

SNMP approach to both problems is to represent each component of a device as a named object, similar to named variables seen in programming languages, and state of a component maps to a value associated with this imaginary variable. These are called Managed Objects in SNMP.

For representing a group of similar components of a device, such as network interfaces, Managed Objects can be organized into a so-called conceptual table.

Manager talks to Agent by sending it messages of several types. Message type implies certain action to be taken. For example, GET message instructs Agent to report back values of Managed Objects whose names are indicated in message.

There's also a way for Agent to notify Manager of an event occurred to Agent. This is done through so-called Trap messages. Trap message also carries Managed Objects and possibly Values, but besides that it has an ID of event in form of integer number or a Managed Object.

For naming Managed Objects, SNMP uses the concept of Object Identifier. As an example of Managed Object, .iso.org.dod.internet.mgmt.mib-2.system.sysName.0 represents human-readable name of a device where Agent is running.

Managed Objects values are always instances of ASN.1 types (such as Integer) or SNMP-specific subtypes (such as IpAddress). As in programming languages, type has an effect of restricting possible set of states Managed Object may ever enter.

Whenever SNMP entities talk to each other, they refer to Managed Objects whose semantics (and value type) must be known in advance by both parties. SNMP Agent may be seen as a primary source of information on Managed Objects, as they are implemented by Agent. In this model, Manager should have a map of Managed Objects contained within each Agent to talk to.

SNMP standard introduces a set of ASN.1 language constructs (such as ASN.1 subtypes and MACROs) which is called Structure of Management Information (SMI). Collections of related Managed Objects described in terms of SMI comprise Management Information Base (MIB) modules.

Commonly used Managed Objects form core MIBs that become part of SNMP standard. The rest of MIBs are normally created by vendors who build SNMP Agents into their products.

More often then not, Manager implementations could parse MIB files and use Managed Objects information for names resolution, value type determination, pretty printing and so on. This feature is known as MIB parser support.

1.2 The history of SNMP

First SNMP version dates back to 1988 when a set of IETF RFC's were first published ( RFC1065, RFC1066, RFC1067 ). These documents describe protocol operations (in terms of message syntax and semantics), SMI and a few core MIBs. The first version appears to be lightweight and easy to implement. Although, its poor security became notorious over years (Security? Not My Problem!), because cleartext password used for authentication (AKA Community String) is extremely easy to eavesdrop and replay, even after almost 20 years, slightly refined standard ( RFC1155, RFC1157, RFC1212 ) still seems to be the most frequent encounter in modern SNMP devices.

In effort to fix security issues of SNMPv1 and to make protocol faster for operations on large number of Managed Objects, SNMP Working Group at IETF came up with SNMPv2. This new protocol offers bulk transfers of Managed Objects information (by means of new, GETBULK message payload), improved security and re-worked SMI. But its new party-based security system turned out to be too complicated. In the end, security part of SNMPv2 has been dropped in favor of community-based authentication system used in SNMPv1. The result of this compromise is known as SNMPv2c (where "c" stands for community) and is still widely supported without being a standard ( RFC1902, RFC1903, RFC1904, RFC1905, RFC1906, RFC1907, RFC1908 ).

The other compromise targeted at offering greater security than SNMPv1, without falling into complexities of SNMPv2, has been attempted by replacing SNMPv2 party-based security system with newly developed user-based security model. This variant of protocol is known as SNMPv2u. Although neither widely implemented nor standardized, User Based Security Model (USM) of SNMPv2u got eventually adopted as one of possibly many SNMPv3 security models.

As of this writing, SNMPv3 is current standard for SNMP. Although it's based heavily on previous SNMP specifications, SNMPv3 offers many innovations but also brings significant complexity. Additions to version 3 are mostly about protocol operations. SMI part of standard is inherited intact from SNMPv2.

SNMPv3 system is designed as a framework that consists of a core, known as Message and PDU Dispatcher, and several abstract subsystems: Message Processing Subsystem (MP), responsible for SNMP message handling, Transport Dispatcher, used for carrying over messages, and Security Subsystem, which deals with message authentication and encryption issues. The framework defines subsystems interfaces to let feature-specific modules to be plugged into SNMPv3 core thus forming particular feature-set of SNMP system. Typical use of this modularity feature could be seen in multiprotocol systems -- legacy SNMP protocols are implemented as version-specific MP and security modules. Native SNMPv3 functionality relies upon v3 message processing and User-Based Security modules.

Besides highly detailed SNMP system specification, SNMPv3 standard also defines a typical set of SNMP applications and their behavior. These applications are Manager, Agent and Proxy ( RFC3411, RFC3412, RFC3413, RFC3414, RFC3415, RFC3416, RFC3417, RFC3418 ).

2. Programming with PySNMP

PySNMP is a pure-Python SNMP engine implementation. This software deals with the darkest corners of SNMP specifications all in Python programming language.

This paper is dedicated to PySNMP revisions 4.2.3 and up. Since PySNMP API's evolve over time, older revisions may provide slightly different interfaces than those described in this tutorial. Please refer to release-specific documentation for a more precise information.

From Programmer's point of view, the layout of PySNMP software reflects SNMP protocol evolution. It has been written from ground up, from trivial SNMPv1 up to fully featured SNMPv3. Therefore, several levels of API to SNMP functionality are available:

  • The most ancient 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.

  • Parts of SNMPv3 standard is expressed in terms of some abstract API to SNMP engine and its components. PySNMP implementation adopts this abstract API to a great extent, so it's available at Programmer's disposal. As a side effect, SNMP RFCs could be referenced for API semantics when programming PySNMP at this level.

    This API is much more higher-level than previous; here Programmer would have to manage two major issues: setting up Local Configuration Datastore (LCD) of SNMP engine and build/parse PDUs. PySNMP system is shipped multi-lingual, thus at this level all SNMPv1, SNMPv2c and SNMPv3 features are available.

  • At last, the highest-level API to SNMP functionality is available through the use of standard SNMPv3 applications. These applications cover the most frequent needs. That's why this API is expected to be the first to start with.

    The Applications API further simplifies Programmer's job by hiding LCD management issues (contrary to SNMPv3 engine level). This API could be exploited in a oneliner fashion, for quick and simple prototyping.

As for its internal structure, PySNMP consists of a handful of large, dedicated components. They normally take shape of classes which turn into linked objects at runtime. So here are the main components:

  • SNMP Engine is an object holding references to all 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 a heart of SNMP system. 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. All MP Modules share standard API used by Message And PDU Dispatcher.

  • 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 serving Agent Applications or Trap receiver in Manager Applications.

  • A collection of dedicated Managed Objects Instances are used by PySNMP for its internal purposes. They are collectively called Local Configuration Datastore (LCD). In PySNMP, all SNMP engine configuration and statistics is kept in LCD. LCD Configurator is a wrapper aimed at simplifying LCD operations.

In most cases user is expected to only deal with the top-leve oneliner API to all these PySNMP components. However implementing SNMP Agents, Proxies and some other fine features of Managers require using the Standard Applications API. In those cases general understanding of SNMP operations and SNMP Engine components would be helpful.

2.1 One-line Applications

As of this writing, oneliner Applications support generating Manager-side GET/SET/GETNEXT/GETBULK and issuing Agent-side TRAP/INFORM messages. Agent and Manager side responders are more complex and rarely used to fit them into the concise oneliner API so these should be implemented on top of standard SNMP Applications API.

There're two kinds of APIs to oneline Applications: synchronous and asynchronous. They are very similar in terms of their API and behaviour, both are implemented by the pysnmp.entity.rfc3413.oneliner.cmdgen module. The asynchronous version is more suited for massively parallel SNMP messaging.

2.1.1 Synchronous One-line Applications

This is the simplest and the most high-level API to standard SNMP Applications. It's advised to employ for singular and blocking operations as well as for rapid prototyping.

2.1.1.1 Command Generator

All Command Generator Applications are implemented by a single class:

class CommandGenerator([snmpEngine])

Create a SNMP Command Generator object.

Although instantiation of this class is cheap, in the course of its further use, SNMP engine configuration is built and maintained though methods invocation. Therefore it is advised to keep and reuse CommandGenerator instance (or snmpEngine instance if passed as an initializer) for as long as possible within user applicatin.

Methods of the CommandGenerator class instances implement specific request types.

getCmd( authData, transportTarget, *varNames, lookupNames=False, lookupValues=False )

Perform SNMP GET request and return a response or error indication.

The authData is a SNMP Security Parameters object, transportTarget is a SNMP Transport Configuration object and *varNames is a sequence of Managed Objects names.

The getCmd method returns a tuple of errorIndication, errorStatus, errorIndex, varBinds.

Non-empty errorIndication string indicates SNMP engine-level error.

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

The varBinds is a sequence of Managed Objects. Those found in response are bound by position to Managed Object names passed in request.

If lookupNames parameter evaluates to True, PySNMP will attempt to gather more information on Managed Objects returned in varBinds by searching for relevant MIB module and looking up there. Instance of MibVariable class will be returned as Managed Object names.

If lookupValues parameter evaluates to True, Managed Objects Instances values returned in varBinds may be converted into a more precise type (employing TEXTUAL-CONVENTION data from MIB) if PySNMP has relevant MIB loaded. Otherwise response values will belong to protocol-level Managed Object Instance value types.

The following code performs SNMP GET operation

  • using SNMP v2c
  • with community name 'public'
  • over IPv4/UDP
  • against an Agent listening at localhost (UDP port 161)
  • requesting two Managed Object Instances specified by name in string form

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',
    '1.3.6.1.2.1.1.6.0'
)

# Check for errors and print out results
if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex)-1] or '?'
            )
        )
    else:
        for name, val in varBinds:
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
setCmd( authData, transportTarget, *varBinds, lookupNames=False, lookupValues=False )

Perform SNMP SET request and return a response or error indication.

The authData, transportTarget, lookupNames and lookupValues parameters have the same semantics as in getCmd method.

The *varBinds input parameter is a sequence of Managed Objects to be modified at the Agent.

The setCmd method returns a tuple of errorIndication, errorStatus, errorIndex, varBinds. having the same meaning as in getCmd method.

The following code performs SNMP SET operation

  • using SNMP v3
  • with username 'usr-md5-des', MD5 authentication and DES privacy protocols
  • over IPv4/UDP
  • against an Agent listening at localhost (UDP port 161)
  • setting SNMPv2-MIB::sysName.0 object to a new value

The MibVariable object is used on input to allow symbolic Managed Object Instance name specification. Response names are requested to be returned also in form of a MibVariable object and response values converted into MIB-defined type.

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd(
    cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    (cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0), 'my new value'),
    lookupNames=True, lookupValues=True
)

# Check for errors and print out results
if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBinds[int(errorIndex)-1] or '?'
            )
        )
    else:
        for name, val in varBinds:
            print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
nextCmd( authData, transportTarget, *varNames, lookupNames=False, lookupValues=False, lexicographicMode=False, ignoreNonIncreasingOid=False, maxRows=0 )

Perform SNMP GETNEXT request and return a response or error indication. The GETNEXT request type implies referring to Managed Objects whose Object Names are "next greater" to those used in request.

The authData, transportTarget, lookupNames and lookupValues parameters have the same semantics as in getCmd method.

The *varNames parameter is a sequence of Managed Objects names to query Agent for their "next" greater neignbours' Managed Objects Instances values. Unlike the same-named parameter of getCmd method, a partial (prefix part of) Managed Objects names are allowed here. For instance, a '1.3.6.1' argument would ask the Agent to report Managed Object Instance value with the next greater name known to this Agent (which may turn out to be '1.3.6.1.2.1.1.1.0').

The nextCmd method returns a tuple of errorIndication, errorStatus, errorIndex, varBindTable.

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

The varBindTable parameter is a sequence of varBinds. Each varBind of varBinds in varBindTable represent a set of Managed Objects whose Object Names reside inside OID sub-tree of Managed Object name passed in request. In other words, with this oneliner API, an invocation of nextCmd method for a single Managed Object might return a sequence of Managed Objects so that Object Name passed in request would be a prefix for Object Names returned in response (as a side note, the same method in Applications API would return varBinds as held in a single response, and regardless of the prefix property).

It's possible to modify the above behaviour so that the varBindTable returned would contain *all* Managed Objects from those passed in request up to the end of the list of available Managed Objects at the Agent. This option is enabled by passing the lexicographicMode=True parameter to nextCmd method.

In some cases application is also interested in some contiguous set of Managed Objects Instances not necessarily strictly belonging to the same subtree. The maxRows=NNN parameter to nextCmd would stop Command Generator once the required number (NNN) of Managed Objects Instances are retrieved from the Agent.

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

The following code performs SNMP GETNEXT operation against a MIB subtree

  • using SNMP v1
  • with community name 'public'
  • over IPv4/UDP
  • against an Agent listening at localhost (UDP port 161)
  • for some columns of the IF-MIB::ifEntry table
  • stop reading values from Agent once response names leave the scopes of initial names (e.g. OBJECT IDENTIFIER's)

The MibVariable object is used on input to allow symbolic MIB table columns specification. Response values are requested to be converted into MIB-defined type.

Note: the code below needs access to IF-MIB (e.g. IF-MIB.py) which is installed with the pysnmp-mibs package or could be converted manually into pysnmp MIB module from IF-MIB text source.

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
    cmdgen.CommunityData('public', mpModel=0),
    cmdgen.UdpTransportTarget(('localhost', 161)),
    cmdgen.MibVariable('IF-MIB', 'ifDescr'),
    cmdgen.MibVariable('IF-MIB', 'ifType'),
    cmdgen.MibVariable('IF-MIB', 'ifMtu'),
    cmdgen.MibVariable('IF-MIB', 'ifSpeed'),
    cmdgen.MibVariable('IF-MIB', 'ifPhysAddress'),
    lookupValues=True
)

if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
            )
        )
    else:
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
bulkCmd( authData, transportTarget, nonRepeaters, maxRepetitions, *varNames, lookupNames=False, lookupValues=False, lexicographicMode=False, ignoreNonIncreasingOid=False, maxRows=0 )

Perform SNMP GETBULK request and return a response or error indication. The GETBULK request type has the same semantics as GETNEXT one except that the latter is able to report multiple Managed Objects per each Managed Object name passed in request.

The authData, transportTarget, *varNames, lookupNames, lookupValues, lexicographicMode and maxRows input parameters to the bulkCmd method are the same as of nextCmd.

The nonRepeaters parameter indicates how many of *varNames passed in request should be queried for a single instance with in a request.

The maxRepetitions parameter indicates for how many instances of Managed Objects in the rest of *varNames, besides first nonRepeaters ones, should be queried within a single request.

The bulkCmd method returns a tuple of errorIndication, errorStatus, errorIndex, varBindTable. having same meaning as in nextCmd method.

The following code performs SNMP GETBULK operation against a MIB subtree

  • using SNMP v3
  • with SNMPv3, user 'usr-sha-aes128', SHA auth, AES128 privacy
  • over IPv6/UDP
  • against an Agent listening at ::1 (UDP port 161)
  • with values non-repeaters = 0, max-repetitions = 20
  • for the SNMPv2-MIB::system subtree
  • stop reading values from Agent once response names leave the scopes of initial names (e.g. OBJECT IDENTIFIER's)

The MibVariable object is used on input to allow symbolic MIB table columns specification.

from pysnmp.entity.rfc3413.oneliner import cmdgen

cmdGen = cmdgen.CommandGenerator()

errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
    cmdgen.UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1',
                       authProtocol=cmdgen.usmHMACSHAAuthProtocol,
                       privProtocol=cmdgen.usmAesCfb128Protocol),
    cmdgen.Udp6TransportTarget(('::1', 161)),
    0, 20,
    cmdgen.MibVariable('SNMPv2-MIB', 'system')
)

if errorIndication:
    print(errorIndication)
else:
    if errorStatus:
        print('%s at %s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
            )
        )
    else:
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))

2.1.1.2 Notification Originator

The Notification Originator Application is implemented within a single class:

class NotificationOriginator([snmpContext])

Create a SNMP Notification Originator object.

Although instantiation of this class is cheap, in the course of its further use, SNMP engine configuration is built and maintained though methods invocation. Therefore it is advised to keep and reuse NotificationOriginator instance (or snmpEngine instance if passed as an initializer) for as long as possible within user applicatin.

All notifications are sent by in invocation of the following method:

sendNotification( authData, transportTarget, notifyType, notificationType, *varBinds )

Send either unconfirmed (TRAP) or confirmed (INFORM) SNMP notification and possibly return an error indication.

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

The notifyType parameter determines the type of notification to be generated. Supported values include "trap" for unconfirmed notification or "inform" for a confirmed one.

The notificationType parameter indicates the kind of event to notify Manager about in form of SMI NOTIFICATION-TYPE object name. Either ObjectIdentifier class instance, its initialization value (like '1.3.6.1.6.3.1.1.5.1') or MibVariable object can be used on input to allow MIB symbols references. For example, '1.3.6.1.6.3.1.1.5.1' or MibVariable('SNMPv2-MIB', 'coldStart') specify SNMPv2-MIB::coldStart type of trap.

When sending SNMP v1 traps, the notificationType parameter encodes both Generic and Specific trap numbers hardwired into SNMP v1 TRAP PDU, but missing in SNMP v2c TRAP and INFORM PDUs.

notificationType GenericTrap SpecificTrap
1.3.6.1.6.3.1.1.5.1coldStart(0)0
1.3.6.1.6.3.1.1.5.2warmStart(1)0
1.3.6.1.6.3.1.1.5.3linkDown(2)0
1.3.6.1.6.3.1.1.5.4linkUp(3)0
1.3.6.1.6.3.1.1.5.5authenticationFailure(4)0
1.3.6.1.6.3.1.1.5.6egpNeighborLoss(5)0
1.3.6.1.6.3.1.1.5.0.1enterpriseSpecific(6)1
1.3.6.1.6.3.1.1.5.0.999enterpriseSpecific(6)999
1.3.6.1.6.3.1.1.5.0.NenterpriseSpecific(6)N

The *varBinds input parameter is a tuple of Managed Objects to be passed over to Manager along with Notification. The syntax of *varBinds is the same as in getCmd

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

When sending SNMP traps to a SNMPv1 system, PDU parameters that are present in SNMPv1 PDU but are missing in SNMPv2c PDU are mapped one to another via special Managed Objects Inctance values in *varBinds.

  • SNMP v1 PDU enterprise parameter is passed as a value of 1.3.6.1.6.3.1.1.4.3.0 Managed Object Instance in *varBinds. If not specified, the default value is 1.3.6.1.6.3.1.1.5. If Generic encoded in notificationType is enterpriseSpecific, the enterprise parameter is implicitly initialized into notificationType value minus trailing sub-OID.
  • SNMP v1 PDU agent-addr parameter is passed as a value of 1.3.6.1.6.3.18.1.3.0 Managed Object Instance in *varBinds.
  • SNMP v1 PDU time-stamp parameter is passed as a value of 1.3.6.1.2.1.1.3.0 Managed Object Instance in *varBinds.

The following code sends SNMP v2c TRAP message:

  • using SNMP v2c
  • with community name 'public'
  • over IPv4/UDP
  • send TRAP notification
  • with TRAP ID 'coldStart' specified as a MIB symbol
  • include managed object information specified as a MIB symbol

from pysnmp.entity.rfc3413.oneliner import ntforg

ntfOrg = ntforg.NotificationOriginator()

errorIndication = ntfOrg.sendNotification(
    ntforg.CommunityData('public'),
    ntforg.UdpTransportTarget(('localhost', 162)),
    'trap',
    ntforg.MibVariable('SNMPv2-MIB', 'coldStart'),
    (ntforg.MibVariable('SNMPv2-MIB', 'sysName', 0), 'new name')
)

if errorIndication:
    print('Notification not sent: %s' % errorIndication)

To send SNMP v1 traps using standard Notification Originator application API, one may need to pass, and possibly override some of defaulted, SNMP v1 PDU fields that are not present as such in SNMP v2c PDU and thus in the API.

The following example sends SNMP v1 TRAP message overriding implicit defaults:

  • using SNMP v1
  • with community name 'public'
  • over IPv4/UDP
  • send TRAP notification
  • with Generic Trap #6 (enterpriseSpecific) and Specific Trap 432
  • overriding local snmpEngine's Uptime with value 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' specified as an OID-value pair

from pysnmp.entity.rfc3413.oneliner import ntforg
from pysnmp.proto import rfc1902

ntfOrg = ntforg.NotificationOriginator()

errorIndication = ntfOrg.sendNotification(
    ntforg.CommunityData('public', mpModel=0),
    ntforg.UdpTransportTarget(('localhost', 162)),
    'trap',
    '1.3.6.1.4.1.20408.4.1.1.2.0.432',
    ('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', rfc1902.OctetString('my system'))
)

if errorIndication:
    print('Notification not sent: %s' % errorIndication)

The following code sends SNMP v2c INFORM message over SNMPv3:

  • using SNMP v3
  • with user 'usr-md5-des', auth: MD5, priv 3DES
  • 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' specified as an OID-value pair

from pysnmp.entity.rfc3413.oneliner import ntforg
from pysnmp.proto import rfc1902

ntfOrg = ntforg.NotificationOriginator()

errorIndication = ntfOrg.sendNotification(
    ntforg.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
    ntforg.UdpTransportTarget(('localhost', 162)),
    'inform',
    '1.3.6.1.6.3.1.1.5.2',
    ('1.3.6.1.2.1.1.5.0', rfc1902.OctetString('system name'))
)

if errorIndication:
    print('Notification not sent: %s' % errorIndication)

2.1.2 Asynchronous One-line Applications

Asynchronous API to oneliner Applications is actually a foundation for Synchronous version, so they're very similar. This Asynchronous API is useful for purposes such as running multiple, possibly different, SNMP Applications at the same time or handling other activities inside user's program while SNMP Application is waiting for input/output.

2.1.2.1 Asynchronous Command Generator

All Command Generator Applications are implemented within a single class:

class AsynCommandGenerator([snmpEngine])

Create an asynchronous SNMP Command Generator object.

Although instantiation of this class is cheap, in the course of its further use, SNMP engine configuration is built and maintained though methods invocation. Therefore it is advised to keep and reuse CommandGenerator instance (or snmpEngine instance if passed as an initializer) for as long as possible within user applicatin.

Methods of the AsynCommandGenerator class instances implement specific request types. These methods are similar to those described in the CommandGenerator class section except that asynchronous interface uses a callback function for delivering responses.

getCmd( authData, transportTarget, varNames, (cbFun, cbCtx), lookupNames=False, lookupValues=False )

Prepare SNMP GET request to be dispatched. Return the sendRequestHandle value.

The cbFun parameter is a reference to a callable object (such as a Python function) having the following signature:

cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx )

Where sendRequestHandle is an integer value used for matching response to request. Its counterpart is returned on request submission by the getCmd method.

The cbCtx parameter is a reference to the cbCtx object being passed to getCmd method. Its purpose is to carry opaque application's state from request through response methods.

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

The authData, transportTarget, varNames, lookupNames and lookupValues parameters have the same meaning as in getCmd method except that varNames is passed as a sequence, not as individual Managed Objects Instances names.

The getCmd method returns unique sendRequestHandle integer value used for matching subsequent response to this request.

The following code performs multiple, simultaneous SNMP GET operations for multiple Managed Objects Instances to a single Agent. Authentication information used in this example are the same for all targets. So the GET operation is performed:

  • using SNMP v2c
  • with SNMPv2c community 'public'
  • over IPv4/UDP
  • against an Agent listening at 127.0.0.1
  • for the SNMPv2-MIB::sysDescr.0, SNMPv2-MIB::sysLocation.0 and SNMPv2-MIB::sysName.0 objects

from pysnmp.entity.rfc3413.oneliner import cmdgen

def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
          varBinds, cbCtx):
    if errorIndication:
        print(errorIndication)
        return
    if errorStatus:
        print('%s at %s' % \
            (errorStatus.prettyPrint(),
             errorIndex and varBinds[int(errorIndex)-1] or '?')
        )
        return
    
    for oid, val in varBinds:
        if val is None:
            print(oid.prettyPrint())
        else:
            print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

cmdGen  = cmdgen.AsynCommandGenerator()

for varName in ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
                 cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0),
                 cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0) ):
    cmdGen.getCmd(
        cmdgen.CommunityData('public'),
        cmdgen.UdpTransportTarget(('127.0.0.1', 161)),
        (varName,),
        (cbFun, None)
    )

cmdGen.snmpEngine.transportDispatcher.runDispatcher()

It is trivial to modify the above code to make it using different SNMP versions, credentials and query different Managed Objects Instances per each target.

All queries are made in parallel, so with default timeout and retries settings, the above code will terminate in 6 seconds regardless of Agents avialability and responsiveness.

setCmd( authData, transportTarget, varBinds, (cbFun, cbCtx), lookupNames=False, lookupValues=False )

Prepare SNMP SET request to be dispatched. Return the sendRequestHandle value.

The authData, transportTarget, varNames, lookupNames and lookupValues parameters have the same meaning as in setCmd.

The cbFun and cbCtx parameters have the same meaning as in AsynCommandGenerator.getCmd method.

nextCmd( authData, transportTarget, varNames, (cbFun, cbCtx), lookupNames=False, lookupValues=False )

Prepare SNMP GETNEXT request to be dispatched. Return the sendRequestHandle value.

The authData, transportTarget, varNames, lookupNames and lookupValues parameters have the same meaning as in nextCmd method except that varNames is passed as a sequence, not as individual Managed Objects Instances names.

The cbFun and cbCtx parameters have the same meaning as in AsynCommandGenerator.getCmd method. Appliction can indicate to GETNEXT SNMP Application that it is no more interested in further information from Agent and wishes to stop by returning True from the cbFun. Otherwise it should return False.

The varNames parameter has the same meaning as in CommandGenerator.nextCmd method except that here it is passed in as a tuple.

The following code performs multiple, simultaneous SNMP GETNEXT operations against distinct Agents identified by their transport addresses. Authentication information and queried Managed Objects Instances used in this example are the same for all targets. So the GETNEXT operation is performed:

  • using SNMP v3
  • with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols
  • over IPv4/UDP
  • against Agents listening at 127.0.0.1, 192.168.1.1, 10.40.1.1 (port 161)
  • for the SNMPv2-MIB::system subtree

from pysnmp.entity.rfc3413.oneliner import cmdgen

def cbFun(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] or '?')
        )
        return
    
    for varBindRow in varBindTable:
        for oid, val in varBindRow:
            if val is None:
                return    # stop table retrieval
            else:
                print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))

    return True  # continue table retrieval

cmdGen  = cmdgen.AsynCommandGenerator()

for transportTarget in ( cmdgen.UdpTransportTarget(('127.0.0.1', 161)),
                         cmdgen.UdpTransportTarget(('192.168.1.1', 161)),
                         cmdgen.UdpTransportTarget(('10.40.1.1', 161)) ):
    cmdGen.nextCmd(
        cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
        transportTarget,
        ( cmdgen.MibVariable('SNMPv2-MIB', 'system'), ),
        (cbFun, None)
    )

cmdGen.snmpEngine.transportDispatcher.runDispatcher()
bulkCmd( authData, transportTarget, nonRepeaters, maxRepetitions, varNames, (cbFun, cbCtx), lookupNames=False, lookupValues=False )

Prepare SNMP GETBULK request to be dispatched. Return the sendRequestHandle value.

The authData, transportTarget, nonRepeaters, maxRepetitions varNames, lookupNames and lookupValues parameters have the same meaning as in bulkCmd method except that varNames is passed as a sequence, not as individual Managed Objects Instances names.

The cbFun and cbCtx parameters have the same meaning as in AsynCommandGenerator.nextCmd method.

After one or more requests have been submitted by calling one or more of the methods above, Transport Dispatcher must be invoked to get SNMP engine running. This is done by calling:

asynCommandGenerator.snmpEngine.transportDispatcher.runDispatcher ()

Where asynCommandGenerator is AsynCommandGenerator class instance.

The runDispatcher() method terminates when no pending requests left for running Applications.

2.1.2.2 Asynchronous Notification Originator

The Notification Originator Application is implemented within a single class:

class AsynNotificationOriginator([snmpContext])

Create an asynchronous SNMP Notification Originator object.

The only method of AsynNotificationOriginator class is similar to that described in the NotificationOriginator class section except that asynchronous interface uses a callback function for delivery confirmation when confirmed notification are used.

sendNotification( authData, transportTarget, notifyType, notificationType, varBinds, (cbFun, cbCtx) )

Prepare SNMP TRAP or INFORM notification to be dispatched. Return the sendRequestHandle value.

The cbFun parameter is a reference to a callable object (such as Python function) that takes the following parameters:

cbFun( sendRequestHandle, errorIndication, cbCtx )

Where the sendRequestHandle, errorIndication and cbCtx parameters have the same meaning as in callback function in AsynCommandGenerator.getCmd method.

The cbCtx parameter has the same meaning as in AsynCommandGenerator.getCmd method.

The notifyType, notificationType and varBinds parameters have the same meaning as in NotificationOriginator.sendNotification method except that here it is passed in as a tuple.

The sendNotification method returns unique sendRequestHandle integer value used for matching subsequent delivery confirmation response to arbitrary notification.

After one or more notifications have been submitted by calling the sendNotification method, Transport Dispatcher must be invoked to get SNMP engine running. This is done by calling:

asynNotificationOriginator.snmpEngine.transportDispatcher.runDispatcher ()

Where asynNotificationOriginator is AsynNotificationOriginator class instance.

The runDispatcher() method terminates when no unconfirmed notifications left for running Applications.

The following code sends multiple, simultaneous SNMP INFORM messages to multiple Managers. Authentication information used in this example is the same for all targets.

  • using SNMP v2c
  • with SNMPv2c community 'public'
  • over IPv4/UDP
  • against Managers listening at 127.0.0.1, 127.0.0.2, 127.0.0.3 (port 162)

from pysnmp.entity.rfc3413.oneliner import ntforg
from pysnmp.proto import rfc1902

def cbFun(sendRequestHandle, errorIndication, cbCtx):
    if errorIndication:
        print(errorIndication)
    else:
        print('INFORM %s delivered' % sendRequestHandle)

ntfOrg = ntforg.AsynNotificationOriginator()

for target in ( ntforg.UdpTransportTarget(('127.0.0.1', 162)),
                ntforg.UdpTransportTarget(('127.0.0.2', 162)),
                ntforg.UdpTransportTarget(('127.0.0.3', 162)) ):
    ntfOrg.sendNotification(
        ntforg.CommunityData('public'),
        target,
        'inform',
        ntforg.MibVariable('SNMPv2-MIB', 'coldStart'),
        ( ('1.3.6.1.2.1.1.5.0', rfc1902.OctetString('system name')), ),
        (cbFun, None)
    )

ntfOrg.snmpEngine.transportDispatcher.runDispatcher()

The above script terminates as all queries are either acknowledged or timed out. With default timeout and retries settings, this will happen in no longer than 6 seconds regardless of Managers avialability and responsiveness.

2.1.3 Security configuration

Calls to oneliner Applications API require Security Parameters and Transport configuration objects as input parameters. These classes serve as convenience shortcuts to SNMP engine configuration facilities and for keeping persistent authentication/transport configuration between SNMP engine calls.

Security Parameters object is Security Model specific. UsmUserData class serves SNMPv3 User-Based Security Model configuration, while CommunityData class is used for Community-Based Security Model of SNMPv1/SNMPv2c.

class UsmUserData( securityName, authKey='', privKey='', authProtocol=usmNoAuthProtocol, privProtocol=usmNoPrivProtocol )

Create an object holding User-Based Security Model specific configuration parameters.

Mandatory securityName parameter is SNMPv3 USM username passed in as a string.

Optional authKey parameter is a secret key (string typed) used within USM for SNMP PDU authorization. Setting it to a non-empty value implies MD5-based PDU authentication (usmHMACMD5AuthProtocol) to take effect. Default hashing method may be changed by means of further authProtocol parameter.

Optional privKey parameter is a secret key (string typed) used within USM for SNMP PDU encryption. Setting it to a non-empty value implies MD5-based PDU authentication (usmHMACMD5AuthProtocol) and DES-based encryption (usmDESPrivProtocol) to take effect. Default hashing and/or encryption methods may be changed by means of further authProtocol and/or privProtocol parameters.

Optional authProtocol parameter may be used to specify non-default hash function algorithm. Possible values include:

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

Optional privProtocol parameter may be used to specify non-default ciphering algorithm. Possible values include:

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

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

class CommunityData( communityName, mpModel=1 )

Create an object holding Community-Based Security Model specific configuration parameters.

Mandatory communityName parameter is SNMPv1/SNMPv2c Community name passed as a string.

Optional mpModel parameter indicates whether SNMPv2c (mpModel=1, default) or SNMPv1 (mpModel=0) protocol should be used.

2.1.4 Transport configuration

Transport configuration object is Transport domain specific. UdpTransportTarget class represents a remote network endpoint of a UDP-over-IPv4 transport.

class UdpTransportTarget( transportAddr, timeout=1, retries=5 )

Create an object representing a network path connecting two SNMP entities through a UDP/IPv4 socket.

Mandatory transportAddr parameter indicates remote address in form of a tuple of FQDN, port where FQDN is a string representing either hostname or IPv4 address in quad-dotted form, port is an integer.

Optional timeout and retries parameters may be used to modify default response timeout (1 second) and number of succesive request retries (5 times).

class Udp6TransportTarget( transportAddr, timeout=1, retries=5 )

Create an object representing a network path connecting two SNMP entities through a UDP/IPv6 socket.

Mandatory transportAddr parameter indicates remote address in form of a tuple of FQDN, port where FQDN is a string representing either hostname or IPv6 address in semicolon-separated form, port is an integer.

Optional timeout and retries parameters may be used to modify default response timeout (1 second) and number of succesive request retries (5 times).

2.2 Managed Objects names and values

On the protocol level, a Managed Object Instance is represented by a pair of Name and Value items collectively called a Variable-Binding. In PySNMP oneliner API, a Managed Object Instance is represented by a two-component sequence of two objects -- one represents Managed Object Name or Managed Object Instance Name, and the other - Managed Object Instance Value. The types of these objects may vary, details follow.

2.2.1 Managed Objects Names

Managed Object or Managed Object Instance Name is an instance of ObjectName class which is derived from PyASN1 ObjectIdentifier. In most cases, PySNMP oneliner API will automatically create an instance of ObjectName class from its initialization value which can be:

  • a plain string of dot-separated numbers, e.g. '1.3.6.1.2.1.1.1.0'
  • a tuple of integers e.g., (1, 3, 6, 1, 2, 1, 1, 1, 0)
  • an instance of ObjectIdentifier class or its derivative such as ObjectName

In order to make use of additional information related to Managed Objects, such as their human-friendly representation, associated value type, description of intended use and other details contained in MIBs, the MibVariable class instances may be used interchangeably instead of ObjectName objects.

class MibVariable( varName )

Create an object representing a varying amount of Managed Object Name information. At the bare minimum MibVariable object will only hold an OBJECT IDENTIFIER that identifies particular Managed Object. However more information on Managed Object may be gathered by PySNMP during the course of SNMP request processing. All the extra information comes through a lookup at a MIB where particular Managed Object is specified.

The mandatory varName argument must hold a valid initializer for ObjectIdentifier kind of objects.

or

class MibVariable( mibName, symName, *indices )

Create an object potentially representing all MIB information on particular Managed Object. By the moment of instantiation no additional information is acquired, but during the later stages of SNMP request processing, PySNMP will attempt to lookup additional information at the MIB named mibName for the object registered there under name symName.

If requested MIB or symbol can not be found, the PySnmpError exception will be thrown.

The mandatory mibName and symName arguments refer to the names under which particular Managed Object is specified in the MIB (e.g. 'IF-MIB' and 'ifTable' respectively). Both parameters are Python strings.

The optional indices sequence semantics depend on the type of MIB Object refered by mibName and symName parameters.

  • For MibTableColumn objects indices are a sequence of Conceptual Table Instance ID in a human-friendly form (e.g. "127.0.0.1"-indexed element of a IP-MIB::ipAdEntAddr column)
  • For MibScalar objects indices are interpreted as an sub-OBJECT IDENTIFIER

Methods of the MibVariable objects are as follows:

getMibSymbol( )

Return a sequence of mibName, symName and indices identifying arbitrary Managed Object.

getOid( )

Return Managed Object Name in form of ObjectIdentifier object.

getMibNode( )

Return MIB information in form of a Managed Object identified by this particular name.

isFullyResolved( )

Return True if MIB lookup for initial initializers was successful and complete MIB information is available.

2.2.2 Managed Objects Values

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

PySNMP implementation of SNMPv3 architecture always exposes, SMIv2 definitions for Managed Objects are always used regardless of the underlying SNMP protocol version being talked with a peer. For instance, an SNMPv3 Manager will always report SMIv2 types even when working to SNMPv1 Agent (which is SMIv1-compliant).

The list of Managed Object Instance Value classes follows.

class Integer( value )

Create a SMIv2 Integer object. The value parameter should be an integer value. Instances of this class mimic basic properties of a Python integer. SMIv2 Integer class is derived from PyASN1 Integer.

class Integer32( value )

Create a SMIv2 Integer32 object. This object is similar to Integer class instance.

class OctetIdentifier( value )

Create a SMIv2 OctetIdentifier object. The value parameter could be a tuple of integer sub-IDs or a human-friendly string form like ".1.3.6.1.3.1". SMIv2 OctetString class is derived from PyASN1 OctetIdentifier.

class OctetString( value )

Create a SMIv2 OctetString object. The value parameter should be a string value. Instances of this class mimic basic properties of a Python string. SMIv2 OctetString class is derived from PyASN1 OctetString.

class IpAddress( value )

Create a SMIv2 IpAddress object. The value parameter should be an IP address expressed in quad-dotted notation (e.g. "127.0.0.1"). SMIv2 IpAddress class is derived from PyASN1 OctetString.

class Counter32( value )

Create a SMIv2 Counter32 object. Besides different value constraints, this object is similar to Integer class instance.

class Gauge32( value )

Create a SMIv2 Gauge32 object. Besides different value constraints, this object is similar to Integer class instance.

class Unsigned32( value )

Create a SMIv2 Unsigned32 object. Besides different value constraints, this object is similar to Integer class instance.

class TimeTicks( value )

Create a SMIv2 TimeTicks object. Besides different value constraints, this object is similar to Integer class instance.

class Opaque( value )

Create a SMIv2 Opaque object. This object is similar to OctetString class instance.

class Counter64( value )

Create a SMIv2 Counter64 object. Besides different value constraints, this object is similar to Integer class instance.

class Bits( value )

Create a SMIv2 Bits object. The value parameter should be sequence of names of bits raised to one. Unmentioned bits default to zero. The Bits class is derived from PyASN1 OctetString.

All the above types are directly used by SNMP protocol and can be exchanged between user application and PySNMP in the course of SNMP engine operations through PySNMP APIs. However, by SNMP design, some additional information on specific Managed Objects Instances value ranges and human-friendly representation can be carried by MIBs in form of TEXTUAL-CONVENTION SMI constructs. PySNMP implements this feature in form of TextualConvention class which is actually a derivative of one of the above Managed Objects Instance Value classes so objects of these classes can be used interchangeably in all PySNMP APIs.

For more information on SNMP Managed Value objects properties, refer to their base classes in PyASN1 documentation.

2.3 MIB services

PySNMP supports both Manager and Agent-side operations on Managed Objects, including MIB lookup and custom Managed Objects implementation.

Managed Objects, implemented in Python code, is the basis for PySNMP MIB services. Managed Objects are collected into a pool and then managed by a MIB builder. Both Manager and Agent applications deal with their Managed Objects through role-specific MIB view and MIB instrumentation. The same set of Managed Objects could serve both Manager and Agent purposes within a single SNMP entity.

2.3.1 Data model for Managed Objects

In PySNMP, Managed Objects specified in MIBs take shape of Python objects that implement various kinds of SMIv2 definitions. Managed Objects specified in a MIB file translate in a one-to-one fashion into Python modules.

Automated conversion of MIB text files into Python modules can be done through the use of smidump tool of libsmi package and "build-pysnmp-mib" script shipped with PySNMP.

The pysnmp.smi.mibs.SNMPv2-SMI module implements the following classes:

class MibScalar( name, syntax )

A representation of a scalar Managed Object specification identified by name with associated value of type syntax. Objects of this kind never hold actual values, rather they serve the following purposes:

  • Logically bind Managed Object Name with Value
  • Specify value type (including TEXTUAL-CONVENTION-based constraints)
  • Provide human-friendly Managed Object name and value representation

The name parameter represents an Object Identifier which can be expressed as either a tuple of integers or tuple-like Object Identifier class instance.

The syntax parameter represents Managed Object Instance value type.

The MibScalar class implements the following methods:

getName()

Return the name initializer an OctetIdentifier object.

getSyntax()

Return the syntax initializer which is a PyASN1 object including its TEXTUAL-CONVENTION derivative. The syntax object does not carry any value, it denotes an acceptable type specifier and may be used for cloning compliant objects for building SNMP messages or pretty printing concrete values.

getUnits()

Return value units in form of a Python string. This is mostly used for pretty printing things like "10 seconds", not just "10".

getDescription()

Return a textual, human-readable description of the Managed Object semantics, meaning, uses and restrictions. Since these descriptions may be quite large, they are not loaded into memory by default. This setting can be altered through a property of MibBuilder.

class MibScalarInstance( name, syntax )

A representation of scalar Managed Object Instance or Conceptual Table element with name and associated value carried by the syntax object. This class is a subclass of MibScalar but, unlike MibScalar, it represents existing Managed Object holding a value.

The name of Managed Object Instance is a concatination of name of a Managed Object and instance identifier. For scalar Managed Objects, instance identifier is always a single zero (0,). For Conceptual Table elements instance identifier is a concatination of table indices.

The name and syntax parameters have the same meaning as in MibScalar class.

class MibTableColumn( name, syntax )

A representation of Conceptual Table Column specification with name and associated value of type syntax. This class is a subclass of MibScalar.

The name parameter has the same meaning as in MibScalar class.

The syntax parameter represents type of the value associated with columnar Managed Object.

The MibTableColumn class implements the following methods:

setProtoInstance( instanceClass )

Configure MibTableColumn object to instantiate instanceClass when creating Columnar Objects. By default, MibScalarInstance is instantiated.

class MibTableRow( name )

A representation of a Conceptual Table Row specification with name. This class is a subclass of MibScalar although it can't have any associated value.

The name parameter has the same meaning as in MibScalar class.

The MibTableRow class implements the following methods:

getInstIdFromIndices( *indices )

Compute and return Conceptual Table Column instance identifier from *indices using MIB Table Index definition.

Types of *indices must coerce into Table Index syntax.

getIndicesFromInstId( instanceId )

Compute and return a tuple of Conceptual Table Index values from Column instance identifier instanceId using MIB Table Index definition.

The number of types of returned index values depend on MIB Table definition.

class MibTable( name )

Represents Conceptual Table specification with name. This class is a subclass of MibScalar although it can't have any associated value.

The name parameter has the same meaning as in MibScalar class.

The following examples explain how MIB text could be expressed in terms of PySNMP SMI data model. First example is on a scalar:

myManagedObject = MibScalar((1, 3, 6, 1, 4, 1, 20408, 2, 1),
                            OctetString()).setMaxAccess("readonly")

Managed Object Instance can be put into a stand-alone PySNMP SMI module or be implemented inside Agent application. Managed Object Instance will be associated with its parent Managed Object, by the MIB building part of PySNMP, on the basis of their names relation.

myManagedObjectInstance = MibScalarInstance(myManagedObject.getName() + (0,), 
    myManagedObject.getSyntax().clone('my string'))

Let's consider SNMP Conceptual Table created in an "MY-MIB.py" file:

myTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 2, 1))
myTableEntry = MibTableRow(myTable.getName() + (1,)).setIndexNames(
                   (0, "MY-MIB", "myTableIndex")
               )
myTableIndex = MibTableColumn(myTableEntry.getName() + (1,), Integer())
myTableValue = MibTableColumn(myTableEntry.getName() + (2,), OctetString())

Populate Managed Objects table with Managed Objects Instance in the first column.

myTableValueInstance = MibScalarInstance(myTableValue.getName() + (1,), 
    myTableValue.getSyntax().clone('my value'))

For more real-life cases, refer to modules in pysnmp.smi.mibs sub-package.

2.3.2 MIB builder

The pythonized MIB modules are then managed by the MibBuilder class from pysnmp.smi.builder module.

class MibBuilder()

Create MIB modules loader/evaluator/indexer.

loadModules( *modNames )

Locate in search path and evaluate each of *modNames through Python execfile() passing a reference to MibBuilder class instance to module's global scope. Evaluating modules might register their objects at MibBuilder through exportSymbols() call.

MIB builder would then create an in-memory index of registered MIB objects by MIB names.

Search path is managed by the getMibPath() and setMibPath() methods.

The loadModules method may be further invoked recursively on dependent MIB modules import.

unloadModules( *modNames )

Drop all references to Python objects previously created through calling loadModules() method against [here optional] *modNames. This method would invoke unexportSymbols() against MIB symbols previously registered under each of *modNames.

Missing *modNames implies all currently loaded modules.

importSymbols( modName, *symNames )

Return a tuple of Managed Objects looked up by their MIB names *symNames. Managed Objects returned in tuple are position-bound to *symNames parameters.

If MIB module modName is not yet loaded, the importSymbols() method would be invoked implicitly.

exportSymbols( modName, *anonymousSyms, **namedSyms )

Register Managed Objects *anonymousSyms and/or **namedSyms at MibBuilder within MIB module modName scope.

Managed Objects defined in MIB are always named. These are exported using **namedSyms parameter(s). Managed Objects Instances don't have to have MIB names, unless Application wants to access Managed Objects Instances by MIB name, so these may be exported through *anonymousSyms.

unexportSymbols( modName, *symNames )

Drop all references to Python objects previously registered under *symNames within modName through exportSymbols() call.

Missing *symNames implies all symbols currently registered within modName module.

In the following example MIB builder will be created, MIB modules loaded up and Managed Object definition looked up by symbolic name:

>>> from pysnmp.smi import builder
>>>
>>> # create MIB builder
... mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'IF-MIB')
>>>
>>> # get Managed Object definition by symbol name
... mibNode, = mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr')
>>> print(mibNode.getName())
(1, 3, 6, 1, 2, 1, 1, 1)
>>> print(repr(mibNode.getSyntax()))
DisplayString('')
>>>

2.3.3 MIB view controller

The following facilities are intended for Manager-side access to MIB definitions. The pysnmp.smi.view module contains the following items:

class MibViewController(mibBuilder)

The MibViewController class instance tackles Managed Objects, constructed by MibBuilder, for their properties and provide efficient/ordered access to Managed Objects properties. Most important of these are OID names and labels.

The mibBuilder argument is an instance of MibBuilder class.

The MibViewController class implements the following methods:

getNodeName(name)

The name parameter is Managed Object name. It can be either a tuple representing sub-OIDs or Object Identifier class instance. Sub-OIDs can be a mix of integers and string labels. For example, the following are valid values of name:

  • (1, 3, 6, 1)
  • ('iso', 'org', 'dod', 'internet')
  • ('iso', 2, 'dod', 1)
  • pysnmp.proto.rfc1902.ObjectIdentifier("1.3.6.1")

The getNodeName method returns a tuple of (oid, label, suffix) where:

  • The oid and label are tuples of sub-OIDs of best (longest) matched Managed Object in integer and label forms respectively.
  • The suffix parameter is the unmatched, trailing part of original name parameter.

    If a Managed Object is looked up with getNodeName method and an exact match occured, suffix would be an empty tuple.

    If suffix is not empty, it indicates either an index part of Conceptual Table instance name (which can be further parsed into index values by MibTableRow class methods) or a partial Managed Object name match.

    In order to distinguish MIB Table element match from a failure, see if closest matched Managed Object oid (MIB symbol label[-1]) is an instance of MibTableColumn class.

    If even partial match fails, the SmiError exception is raised.

>>> from pysnmp.smi import builder, view
>>>
>>> mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB')
>>> mibViewController = view.MibViewController(mibBuilder)
>>> 
>>> oid, label, suffix = mibViewController.getNodeName(
                             (1,3,6,1,2,'mib-2',1,'sysDescr')
                         )
>>> print(oid)
(1, 3, 6, 1, 2, 1, 1, 1)
>>> print(label)
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>> print(suffix)
()

getNextNodeName( name, modName='' )

The getNextNodeName method works the same as getNodeName but it deals with Managed Object whose name appears to be next to the name given on input.

The modName parameter is MIB module name as seen by MibBuilder. Use this parameter to restrict by-name to particular MIB module's scope.

getFirstNodeName(modName='')

The getFirstNodeName method works the same as getNodeName but it returns Managed Object whose name appears to be the first among others within MIB module modName.

If no modName is given, the whole OID namespace is assumed.

getNodeLocation(name)

The getNodeLocation method returns MIB location of Managed Object by OID name as a tuple of (modName, mibName, suffix).

The modName and mibName parameters are as used in MibBuilder interface. The suffix parameter is as described in getNodeName() method.

>>> from pysnmp.smi import builder, view
>>>
>>> mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB')
>>> mibViewController = view.MibViewController(mibBuilder)
>>> 
>>> modName, symName, suffix = mibViewController.getNodeLocation(
                                   (1,3,6,1,2,1,1,1,123)
                               )
>>> print(modName)
SNMPv2-MIB
>>> print(symName)
sysDescr
>>> print(suffix)
(123,)

2.3.4 Implementing Managed Objects Instances

The following chapter explains SNMP Agent-controlled Managed Object Instances to real-life objects mapping.

SNMP defines four types of operations on Managed Objects Instances. For scalars, these are:

  • Get Managed Object Instance value (though SNMP GET request)
  • Modify Managed Object Instance value (though SNMP SET request)

Conceptual Tables additionaly support:

  • Table row creation (through SNMP SET against a special-purpose RowStatus column instance)
  • Table row removal (similary, through SNMP SET against RowStatus column instance)

PySNMP Managed Objects Instances are implemented by the MibScalarInstance objects while a value associated with Managed Object Instance is represented by its syntax initialization parameter.

There are two distinct approaches to Managed Objects Instances implementation in PySNMP. The first one is simpler to use but it only works for relatively static Managed Objects. The other is universal but it is more complex to deal with.

2.3.4.1 Associated value gatewaying

This method only works for scalars and static tables (meaning no row creation and deletion is performed through SNMP). Also, it is not safe with this method to modify dependent values though a single request as failed modification won't roll back others in the bulk.

Whenever SNMP Agent receives read or modification request against arbitrary Managed Object Instance, it ends up clone()'ing syntax parameter of MibScalarInstance object. Read queries (e.g. GET/GETNEXT/GETBULK) trigger clone method invocation without passing it new value, while new value will be fed to the clone method on modification request.

This value-based gatewaying method works by listening on the clone() method of MibScalarInstance associated value thus fetching current or applying new state of some outer system represented by arbitrary Managed Object Instance.

Consider SMI-to-filesystem gateway for example, where a Managed Object Instance would represent particular file contents. File contents would be solely dependent on SNMP updates.

class MyFile(OctetString):
  def clone(self, value=None):
    if value is not None:
      # SNMP SET
      open('/tmp/myfile', 'w').write(value)

    # SNMP S/GET*
    return OctetString.clone(self, open('/tmp/myfile', 'r').read())

mibBuilder.exportSymbols(
  'MYFILE-MIB', MibScalarInstance((1, 3, 6, 1, 4, 1, 20408, 1), MyFile())
)

A variation of this through-value SMI gatewaying method would be for a third-party system to keep Managed Object Instance value synchronized with system's current state. Take file size monitor for instance -- the following code would be run periodically to measure most recent file size and re-build its SMI projection:

myManagedObjectInstance = MibScalarInstance(
  (1, 3, 6, 1, 4, 1, 20408, 1), Integer(os.stat('/var/adm/messages')[6])
)

mibBuilder.exportSymbols(
  'FILESIZE-MIB', myManagedObjectInstance=myManagedObjectInstance
)

2.3.4.2 Tapping on Management Instrumentation API

This is a generic SMI Managed Objects Instances to real-life objects mapping method. It works for scalars and tables of any origin, though, programming with it involves customization of PySNMP SMI base classes what adds up to usage complexity.

A single SNMP request may invoke an operation on multiple Managed Objects Instances. In SNMP design, it must either succeed on all Managed Objects Instances or be rolled back and reported as a failure otherwise.

SNMP engine talks to its Managed Objects through a protocol which is comprised from a collection of API methods (further refered to as Management Instrumentation API), implemented by Managed Objects classes and a definite sequence of their invocation. Default handlers implemented in Managed Objects classes read/modify/create the syntax parameter, passed on instantiation, to MibScalarInstance objects for scalars and MibTableColumn for tables. The essence of this Management Instrumentation Tapping technique is to listen on Management Instrumentation API methods for gaining control over particular Managed Object at request processing points.

Formal parameters of Management Instrumentation API methods don't make much sense to custom implementation, so they are partially documented here and, in most cases, should be blindly passed down as-is to the overloaded method to not to interfere with behind-the-scene SMI workings.

Value read methods implemented by Managed Objects and invoked by SNMP engine in response to SNMP GET/GETNEXT/GETBULK requests are:

readTest( *args )

The readTest method is invoked by SNMP engine prior to performing actual Managed Object Instance value read to give implementation a chance to ensure that subsequent value read is likely to succeed.

readGet( *args )

The readGet method is invoked by SNMP engine to fetch Managed Object Instance's value. This method must return a tuple of (name, value) which is returned by overloaded method invocation. Custom implementation may replace the value part by its own version taken from third-party sources.

readTestNext( *args )

The readTestNext method is invoked by SNMP engine prior to performing actual Managed Object Instance value read to give implementation a chance to ensure that subsequent value read is likely to succeed.

readGetNext( *args )

The readGetNext method is invoked by SNMP engine to fetch Managed Object Instance's value. This method must return a tuple of (name, value) which is returned by overloaded method invocation. Custom implementation may replace the value part by its own version taken from third-party sources.

The following is a re-implementation of file size monitor:

class FileWatcherInstance(MibScalarInstance):
  def readTest(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.readTest(self, name, val, idx, (acFun, acCtx))
    try:
      os.stat('/var/adm/messages')
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def readGet(self, name, val, idx, (acFun, acCtx)):
    name, val = MibScalarInstance.readGet(self, name, val, idx, (acFun, acCtx))
    try:
      return name, val.clone(os.stat('/var/adm/messages')[6])
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

mibBuilder.exportSymbols(
  'FILESIZE-MIB', FileWatcherInstance((1,3,6,1,4,1,20408,1), Integer())
)

Value modification methods implemented by Managed Objects and invoked by SNMP engine in response to SNMP SET request:

writeTest( name, value, *args )

The writeTest method is invoked by SNMP engine prior to performing actual Managed Object Instance value modification to give implementation a chance to ensure that subsequent value modification is likely to succeed.

Upon successful completion, this method brings Managed Object Instance into a state of pending modification which ends through either calling writeCleanup() on success or writeUndo() on failure.

writeCommit( *args )

The writeCommit method is invoked by SNMP engine by way of request processing in attempt to apply pending value, previously passed to Managed Object Instance through writeTest method. Custom implementation may attempt to apply pending value to a third-party system.

writeCleanup( *args )

The writeCleanup method is invoked by SNMP engine by way of request processing to bring Managed Object Instance out of pending value modification state. Custom implementation may attempt to bring a third-party system out of value modification state.

writeUndo( *args )

The writeUndo method is invoked by SNMP engine by way of request processing to drop the value applied to Managed Object Instance by the previously called writeCommit() method and re-assign previous value. This method also brings Managed Object Instance out of pending value modification state. Custom implementation may attempt to bring a third-party system out of value modification state.

The following is a re-implementation of SMI-to-filesystem binding for file modification:

class MyFileInstance(MibScalarInstance):
  def writeTest(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.writeTest(self, name, val, idx, (acFun, acCtx))
    try:
      open('/tmp/myfile.new', 'w').write(val)
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def writeCommit(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.writeCommit(self, name, val, idx, (acFun, acCtx))
    try:
      os.rename('/tmp/myfile', '/tmp/myfile.old')
      os.rename('/tmp/myfile.new', /tmp/myfile')
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def writeCleanup(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.writeCleanup(self, name, val, idx, (acFun, acCtx))
    try:
      os.unlink('/tmp/myfile.old')
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def writeUndo(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.writeUndo(self, name, val, idx, (acFun, acCtx))
    try:
      os.rename('/tmp/myfile.old', '/tmp/myfile')
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

mibBuilder.exportSymbols(
  'MYFILE-MIB', MyFileInstance((1,3,6,1,4,1,20408,1), OctetString())
)

Table row creation methods implemented by Managed Objects and invoked by SNMP engine in response to SNMP SET request against a non-existent or SNMPv2-TC::RowStatus type Table Column Instance (table cell) object:

createTest( name, value, *args )

The createTest method is invoked by SNMP engine as a first step of Columnar Instance (e.g. Managed Object Instance) creation to make sure the column instance could be created and optionally supplied value is good. Custom implementation may attempt to create a new object at a third-party system.

The name and value parameters hold OID/value pair as arrived in request.

Upon successful completion, this method brings Managed Object Instance into a state of pending creation which ends through either calling createCleanup() on success or createUndo() on failure.

createCommit( *args )

The createCommit method is invoked by SNMP engine by way of Columnar Object creation to indicate that newly created Columnar Object has been brough on-line and in attempt to apply [optional] pending value, as passed through createTest() method. Custom implementation may bring previously created object on-line at a third-party system.

createCleanup( *args )

The createCleanup method is invoked by SNMP engine by way of Columnar Instance creation to indicate a success. Custom implementation may pass this information to a third-party system.

createUndo( *args )

The createUndo method is invoked by SNMP engine by way of Columnar Instance creation to indicate a failure. Custom implementation may destroy previously created object at a third-party system.

The following is a SMI-to-filesystem binding for file creation:

class MyFileInstance(MibScalarInstance):
  def createTest(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.createTest(self, name, val, idx, (acFun, acCtx))
    # Build path to file to create from column index
    myFileEntry, = mibBuilder.importSymbols('MYFILE-MIB', 'myFileEntry')
    indices = myFileEntry.getIndicesFromInstId(name[myFileEntry.getName()+1:])
    self.__myFile = apply(os.path.join, indices)

    try:
      open('%s.new' % self.__myFile, 'w')
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def createCommit(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.createCommit(self, name, val, idx, (acFun, acCtx))
    try:
      os.rename(self.__myFile, '%s.old' % self.__myFile)
      os.rename('%s.new' % self.__myFile, self.__myFile)
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def createCleanup(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.createCleanup(self, name, val, idx, (acFun, acCtx))
    try:
      os.unlink('%s.old' % self.__myFile)
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

  def createUndo(self, name, val, idx, (acFun, acCtx)):
    MibScalarInstance.createUndo(self, name, val, idx, (acFun, acCtx))
    try:
      os.rename('%s.old' % self.__myFile, self.__myFile)
    except StandardError, why:
      raise ResourceUnavailableError(idx=idx, name=name)

# Register custom Managed Object Instance at Column
myFileColumn, = mibBuilder.importSymbols('MYFILE-MIB', 'myFileColumn')
myFileColumn.setProtoInstance(MyFileInstance)

In the above example, it is assumed that there is a MIB module named MYFILE-MIB where a MIB table column named myFileColumn is defined.


Appendixies

ASN.1 standard

SNMP relies on Abstract Syntax Notation One (ASN.1) ITU-T standard . It is actually a family of standards targeting network systems interoperability and protocols development automation.

In theory, ASN.1 technology provides a complete solution for protocol development: new protocol could be expressed in terms of data structures described in a specialized formal language.

The ASN.1 notation is designed purely for data description. All data structures there are based on a small set of elementary data types, such as INTEGER or SEQUENCE OF some other types.

Whenever protocol designer wants to define a more precise, narrow set of valid values for a field, a subtype can be created from a base ASN.1 type or another subtype by tearing up a constraint on various data properties to parent ASN.1 type. For example, a subtype of in INTEGER may allow only arbitrary values of an integer.

Another way to create a subtype from existing type is to add or replace ASN.1 tag, which serves like an ID for a type. In this new type has all the same properties of its parent type but is now known under a different name.

Once something gets expressed in ASN.1 notation, it could then be automatically translated into a variety of platform-specific implementations. They are often take shape of a program written in some common programming language like C or Python.

This is where the major feature of ASN.1 emerges. ASN.1 text could be automatically compiled into a high-quality code, that handles all the nightmares of platform-specifics, virtually for free. This code would handle byte-ordering and value ranges, data structures validations and consistency issues.

But the most useful feature is its ability to represent data in a way suitable for transmission over a communication medium. This is called encoding in ASN.1, and also known as concrete or transfer syntax in computer science.

SNMP uses these features of ASN.1 for handling Managed Objects and guiding protocol operations.

Object Identifier

This technique is a simple, unambiguous, decentralized and extensible method of naming anything. It was developed within ASN.1 standard as one of its build-in data types.

An Object Identifier consists of a sequence of integers. Each integer in this sequence maps to a node in a tree, so iterating an OID traverses this tree from root to leaf, forming a branch. Nodes in OID tree hold a group of conceptually related objects. Nodes become more specific from root to leaves. Sub-trees, or parts of OID space, often become a courtesy of various organizations and individuals.

OIDs are conventionally written as a dot-separated sequence of integers, from left to right as from root to leaves. For example, .1.3.6.1 is an arbitrary OID.

For the purpose of making OIDs human-readable, integers in OIDs (AKA sub-OIDs) can be replaced with a textual labels. Consider .org.iso.dod.internet as a labeled version of the previous example. The numeric and labeled OID representations are invariant and may mix within a single OID.

ASN.1 data encoding

For several entities to exchange ASN.1 data items some common transmission protocol is needed. This protocol would have to be able to represent ASN.1 values in a platform-native way. This might require handling hardware and/or software specific issues such as varying integer sizes, byte ordering, character encoding and so on.

Besides data representation issues, this communication protocol would have to break up data being transmitted into small chunks. The reason is that most data transmission technologies handle only a few bits in a channel at any moment of time. After buffering and packing up few bits into larger chunks, most link-level protocols still handle information in small grains. Typical measurement is eight bit or octet.

For all the reasons mentioned above, ASN.1 family of standards suggests several methods of two-way ASN.1 data conversion protocols. They are sometimes referred to as data encoding or serialization.

SNMP uses somewhat restricted flavor of Basic Encoding Rules (BER) for its ASN.1 data serialization purposes. The SNMP-specific restrictions make BER encoding deterministic -- with these restrictions applied, there is a one-to-one mapping between ASN.1 value and octet-stream produced by BER encoder. Determinism in encoding makes it possible for trivial SNMP entities to reduce their SNMP engine implementation to opaque octet-streams manipulations.


pysnmp-4.2.5/docs/mibs/0000755000076400001440000000000012222743671015061 5ustar ilyausers00000000000000pysnmp-4.2.5/docs/mibs/PYSNMP-COMMUNITY-MIB.txt0000644000076400001440000002032111675674316020647 0ustar ilyausers00000000000000PYSNMP-COMMUNITY-MIB DEFINITIONS ::= BEGIN IMPORTS MODULE-IDENTITY, OBJECT-TYPE FROM SNMPv2-SMI StorageType FROM SNMPv2-TC SnmpAdminString, SnmpEngineID FROM SNMP-FRAMEWORK-MIB SnmpTagValue FROM SNMP-TARGET-MIB pysnmpModuleIDs FROM PYSNMP-MIB; pysnmpCommunityMIB MODULE-IDENTITY LAST-UPDATED "201112250000Z" -- 25 Dec 2011, midnight ORGANIZATION "The PySNMP project" CONTACT-INFO "E-mail: ilya@glas.net Subscribe: pysnmp-users-request@lists.sourceforge.net" DESCRIPTION "This MIB module defines additional indices to facilitate fast SNMP-COMMUNITY-MIB objects retrieval." REVISION "201112250000Z" -- 25 Dec 2011, midnight DESCRIPTION "The Initial Revision" ::= { pysnmpModuleIDs 2 } -- Administrative assignments **************************************** pysnmpCommunityMIBObjects OBJECT IDENTIFIER ::= { pysnmpCommunityMIB 1 } pysnmpCommunityMIBConformance OBJECT IDENTIFIER ::= { pysnmpCommunityMIB 2 } -- -- The pysnmpOutboundCommunityTable contains a database of SNMPv1/v2c security -- names indexed by SNMP community names. -- This table may be consulted by pysnmp security module whilst processing -- SNMPv1/v2c message. -- pysnmpOutboundCommunityTable OBJECT-TYPE SYNTAX SEQUENCE OF PysnmpOutboundCommunityEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Table of SNMP-COMMUNITY-MIB's snmpSecurityName's indexed by snmpCommunityName" ::= { pysnmpCommunityMIBObjects 1 } pysnmpOutboundCommunityEntry OBJECT-TYPE SYNTAX PysnmpOutboundCommunityEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Information about a particular Community-to-Security entry." INDEX { IMPLIED pysnmpOutboundCommunityName, pysnmpOutboundCommunityContextEngineID, pysnmpOutboundCommunityContextName, pysnmpOutboundCommunityTransportTag } ::= { pysnmpOutboundCommunityTable 1 } PysnmpOutboundCommunityEntry ::= SEQUENCE { pysnmpOutboundCommunityName OCTET STRING, pysnmpOutboundCommunitySecurityName SnmpAdminString, pysnmpOutboundCommunityContextEngineID SnmpEngineID, pysnmpOutboundCommunityContextName SnmpAdminString, pysnmpOutboundCommunityTransportTag SnmpTagValue, pysnmpOutboundCommunityRowID OBJECT IDENTIFIER, pysnmpOutboundCommunityStorageType StorageType } pysnmpOutboundCommunityName OBJECT-TYPE SYNTAX OCTET STRING MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityName used in INDEX" ::= { pysnmpOutboundCommunityEntry 1 } pysnmpOutboundCommunitySecurityName OBJECT-TYPE SYNTAX SnmpAdminString MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunitySecurityName used in INDEX" ::= { pysnmpOutboundCommunityEntry 2 } pysnmpOutboundCommunityContextEngineID OBJECT-TYPE SYNTAX SnmpEngineID MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextEngineID used in INDEX" ::= { pysnmpOutboundCommunityEntry 3 } pysnmpOutboundCommunityContextName OBJECT-TYPE SYNTAX SnmpAdminString MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextName used in INDEX" ::= { pysnmpOutboundCommunityEntry 4 } pysnmpOutboundCommunityTransportTag OBJECT-TYPE SYNTAX SnmpTagValue MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityTransportTag used in INDEX" ::= { pysnmpOutboundCommunityEntry 5 } pysnmpOutboundCommunityRowID OBJECT-TYPE SYNTAX OBJECT IDENTIFIER MAX-ACCESS read-write STATUS current DESCRIPTION "SNMP-COMMUNITY-MIB::snmpCommunityTable object instance ID" ::= { pysnmpOutboundCommunityEntry 6 } pysnmpOutboundCommunityStorageType OBJECT-TYPE SYNTAX StorageType MAX-ACCESS read-create STATUS current DESCRIPTION "The storage type for this conceptual row in the snmpCommunityTable. Conceptual rows having the value 'permanent' need not allow write-access to any columnar object in the row." ::= { pysnmpOutboundCommunityEntry 7 } -- -- The pysnmpCommunityInboundTable contains a database of SNMPv1/v2c security -- names indexed by SNMP community names. -- This table may be consulted by pysnmp security module whilst processing -- SNMPv1/v2c message. -- pysnmpInboundCommunityTable OBJECT-TYPE SYNTAX SEQUENCE OF PysnmpInboundCommunityEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Table of SNMP-COMMUNITY-MIB's snmpSecurityName's indexed by snmpCommunityName" ::= { pysnmpCommunityMIBObjects 2 } pysnmpInboundCommunityEntry OBJECT-TYPE SYNTAX PysnmpInboundCommunityEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Information about a particular Community-to-Security entry." INDEX { IMPLIED pysnmpInboundCommunityName, pysnmpInboundCommunityTransportTag } ::= { pysnmpInboundCommunityTable 1 } PysnmpInboundCommunityEntry ::= SEQUENCE { pysnmpInboundCommunityName OCTET STRING, pysnmpInboundCommunitySecurityName SnmpAdminString, pysnmpInboundCommunityContextEngineID SnmpEngineID, pysnmpInboundCommunityContextName SnmpAdminString, pysnmpInboundCommunityTransportTag SnmpTagValue, pysnmpInboundCommunityRowID OBJECT IDENTIFIER, pysnmpInboundCommunityStorageType StorageType } pysnmpInboundCommunityName OBJECT-TYPE SYNTAX OCTET STRING MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityName used in INDEX" ::= { pysnmpInboundCommunityEntry 1 } pysnmpInboundCommunitySecurityName OBJECT-TYPE SYNTAX SnmpAdminString MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunitySecurityName used in INDEX" ::= { pysnmpInboundCommunityEntry 2 } pysnmpInboundCommunityContextEngineID OBJECT-TYPE SYNTAX SnmpEngineID MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextEngineID used in INDEX" ::= { pysnmpInboundCommunityEntry 3 } pysnmpInboundCommunityContextName OBJECT-TYPE SYNTAX SnmpAdminString MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityContextName used in INDEX" ::= { pysnmpInboundCommunityEntry 4 } pysnmpInboundCommunityTransportTag OBJECT-TYPE SYNTAX SnmpTagValue MAX-ACCESS not-accessible STATUS current DESCRIPTION "A copy of SNMP-COMMUNITY-MIB::snmpCommunityTransportTag used in INDEX" ::= { pysnmpInboundCommunityEntry 5 } pysnmpInboundCommunityRowID OBJECT-TYPE SYNTAX OBJECT IDENTIFIER MAX-ACCESS read-write STATUS current DESCRIPTION "SNMP-COMMUNITY-MIB::snmpCommunityTable object instance ID" ::= { pysnmpInboundCommunityEntry 6 } pysnmpInboundCommunityStorageType OBJECT-TYPE SYNTAX StorageType MAX-ACCESS read-create STATUS current DESCRIPTION "The storage type for this conceptual row in the snmpCommunityTable. Conceptual rows having the value 'permanent' need not allow write-access to any columnar object in the row." ::= { pysnmpInboundCommunityEntry 7 } -- -- The pysnmpUsmKeysTable contains a database of COMMUNITY users' localized -- keys. -- -- Conformance Information ******************************************* pysnmpCommunityMIBCompliances OBJECT IDENTIFIER ::= { pysnmpCommunityMIBConformance 1 } pysnmpCommunityMIBGroups OBJECT IDENTIFIER ::= { pysnmpCommunityMIBConformance 2 } END pysnmp-4.2.5/docs/mibs/PYSNMP-MIB.txt0000644000076400001440000000271710253532633017260 0ustar ilyausers00000000000000PYSNMP-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 "200505140000Z" ORGANIZATION "pysnmp.sf.net" CONTACT-INFO "email: ilya@glas.net" DESCRIPTION "Top-level infrastructure of the PySNMP project enterprise MIB tree" 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.2.5/docs/mibs/PYSNMP-PROXY-MIB.txt0000644000076400001440000000740211736661262020203 0ustar ilyausers00000000000000PYSNMP-PROXY-MIB DEFINITIONS ::= BEGIN IMPORTS MODULE-IDENTITY, OBJECT-TYPE FROM SNMPv2-SMI SnmpAdminString FROM SNMP-FRAMEWORK-MIB TDomain, TAddress, RowStatus FROM SNMPv2-TC pysnmpModuleIDs FROM PYSNMP-MIB; pysnmpProxyMIB MODULE-IDENTITY LAST-UPDATED "201204040000Z" -- 04 April 2012, midnight ORGANIZATION "The PySNMP project" CONTACT-INFO "E-mail: ilya@glas.net Subscribe: pysnmp-users-request@lists.sourceforge.net" DESCRIPTION "This MIB module defines implementation specific objects that facilitate LCD lookup by RFC2576 procedures at PySNMP." REVISION "201204040000Z" -- 04 April 2012, midnight DESCRIPTION "The Initial Revision" ::= { pysnmpModuleIDs 5 } -- Administrative assignments **************************************** pysnmpProxyMIBObjects OBJECT IDENTIFIER ::= { pysnmpProxyMIB 1 } pysnmpProxyMIBConformance OBJECT IDENTIFIER ::= { pysnmpProxyMIB 2 } -- -- The pysnmpProxySecurityNameTable contains a database of USM users passphrases -- used for key localization. This table may be consulted during SNMP engine-ID -- autodiscovery procedure. -- pysnmpProxySecurityNameTable OBJECT-TYPE SYNTAX SEQUENCE OF PysnmpProxySecurityNameEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "The table of USM users passphrases configured in the SNMP engine's Local Configuration Datastore (LCD)." ::= { pysnmpProxyMIBObjects 1 } pysnmpProxySecurityNameEntry OBJECT-TYPE SYNTAX PysnmpProxySecurityNameEntry MAX-ACCESS not-accessible STATUS current DESCRIPTION "Information about a particular USM user credentials." INDEX { pysnmpProxyCommunityName, pysnmpProxyTransportDomain, pysnmpProxyTransportAddress } ::= { pysnmpProxySecurityNameTable 1 } PysnmpProxySecurityNameEntry ::= SEQUENCE { pysnmpProxyCommunityName OCTET STRING, pysnmpProxyTransportDomain TDomain, pysnmpProxyTransportAddress TAddress, pysnmpProxySecurityName SnmpAdminString, pysnmpProxySecurityNameStatus RowStatus } pysnmpProxyCommunityName OBJECT-TYPE SYNTAX OCTET STRING (SIZE(0..256)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "The username string for which a row in this table represents a configuration." ::= { pysnmpProxySecurityNameEntry 1 } pysnmpProxyTransportDomain OBJECT-TYPE SYNTAX TDomain MAX-ACCESS not-accessible STATUS current DESCRIPTION "The username string for which a row in this table represents a configuration." ::= { pysnmpProxySecurityNameEntry 2 } pysnmpProxyTransportAddress OBJECT-TYPE SYNTAX TAddress MAX-ACCESS not-accessible STATUS current DESCRIPTION "The username string for which a row in this table represents a configuration." ::= { pysnmpProxySecurityNameEntry 3 } pysnmpProxySecurityName OBJECT-TYPE SYNTAX SnmpAdminString MAX-ACCESS read-only STATUS current DESCRIPTION "The username string for which a row in this table represents a configuration." ::= { pysnmpProxySecurityNameEntry 4 } pysnmpProxySecurityNameStatus OBJECT-TYPE SYNTAX RowStatus MAX-ACCESS read-create STATUS current DESCRIPTION "Table status" ::= { pysnmpProxySecurityNameEntry 5 } -- Conformance Information ******************************************* pysnmpProxyMIBCompliances OBJECT IDENTIFIER ::= { pysnmpProxyMIBConformance 1 } pysnmpProxyMIBGroups OBJECT IDENTIFIER ::= { pysnmpProxyMIBConformance 2 } END pysnmp-4.2.5/docs/mibs/PYSNMP-USM-MIB.txt0000644000076400001440000001406210350571256017720 0ustar ilyausers00000000000000PYSNMP-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 "200505140000Z" -- 14 May 2005, midnight ORGANIZATION "The PySNMP project" CONTACT-INFO "E-mail: ilya@glas.net Subscribe: pysnmp-users-request@lists.sourceforge.net" DESCRIPTION "This MIB module defines objects specific to User Security Model (USM) implementation at PySNMP." 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 } -- 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..32)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's localized key used for authentication." ::= { pysnmpUsmKeyEntry 1 } pysnmpUsmKeyPrivLocalized OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..32)) MAX-ACCESS not-accessible STATUS current DESCRIPTION "User's localized key used for encryption." ::= { pysnmpUsmKeyEntry 2 } pysnmpUsmKeyAuth OBJECT-TYPE SYNTAX OCTET STRING (SIZE(8..32)) 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..32)) 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.2.5/README0000644000076400001440000001253612222736626014070 0ustar ilyausers00000000000000 PYTHON SNMP FRAMEWORK --------------------- This is a pure-Python, open source and free implementation of v1/v2c/v3 SNMP engine. The PySNMP project has been sponsored by a PSF grant [10]. Thanks! 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 and UNIX domain sockets already implemented) * Asynchronous socket-based IO API support * Twisted (http://twistedmatrix.com) integration * Python eggs and py2exe friendly * 100% Python, works with Python 2.4 though 3.4 (alpha 3) * MT-safe (only if run locally to a thread) Features, specific to SNMPv3 model include: * USM authentication (MD5/SHA) and privacy (DES/AES) protocols (RFC3414) * 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) MISFEATURES ----------- * Much slower than C implementations. Some optimization still possible. * No pure-Python MIB compiler. The libsmi's smidump tool used for one-time MIB compilation. INSTALLATION ------------ The PySNMP package uses setuptools for package management. The PyASN1 [8] package is required. For secure SNMPv3 communication, PyCrypto [9] should also be installed. OPERATION --------- As of this writing, PySNMP implements two SNMP architectures -- the first is a legacy one specified by SNMPv1 & v2c standards [5]. It is quite low-level and protocol-oriented by design. In particular, it requires application to manage authentication and access issues, deal with transport failures and similar housekeeping stuff. The second model supported by PySNMP is aligned to SNMPv3 architecture, as specified in [4]. Here is an example on querying SNMP agent for arbitrary value (sysDescr) over SNMP v3 with authentication and privacy enabled: 8X---------------- cut here -------------------- from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('localhost', 161)), cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), lookupNames=True, lookupValues=True ) if errorIndication: # SNMP engine errors print errorIndication else: if errorStatus: # SNMP agent errors print '%s at %s\n' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?') ) else: for oid, val in varBinds: # SNMP agent values print '%s = %s' % (oid.prettyPrint(), val.prettyPrint()) 8X---------------- cut here -------------------- For more examples, please see the examples directory in the PySNMP distribution. MIB SUPPORT ----------- The pysnmp.smi package component defines and implements data model for SNMP SMI objects. With that model, various objects defined in MIB file could be implemented in Python, loaded into SNMP entity and used for verification and visualisation purposes (SNMP manager side) and/or become management targets (SNMP agent side). While MIB parser/codegenerator has not yet been implemented in PySNMP, the smidump tool of libsmi library [6] could be used for automatic, one-time convertion of MIB text files into specific Python programs designed to be dynamically loaded and used by PySNMP engine. To simplify smidump tool invocation followed by libsmi2pysnmp script, PySNMP distribution includes a build-pysnmp-mib shell script. You should use it for one-time MIB text modules convertion into PySNMP format. A large set of pre-compiled MIB files is shipped along the pysnmp-mibs package.[2] AVAILABILITY ------------ The PySNMP software is freely available for download from project homepage.[1] GETTING HELP ------------ If something does not work as expected, please, try browsing PySNMP mailing list archives or post your question there. [7] FEEDBACK -------- I'm interested in bug reports and fixes, suggestions and improvements. I'd be happy knowning whenever you used the PySNMP software for whatever purpose. Please, send me a note then. Thanks! REFERENCES ---------- [1] PySNMP project homepage: http://pysnmp.sf.net [2] Pre-compiled PySNMP MIB modules: http://sourceforge.net/project/showfiles.php?group_id=14735 [3] PySNMP applications: http://sourceforge.net/project/showfiles.php?group_id=14735 [4] SNMP Version 3 specification and related http://www.ibr.cs.tu-bs.de/projects/snmpv3/ [5] SNMP Version 1/2 specifications: http://www.ietf.org/rfc/rfc1155.txt - http://www.ietf.org/rfc/rfc1158.txt http://www.ietf.org/rfc/rfc1901.txt - http://www.ietf.org/rfc/rfc1909.txt [6] libsmi homepage http://www.ibr.cs.tu-bs.de/projects/libsmi/ Use libsmi version > 0.4.5, possibly from libsmi SVN: svn checkout http://www.ibr.cs.tu-bs.de/svn/libsmi [7] PySNMP mailing list archives: http://sourceforge.net/mail/?group_id=14735 [8] PyASN1 project homepage: http://pyasn1.sf.net [9] PyCrypto package: http://pycrypto.org [10] Python Software Foundation http://www.python.org/psf/ =-=-= mailto: ilya@glas.net pysnmp-4.2.5/CHANGES0000644000076400001440000012626412222117725014200 0ustar ilyausers00000000000000Revision 4.2.5rc2 ----------------- - 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. - 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 -------------- - 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 convertion 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 -------------- - SECURITY FIX: USM subsystem did not verify securityLevel of a request to an authoritative SNMP engineinbound 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 -------------- - 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 -------------- - Support string OIDs at one-liner API. - Code quality of libsmi2pysnmp tool improved, MIBs re-built. - SNMP-PROXY-MIB & SNMP-USER-BASED-SM-3DES-MIB added - v1arch bulkgen.py example added - Major overhawl for Python 2.4 -- 3.2 compatibility: + get rid of old-style types + drop string module usage + switch to rich comparation + drop explicit long integer type use + map()/filter() replaced with list comprehension + apply() replaced with */**args + dictionary operations made 2K/3K compatible + division operator made 2K/3K compatible + sorting function now operates on key + iterators returned by some funcs in py3k converted to lists + exception syntax made 2K/3K compatible + tuple function arguments resolved to scalars to become py3k compatible + BER octetstream is now of type bytes (Py3k) or still string (Py2k) Revision 4.1.16d ---------------- - Fix to SNMPv1 Trap PDU agentAddress setter shortcut method. Revision 4.1.16c ---------------- - Missing module import fixed in privacy subsystem Revision 4.1.16b ---------------- - Oneliner CommandGenerator can now optionally ignore non-increasing OIDs. - Default CommandResponder now skips non-compliant (Counter64) values when responding to a v1 Manager. - Fix to state information handling at CommandResponder app. - Fix to Twisted reactor shutdown condition. - Fix to distutils dependencies syntax. Revision 4.1.16a ---------------- - Extended Security Options (3DESEDE, AES192, AES256) privacy protocols implemented. - The error-indication codes moved from literals to objects for reliability and clarity - Fix to v1.TrapPDUAPI.getVarBinds() to address PDU component at the right position. - Fix to rfc1902.Bits initialization from named bits sequence. - Fix to MIB builder by-extension module filtering code to cope with .pyw files. - Internal caches structure improved. - Sync versions of oneliner apps split off async implementation for clarity. - Randomize initial in various numeric sequences. - MsgAndPduDsp expectResponse parameters passing reworked. - GetNext/GetBulk response processing logic moved to getNextVarBinds() - Changes towards performance improvement: + all dict.has_key() & dict.get() invocations replaced with modern syntax (this breaks compatibility with Python 2.1 and older). + introduce the MibInstrumControlle.readVarsFast() method (which skips the "testing" phase of MIB value readin) for dealing with internal configuration (LCD). + default debug.logger is now just a zero value instead of an object what saves big on frequent calls + SNMPv2-SMI columnar indices <-> index values convertion code optimized. + pre-compute and re-use some of ASN.1 structures. + avoid setting PDU defaults to save on unnecessary initialization. + skip ASN.1 types verification where possible. + at oneliner Command Generator, avoid looking up pure OID arguments at MIB as it's pointless but takes time. + cache MIB columnar objects instance ID <-> symbolic index representation mapping Revision 4.1.15a ---------------- - SNMP Proxy example added. - End-of-MIB condition detection reworked what caused backward incompatibility at v1arch GETNEXT API. Previous pysnmp versions used value = None in var-binds as returned by getVarBindTable() API method. This version uses rfc1905 exception values (v2c/v3) or pyasn1 Null (v1). Built-in GETNEXT/GETBULK apps now do not require user to track end-of-mib conditions anymore -- this is now done automatically. - CommandResponder API now supports async mode of operation. - SNMP exception values now exported from rfc1905 module, and made pretty printable. - Lexicographic walking mode is now supported at oneliner CommandGenerator. - ContextEngineId&ContextName parameters passing implemented at v3arch oneliner API. - Multiple instances of the same transport domain now supported. - Initial snmpEngineId value generation improved not to accidentally collide within an administrative domain. - MibTableColumn instances now build value-to-column-instance map to speedup by-value search. - SNMPv2-CONF::AgentCapabilities macro implemented. - The libsmi2pysnmp tool handles some more MACROs. - Void access control module implemented to let apps disabling [default] VACM. - Allow standard SNMP apps to choose access control method to use. - Twisted-based CommandResponder example added. - Fix/rework of Twisted GETNEXT/BULK CommandGenerator callback API to make it simpler and uniform with other CommandGenerators - Fix to SNMPv3 security module to store peer SNMP engine timeline only if taken from an authenticated message. Prior to this fix SNMP engine was not been protected from spoofing. - Fix to $SMIPATH initialization at build-pysnmp-mib. - Fix to maxSizeResponseScopedPDU calculation. - Fix to Next/Bulk CommandGenerators to catch a non-increasing OID error condition (what prevents looping). - Fix to Opaque value tagging at rfc1155.Opaque type. - Fix to handle (fail gracefully) zero-length user password. - Fix to SNMP error propagation at Twisted driver (SF tracker ID #3054505). - Fix to Agent-role snmpEngineId discovery procedure that allows authenticated ReportPDU generation. - Fix to SNMPv1 PDU handling at CommandResponder & NotificationReceiver apps. - Fix to CommandResponder app to skip Counter64 SMI values when responding to SNMPv1 Manager. - Fix to protocol translator code (rfc2576) to handle Counter64 type in v2c-to-v1 PDU translation. - Fix to non-response var-binds translation in rfc2576.v2ToV1(). - Fix to wrong exceptions used in pysnmp/entity modules. - Fix to noauth/nopriv security module so that it would not crash SNMP engine if called accidentally. - Fix to CommandResponder not to return out-of-range errorIndex along with genErr - Fix to GETBULK CommandResponder to do a by-column MIB walk, not by-raw. - Fix to getVarBindTable() API function logic. - Fix to example Manager scripts to use errorIndex when available. - Fix to dummy encryptData()/decryptData() API - Fix to oneliner GETBULK table collection code to make it stripping uneven rows off table tail. Revision 4.1.14a ---------------- - Fix to maxSizeResponseScopedPDU calculation at USM security module: now more precise and robust against screwed values on input. - Fix to MIB loading logic that used to load same-name modules at disticts search paths on each loadModules() call. - Fix to AsynsockDispatcher.runDispatcher() to make use of optional non-default select() timeout value. - AbstractTransportDispatcher now allows user application registering multiple timer callbacks each with dedicated call period. - Asynsock mainloop default idle period reduced to 0.5 sec for better timer resolution. - Fix to SNMPv1->SNMPv2c error status handling at proxy module. This defect may have caused an infinite loop on a multiple var-bind SNMPv1 GetNext operation. - Fix to contextName processing at config.addV1System -- typo rendered passed contextName not committed into LCD. - Fix to unknown ContextName exception handling at CommandResponder App. - config.addVacmUser() now accepts an optional contextName what makes it usable for configuring multiple contextName-bound bases of Managed Objects to SnmpEngine. - MP pending states cache management re-worked so that SNMP engine will now handle an unlimited number of pending request/responses. - Fix to SNMP discovery procedure: include ContentName in SNMP discovery messaging. - Many fixes to AES crypto code that makes it actually working. - Fix to SNMPv2-SMI createUndo operations. - Fix to INFORM sending error handling at oneliner. - Fix to mismatched response PDU handling at CommandGenerator application. - Debug category 'app' (for Application) added to facilitate Standard SNMP Applications debugging. - The retryCount semantic of CommandGenerator application changed to include sole retries and do not include initial request. Thus, retryCount=1 will now send up to two packets, not just one as it used to be. - Debugging printout now escapes non-printable characters. Revision 4.1.13a ---------------- - UDP over IPv6 transport implemented. - Fix to MIB tree walking code that used to fail on table columns where indices have identical leading parts. - SNMPv1/v2c snmpCommunityTransportTag-based imcoming message filtering implemented (rfc2576). Revision 4.1.12a ---------------- - API versioning retired (pysnmp.v4 -> pysnmp). - MIB loading mechanics re-designed to allow ZIP import. - MIB loader supports code objects (py[co]) - Installer now uses setuptools for package management whenever available. - The libsmi2pysnmp tool improved to build constraints of more than 256 items (Python has a limit on the number of function params). - Missing SNMPTrap PDU API implemented at proto.api.v2c, RFC2576 proxy code reworked. - Fix to sysUpTime OID at SNMPv2 TRAP PDU. Revision 4.1.11a ---------------- - Twisted integration implemented. - Attempt to use hashlib whenever available. - Fix to oneliner Manager code on < Python 2.4. - Let NotificationReceiver and CommandResponder Apps browsing request details (transport information at the moment) at SNMP engine. - Fix to config.addV1System() to allow multiple systems to co-exist in LCD. - Fix to wrongly succeeding user-parameters-by-community-name searching code in rfc2576 processIncomingMsg() method. - Do sanity checking on PYSNMP_MODULE_ID, Groups and Notifications in libsmi2pysnmp (SF bug #2122489). - Fix to oneliner Notification Originator that sometimes used to send multiple requests at once. - Oneliners LCD names generation code reworked to avoid accidental clashes. - Fix and re-work of sysUpTime value management in LCD. - Fix to pending inform request data caching in mpmod/rfc2576.py -- previous code led to cache data corruption on multple outstanding requests. - In SMI configuration wrapper functions, catch access to non-configured entries and raise an exception. - Allow multuple callback timer functions in all transport dispatchers. - Fix to libsmi2pysnmp code to preserve more underscored object names and to guess the right type between indistinguishable ObjectGroup & NotificationGroup - Fix to MibScalarInstance value setting logic - previous code failed when modifying the same OID multiple times within a single SET operation. - Minor usability improvements to tools/build-pysnmp-mib. - Made MIB objects unexport feature operational. Revision 4.1.10a ---------------- - Internal MIB indexing method __indexMib() unmangled to facilitate setting up mutex there for sharing MIB stuff between threads. - Fixed broken IpAddress value handling in SET operation. - Broken MibBuilder.unloadModules() method now works. - Use getLabel() SMI object method when building MIB tree (in builder.py) in addition to direct attribute access for clearer object protocol. - The MIB building tools updated to match significantly improved smidump tool (libsmi version > 0.4.5). - Made libsmi2pysnmp tool optionally building MIB text fields into pysnmp MIB code (enabled by default) and MibBuilder conditionally loading them up (disabled by default). - SnmpEngine and MsgAndPduDispatcher constructors now optionally take msgAndPduDspr and mibInstrumController class instances respectively to facilitate these objects sharing within a process. - Unique integers, for various parts of the system, are now generated by a nextid.py module. This fixes possible issues with duplicate request IDs and handlers. - Built-in MIBs re-generated to include text fields. Revision 4.1.9a --------------- - 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 convertion 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 --------------- - UNSTABLE ALPHA RELEASE. - SMI/dispatcher timeout convertion 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 --------------- - 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 convertion 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 convertion. - 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 --------------- - 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 --------------- - 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 --------------- - 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 --------------- - 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 --------------- - 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 --------------- - UNSTABLE ALPHA RELEASE. - SNMPv3 code first published - SNMP engine and applications implemented on library level - Major re-design towards SNMPv3-style API. Release 4.0.2a -------------- - Adopted to slightly changed asyncore API (as shipped with python 2,4) Release 4.0.1a -------------- - Minor bug/typo fixes, mostly in example/ scripts. Release 4.0.0a -------------- - 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.2.5/PKG-INFO0000644000076400001440000000235312222743671014277 0ustar ilyausers00000000000000Metadata-Version: 1.0 Name: pysnmp Version: 4.2.5 Summary: SNMP library for Python Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof Author-email: ilya@glas.net License: BSD Description: SNMP v1/v2c/v3 engine and apps written in pure-Python. Supports Manager/Agent/Proxy roles, scriptable MIBs, asynchronous operation and multiple transports. Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Education Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Telecommunications Industry Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Monitoring Classifier: Topic :: System :: Networking :: Monitoring Classifier: Topic :: Software Development :: Libraries :: Python Modules pysnmp-4.2.5/MANIFEST.in0000644000076400001440000000022112222736626014732 0ustar ilyausers00000000000000include CHANGES README LICENSE THANKS recursive-include examples *.py recursive-include tools * recursive-include docs *.txt *.html *.gif *.conf pysnmp-4.2.5/setup.cfg0000644000076400001440000000007312222743671015020 0ustar ilyausers00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pysnmp-4.2.5/pysnmp.egg-info/0000755000076400001440000000000012222743671016217 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp.egg-info/top_level.txt0000644000076400001440000000000712222743671020746 0ustar ilyausers00000000000000pysnmp pysnmp-4.2.5/pysnmp.egg-info/SOURCES.txt0000644000076400001440000002547112222743671020114 0ustar ilyausers00000000000000CHANGES LICENSE MANIFEST.in README THANKS TODO setup.cfg setup.py docs/net-snmpd.conf docs/net-snmptrapd.conf docs/pysnmp-arch.gif docs/pysnmp-tutorial.html docs/mibs/PYSNMP-COMMUNITY-MIB.txt docs/mibs/PYSNMP-MIB.txt docs/mibs/PYSNMP-PROXY-MIB.txt docs/mibs/PYSNMP-USM-MIB.txt examples/smi/backend.py examples/smi/instrum.py examples/smi/view.py examples/v1arch/agent/cmdrsp.py examples/v1arch/agent/ntforg.py examples/v1arch/manager/bulkgen.py examples/v1arch/manager/getgen.py examples/v1arch/manager/nextgen.py examples/v1arch/manager/ntfrcv.py examples/v1arch/manager/setgen.py examples/v3arch/agent/cmdrsp/v1-read-and-write-communities.py examples/v3arch/agent/cmdrsp/v2c-custom-scalar-mib-objects.py examples/v3arch/agent/cmdrsp/v2c-custom-tabular-mib-objects.py examples/v3arch/agent/cmdrsp/v2c-multiple-interfaces.py examples/v3arch/agent/cmdrsp/v2c-multiple-transports.py examples/v3arch/agent/cmdrsp/v3-alternative-mib-controller.py examples/v3arch/agent/cmdrsp/v3-alternative-mib.py examples/v3arch/agent/cmdrsp/v3-custom-engine-id.py examples/v3arch/agent/cmdrsp/v3-multiple-snmp-engines.py examples/v3arch/agent/cmdrsp/v3-multiple-users.py examples/v3arch/agent/ntforg/inform-multiple-protocols.py examples/v3arch/agent/ntforg/inform-v2c.py examples/v3arch/agent/ntforg/inform-v3.py examples/v3arch/agent/ntforg/trap-v1-from-specific-address.py examples/v3arch/agent/ntforg/trap-v1.py examples/v3arch/agent/ntforg/trap-v2c-multiple-addresses.py examples/v3arch/agent/ntforg/trap-v2c-multiple-targets.py examples/v3arch/agent/ntforg/trap-v2c-multiple-transports.py examples/v3arch/agent/ntforg/trap-v2c-with-objects.py examples/v3arch/agent/ntforg/trap-v2c.py examples/v3arch/agent/ntforg/trap-v3.py examples/v3arch/manager/cmdgen/get-v1.py examples/v3arch/manager/cmdgen/get-v2c-custom-timeout.py examples/v3arch/manager/cmdgen/get-v3-custom-context.py examples/v3arch/manager/cmdgen/get-v3.py examples/v3arch/manager/cmdgen/getbulk-v2c.py examples/v3arch/manager/cmdgen/getbulk-v3.py examples/v3arch/manager/cmdgen/getnext-v1.py examples/v3arch/manager/cmdgen/getnext-v2c-from-specific-address.py examples/v3arch/manager/cmdgen/getnext-v3-over-ipv6.py examples/v3arch/manager/cmdgen/getnext-v3-pull-subtree.py examples/v3arch/manager/cmdgen/set-v1.py examples/v3arch/manager/cmdgen/set-v2c.py examples/v3arch/manager/cmdgen/set-v3.py examples/v3arch/manager/ntfrcv/v2c-multiple-interfaces.py examples/v3arch/manager/ntfrcv/v2c-multiple-transports.py examples/v3arch/manager/ntfrcv/v3-multiple-users.py examples/v3arch/oneliner/agent/ntforg/inform-async-multiple-transports-and-protocols.py examples/v3arch/oneliner/agent/ntforg/inform-v2c-with-mib-lookup.py examples/v3arch/oneliner/agent/ntforg/inform-v3-with-custom-contextengineid.py examples/v3arch/oneliner/agent/ntforg/inform-v3-with-custom-contextname.py examples/v3arch/oneliner/agent/ntforg/inform-v3.py examples/v3arch/oneliner/agent/ntforg/trap-async-multiple-transports-and-protocols.py examples/v3arch/oneliner/agent/ntforg/trap-v1-with-custom-values.py examples/v3arch/oneliner/agent/ntforg/trap-v1-with-default-values.py examples/v3arch/oneliner/agent/ntforg/trap-v2c-with-mib-lookup.py examples/v3arch/oneliner/agent/ntforg/trap-v3-with-custom-engineid.py examples/v3arch/oneliner/manager/cmdgen/get-async-multiple-transports-and-protocols.py examples/v3arch/oneliner/manager/cmdgen/get-threaded-multiple-transports-and-protocols.py examples/v3arch/oneliner/manager/cmdgen/get-v1.py examples/v3arch/oneliner/manager/cmdgen/get-v2c.py examples/v3arch/oneliner/manager/cmdgen/get-v3-over-ipv6-with-mib-lookup.py examples/v3arch/oneliner/manager/cmdgen/get-v3-table-object-by-index.py examples/v3arch/oneliner/manager/cmdgen/get-v3-table-object-by-multiple-indices.py examples/v3arch/oneliner/manager/cmdgen/get-v3-with-custom-security-name.py examples/v3arch/oneliner/manager/cmdgen/get-v3-with-mib-lookup.py examples/v3arch/oneliner/manager/cmdgen/get-v3-with-specific-engine-id.py examples/v3arch/oneliner/manager/cmdgen/getbulk-v2c.py examples/v3arch/oneliner/manager/cmdgen/getbulk-v3-over-ipv6-with-mib-lookup.py examples/v3arch/oneliner/manager/cmdgen/getbulk-v3-with-custom-mib-path-and-options.py examples/v3arch/oneliner/manager/cmdgen/getnext-async-multiple-transports-and-protocols.py examples/v3arch/oneliner/manager/cmdgen/getnext-v1.py examples/v3arch/oneliner/manager/cmdgen/getnext-v2c.py examples/v3arch/oneliner/manager/cmdgen/getnext-v3-over-ipv6-with-mib-lookup.py examples/v3arch/oneliner/manager/cmdgen/getnext-v3-pull-whole-mib-with-mib-lookup.py examples/v3arch/oneliner/manager/cmdgen/getnext-v3-pull-whole-mib-with-options.py examples/v3arch/oneliner/manager/cmdgen/set-v1-multiple-values.py examples/v3arch/oneliner/manager/cmdgen/set-v2c-with-value-type-mib-lookup.py examples/v3arch/oneliner/manager/cmdgen/set-v3-with-custom-contextengineid-and-contextname.py examples/v3arch/oneliner/manager/cmdgen/set-v3-with-custom-contextengineid.py examples/v3arch/oneliner/manager/cmdgen/set-v3-with-value-type-mib-lookup.py examples/v3arch/proxy/cmd/udp6-to-udp4-conversion.py examples/v3arch/proxy/cmd/v2c-to-v1-conversion.py examples/v3arch/proxy/cmd/v2c-to-v3-conversion.py examples/v3arch/proxy/cmd/v3-to-v2c-conversion.py examples/v3arch/twisted/agent/cmdrsp/v1-read-and-write-communities.py examples/v3arch/twisted/agent/cmdrsp/v2c-custom-scalar-mib-objects.py examples/v3arch/twisted/agent/cmdrsp/v2c-multiple-interfaces.py examples/v3arch/twisted/agent/cmdrsp/v3-multiple-users.py examples/v3arch/twisted/agent/ntforg/inform-v2c.py examples/v3arch/twisted/agent/ntforg/inform-v3.py examples/v3arch/twisted/agent/ntforg/trap-v1.py examples/v3arch/twisted/agent/ntforg/trap-v2c-multiple-targets.py examples/v3arch/twisted/agent/ntforg/trap-v3.py examples/v3arch/twisted/manager/cmdgen/get-v1.py examples/v3arch/twisted/manager/cmdgen/get-v2c-custom-timeout.py examples/v3arch/twisted/manager/cmdgen/get-v3-custom-context.py examples/v3arch/twisted/manager/cmdgen/get-v3.py examples/v3arch/twisted/manager/cmdgen/getbulk-v2c.py examples/v3arch/twisted/manager/cmdgen/getbulk-v3.py examples/v3arch/twisted/manager/cmdgen/getnext-v1.py examples/v3arch/twisted/manager/cmdgen/getnext-v2c-from-specific-address.py examples/v3arch/twisted/manager/cmdgen/getnext-v3-pull-subtree.py examples/v3arch/twisted/manager/cmdgen/set-v1.py examples/v3arch/twisted/manager/cmdgen/set-v2c.py examples/v3arch/twisted/manager/cmdgen/set-v3.py examples/v3arch/twisted/manager/ntfrcv/v2c-multiple-interfaces.py examples/v3arch/twisted/manager/ntfrcv/v3-multiple-users.py pysnmp/__init__.py pysnmp/cache.py pysnmp/debug.py pysnmp/error.py pysnmp/nextid.py pysnmp.egg-info/PKG-INFO pysnmp.egg-info/SOURCES.txt pysnmp.egg-info/dependency_links.txt pysnmp.egg-info/requires.txt pysnmp.egg-info/top_level.txt pysnmp.egg-info/zip-safe pysnmp/carrier/__init__.py pysnmp/carrier/base.py pysnmp/carrier/error.py pysnmp/carrier/asynsock/__init__.py pysnmp/carrier/asynsock/base.py pysnmp/carrier/asynsock/dispatch.py pysnmp/carrier/asynsock/dgram/__init__.py pysnmp/carrier/asynsock/dgram/base.py pysnmp/carrier/asynsock/dgram/udp.py pysnmp/carrier/asynsock/dgram/udp6.py pysnmp/carrier/asynsock/dgram/unix.py pysnmp/carrier/twisted/__init__.py pysnmp/carrier/twisted/base.py pysnmp/carrier/twisted/dispatch.py pysnmp/carrier/twisted/dgram/__init__.py pysnmp/carrier/twisted/dgram/base.py pysnmp/carrier/twisted/dgram/udp.py pysnmp/carrier/twisted/dgram/unix.py pysnmp/entity/__init__.py pysnmp/entity/config.py pysnmp/entity/engine.py pysnmp/entity/rfc3413/__init__.py pysnmp/entity/rfc3413/cmdgen.py pysnmp/entity/rfc3413/cmdrsp.py pysnmp/entity/rfc3413/config.py pysnmp/entity/rfc3413/context.py pysnmp/entity/rfc3413/mibvar.py pysnmp/entity/rfc3413/ntforg.py pysnmp/entity/rfc3413/ntfrcv.py pysnmp/entity/rfc3413/oneliner/__init__.py pysnmp/entity/rfc3413/oneliner/auth.py pysnmp/entity/rfc3413/oneliner/cmdgen.py pysnmp/entity/rfc3413/oneliner/mibvar.py pysnmp/entity/rfc3413/oneliner/ntforg.py pysnmp/entity/rfc3413/oneliner/target.py pysnmp/entity/rfc3413/twisted/__init__.py pysnmp/entity/rfc3413/twisted/cmdgen.py pysnmp/entity/rfc3413/twisted/ntforg.py pysnmp/proto/__init__.py pysnmp/proto/cache.py pysnmp/proto/errind.py pysnmp/proto/error.py pysnmp/proto/rfc1155.py pysnmp/proto/rfc1157.py pysnmp/proto/rfc1901.py pysnmp/proto/rfc1902.py pysnmp/proto/rfc1905.py pysnmp/proto/rfc3411.py pysnmp/proto/rfc3412.py pysnmp/proto/acmod/__init__.py pysnmp/proto/acmod/rfc3415.py pysnmp/proto/acmod/void.py pysnmp/proto/api/__init__.py pysnmp/proto/api/v1.py pysnmp/proto/api/v2c.py pysnmp/proto/api/verdec.py pysnmp/proto/mpmod/__init__.py pysnmp/proto/mpmod/base.py pysnmp/proto/mpmod/cache.py pysnmp/proto/mpmod/rfc2576.py pysnmp/proto/mpmod/rfc3412.py pysnmp/proto/proxy/__init__.py pysnmp/proto/proxy/rfc2576.py pysnmp/proto/secmod/__init__.py pysnmp/proto/secmod/base.py pysnmp/proto/secmod/cache.py pysnmp/proto/secmod/rfc2576.py pysnmp/proto/secmod/eso/__init__.py pysnmp/proto/secmod/eso/priv/__init__.py pysnmp/proto/secmod/eso/priv/aes192.py pysnmp/proto/secmod/eso/priv/aes256.py pysnmp/proto/secmod/eso/priv/des3.py pysnmp/proto/secmod/rfc3414/__init__.py pysnmp/proto/secmod/rfc3414/localkey.py pysnmp/proto/secmod/rfc3414/service.py pysnmp/proto/secmod/rfc3414/auth/__init__.py pysnmp/proto/secmod/rfc3414/auth/base.py pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py pysnmp/proto/secmod/rfc3414/auth/hmacsha.py pysnmp/proto/secmod/rfc3414/auth/noauth.py pysnmp/proto/secmod/rfc3414/priv/__init__.py pysnmp/proto/secmod/rfc3414/priv/base.py pysnmp/proto/secmod/rfc3414/priv/des.py pysnmp/proto/secmod/rfc3414/priv/nopriv.py pysnmp/proto/secmod/rfc3826/__init__.py pysnmp/proto/secmod/rfc3826/priv/__init__.py pysnmp/proto/secmod/rfc3826/priv/aes.py pysnmp/smi/__init__.py pysnmp/smi/builder.py pysnmp/smi/error.py pysnmp/smi/exval.py pysnmp/smi/indices.py pysnmp/smi/instrum.py pysnmp/smi/view.py pysnmp/smi/mibs/ASN1-ENUMERATION.py pysnmp/smi/mibs/ASN1-REFINEMENT.py pysnmp/smi/mibs/ASN1.py pysnmp/smi/mibs/PYSNMP-MIB.py pysnmp/smi/mibs/PYSNMP-USM-MIB.py pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py pysnmp/smi/mibs/SNMP-MPD-MIB.py pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py pysnmp/smi/mibs/SNMP-PROXY-MIB.py pysnmp/smi/mibs/SNMP-TARGET-MIB.py pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py pysnmp/smi/mibs/SNMP-USM-AES-MIB.py pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py pysnmp/smi/mibs/SNMPv2-CONF.py pysnmp/smi/mibs/SNMPv2-MIB.py pysnmp/smi/mibs/SNMPv2-SMI.py pysnmp/smi/mibs/SNMPv2-TC.py pysnmp/smi/mibs/SNMPv2-TM.py pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py pysnmp/smi/mibs/__init__.py pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py pysnmp/smi/mibs/instances/__SNMPv2-MIB.py pysnmp/smi/mibs/instances/__init__.py tools/build-pysnmp-mib tools/libsmi2pysnmppysnmp-4.2.5/pysnmp.egg-info/PKG-INFO0000644000076400001440000000235312222743671017317 0ustar ilyausers00000000000000Metadata-Version: 1.0 Name: pysnmp Version: 4.2.5 Summary: SNMP library for Python Home-page: http://sourceforge.net/projects/pysnmp/ Author: Ilya Etingof Author-email: ilya@glas.net License: BSD Description: SNMP v1/v2c/v3 engine and apps written in pure-Python. Supports Manager/Agent/Proxy roles, scriptable MIBs, asynchronous operation and multiple transports. Platform: any Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Education Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: Intended Audience :: Telecommunications Industry Classifier: License :: OSI Approved :: BSD License Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: System :: Monitoring Classifier: Topic :: System :: Networking :: Monitoring Classifier: Topic :: Software Development :: Libraries :: Python Modules pysnmp-4.2.5/pysnmp.egg-info/requires.txt0000644000076400001440000000003512222743671020615 0ustar ilyausers00000000000000pyasn1>=0.1.2 pycrypto>=2.4.1pysnmp-4.2.5/pysnmp.egg-info/zip-safe0000644000076400001440000000000112222737023017641 0ustar ilyausers00000000000000 pysnmp-4.2.5/pysnmp.egg-info/dependency_links.txt0000644000076400001440000000000112222743671022265 0ustar ilyausers00000000000000 pysnmp-4.2.5/pysnmp/0000755000076400001440000000000012222743671014525 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/__init__.py0000644000076400001440000000026212106205177016631 0ustar ilyausers00000000000000# http://www.python.org/dev/peps/pep-0396/ __version__ = '4.2.5' # backward compatibility version = tuple([ int(x) for x in __version__.split('.') ]) majorVersionId = version[0] pysnmp-4.2.5/pysnmp/debug.py0000644000076400001440000000413612133570174016166 0ustar ilyausers00000000000000import sys import time 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 Debug: defaultPrinter = sys.stderr.write def __init__(self, *flags): self._flags = flagNone self._printer = self.defaultPrinter 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('DBG: [%s]: %s\n' % (self.timestamp(), msg)) def __and__(self, flag): return self._flags & flag def __rand__(self, flag): return flag & self._flags def timestamp(self): return time.strftime('%H:%M:%S', time.localtime()) + \ '.%.3d' % int((time.time() % 1) * 1000) # 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.2.5/pysnmp/error.py0000644000076400001440000000004311655706725016235 0ustar ilyausers00000000000000class PySnmpError(Exception): pass pysnmp-4.2.5/pysnmp/proto/0000755000076400001440000000000012222743671015670 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/acmod/0000755000076400001440000000000012222743671016753 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/acmod/__init__.py0000644000076400001440000000007311775057744021077 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/acmod/rfc3415.py0000644000076400001440000001122312220073611020377 0ustar ilyausers00000000000000# View-based Access Control Model from pysnmp.smi.error import NoSuchInstanceError from pysnmp.proto import errind, error from pysnmp import debug __powOfTwoSeq = [128, 64, 32, 16, 8, 4, 2, 1] # 3.2 class Vacm: accessModelID = 3 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)) # 3.2.1 vacmContextEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry') tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) try: vacmContextName = vacmContextEntry.getNode( vacmContextEntry.name + (1,) + tblIdx ).syntax except NoSuchInstanceError: raise error.StatusInformation(errorIndication=errind.noSuchContext) # 3.2.2 vacmSecurityToGroupEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry') tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( securityModel, securityName ) try: vacmGroupName = vacmSecurityToGroupEntry.getNode( vacmSecurityToGroupEntry.name + (3,) + tblIdx ).syntax except NoSuchInstanceError: raise error.StatusInformation(errorIndication=errind.noGroupName) # 3.2.3 vacmAccessEntry, = mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' ) # XXX partial context name match tblIdx = vacmAccessEntry.getInstIdFromIndices( vacmGroupName, contextName, securityModel, securityLevel ) # 3.2.4 if viewType == 'read': entryIdx = vacmAccessEntry.name + (5,) + tblIdx elif viewType == 'write': entryIdx = vacmAccessEntry.name + (6,) + tblIdx elif viewType == 'notify': entryIdx = vacmAccessEntry.name + (7,) + tblIdx else: raise error.ProtocolError('Unknown view type %s' % viewType) try: viewName = vacmAccessEntry.getNode(entryIdx).syntax except NoSuchInstanceError: raise error.StatusInformation(errorIndication=errind.noAccessEntry) if not len(viewName): raise error.StatusInformation(errorIndication=errind.noSuchView) # XXX split onto object & instance ? # 3.2.5a vacmViewTreeFamilyEntry, = mibInstrumController.mibBuilder.importSymbols('SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry') tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices(viewName) # Walk over entries initialTreeName = treeName = vacmViewTreeFamilyEntry.name + (2,) + tblIdx maskName = vacmViewTreeFamilyEntry.name + (3,) + tblIdx while 1: vacmViewTreeFamilySubtree = vacmViewTreeFamilyEntry.getNextNode( treeName ) vacmViewTreeFamilyMask = vacmViewTreeFamilyEntry.getNextNode( maskName ) treeName = vacmViewTreeFamilySubtree.name maskName = vacmViewTreeFamilyMask.name if initialTreeName != treeName[:len(initialTreeName)]: # 3.2.5b raise error.StatusInformation(errorIndication=errind.notInView) l = len(vacmViewTreeFamilySubtree.syntax) if l > len(variableName): continue if vacmViewTreeFamilyMask.syntax: mask = [] for c in vacmViewTreeFamilyMask.syntax.asNumbers(): mask = mask + [ b&c for b in __powOfTwoSeq ] m = len(mask)-1 idx = l-1 while idx: if idx > m or mask[idx] and \ vacmViewTreeFamilySubtree.syntax[idx] != variableName[idx]: break idx = idx - 1 if idx: continue # no match else: # no mask if vacmViewTreeFamilySubtree.syntax != variableName[:l]: continue # no match # 3.2.5c return error.StatusInformation(errorIndication=errind.accessAllowed) pysnmp-4.2.5/pysnmp/proto/acmod/void.py0000644000076400001440000000124312220056646020263 0ustar ilyausers00000000000000# Void Access Control Model from pysnmp.proto import errind, error from pysnmp import debug # rfc3415 3.2 class Vacm: 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.2.5/pysnmp/proto/__init__.py0000644000076400001440000000007311775057761020013 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/rfc1902.py0000644000076400001440000001672512010752023017325 0ustar ilyausers00000000000000from pyasn1.type import univ, tag, constraint, namedtype, namedval from pysnmp.proto import rfc1155, error class Integer(univ.Integer): subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( -2147483648, 2147483647 ) class Integer32(univ.Integer): subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( -2147483648, 2147483647 ) class OctetString(univ.OctetString): subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueSizeConstraint( 0, 65535 ) # rfc1902 uses a notion of "fixed length string" what might mean # having zero-range size constraint applied. The following is # supposed to be used for setting and querying this property. fixedLength = None def setFixedLength(self, value): self.fixedLength = value return self def isFixedLength(self): return self.fixedLength is not None def getFixedLength(self): return self.fixedLength class IpAddress(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) ) subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( 4, 4 ) fixedLength = 4 def prettyIn(self, value): if isinstance(value, str) and len(value) != 4: try: value = [ int(x) for x in value.split('.') ] except: raise error.ProtocolError('Bad IP address syntax %s' % value) value = univ.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): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class Gauge32(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class Unsigned32(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class TimeTicks(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class Opaque(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) ) class Counter64(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x06) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 18446744073709551615 ) class Bits(univ.OctetString): namedValues = namedval.NamedValues() def __init__(self, value=None, tagSet=None, subtypeSpec=None, namedValues=None): if namedValues is None: self.__namedValues = self.namedValues else: self.__namedValues = namedValues univ.OctetString.__init__( self, value, tagSet, subtypeSpec ) def prettyIn(self, bits): if not isinstance(bits, (tuple, list)): return univ.OctetString.prettyIn(self, bits) # raw bitstring octets = [] for bit in bits: # tuple of named bits v = self.__namedValues.getValue(bit) if v is None: raise error.ProtocolError( 'Unknown named bit %s' % bit ) d, m = divmod(v, 8) if d >= len(octets): octets.extend([0] * (d - len(octets) + 1)) octets[d] = octets[d] | 0x01 << (7-m) return univ.OctetString.prettyIn(self, octets) def prettyOut(self, value): names = [] ints = self.__class__(value).asNumbers() i = 0 while i < len(ints): v = ints[i] j = 7 while j >= 0: if v & (0x01< snmpEngineMaxMessageSize.syntax: raise error.StatusInformation(errorIndication=errind.tooBig) # 7.1.9.c if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX rfc bug? why stateReference should be created? self._cache.pushByMsgId( msgID, sendPduHandle=sendPduHandle, msgID=msgID, snmpEngineID=snmpEngineID, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, transportDomain=transportDomain, transportAddress=transportAddress ) return ( transportDomain, transportAddress, wholeMsg ) def prepareResponseMessage( self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, maxSizeResponseScopedPDU, # n.b. not actually used here stateReference, statusInformation ): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # 7.1.2.b cachedParams = self._cache.popByStateRef(stateReference) msgID = cachedParams['msgID'] contextEngineId = cachedParams['contextEngineId'] contextName = cachedParams['contextName'] securityModel = cachedParams['securityModel'] securityName = cachedParams['securityName'] securityLevel = cachedParams['securityLevel'] securityStateReference = cachedParams['securityStateReference'] reportableFlag = cachedParams['reportableFlag'] maxMessageSize = cachedParams['msgMaxSize'] transportDomain = cachedParams['transportDomain'] transportAddress = cachedParams['transportAddress'] debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: stateReference %s' % (stateReference)) # 7.1.3 if statusInformation is not None and 'oid' in statusInformation: # 7.1.3a if pdu is not None: requestID = pdu.getComponentByPosition(0) pduType = pdu.tagSet else: pduType = None # 7.1.3b if pdu is None and not reportableFlag or \ pduType is not None and \ pduType not in rfc3411.confirmedClassPDUs: raise error.StatusInformation( errorIndication = errind.loopTerminated ) # 7.1.3c reportPDU = rfc1905.ReportPDU() pMod.apiPDU.setVarBinds( reportPDU, ((statusInformation['oid'], statusInformation['val']),) ) pMod.apiPDU.setErrorStatus(reportPDU, 0) pMod.apiPDU.setErrorIndex(reportPDU, 0) if pdu is None: pMod.apiPDU.setRequestID(reportPDU, 0) else: pMod.apiPDU.setRequestID(reportPDU, requestID) # 7.1.3d.1 if 'securityLevel' in statusInformation: securityLevel = statusInformation['securityLevel'] else: securityLevel = 1 # 7.1.3d.2 if 'contextEngineId' in statusInformation: contextEngineId = statusInformation['contextEngineId'] else: contextEngineId = snmpEngineID # 7.1.3d.3 if 'contextName' in statusInformation: contextName = statusInformation['contextName'] else: contextName = "" # 7.1.3e pdu = reportPDU debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: prepare report PDU for statusInformation %s' % statusInformation) # 7.1.4 if not contextEngineId: contextEngineId = snmpEngineID # XXX impl-dep manner # 7.1.5 if not contextName: contextName = self._emptyStr debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r, contextName %r' % (contextEngineId, contextName)) # 7.1.6 scopedPDU = self.__scopedPDU scopedPDU.setComponentByPosition(0, contextEngineId) scopedPDU.setComponentByPosition(1, contextName) scopedPDU.setComponentByPosition(2) scopedPDU.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False ) # 7.1.7 msg = self._snmpMsgSpec # 7.1.7a msg.setComponentByPosition( 0, self.messageProcessingModelID, verifyConstraints=False ) headerData = msg.setComponentByPosition(1).getComponentByPosition(1) # 7.1.7b headerData.setComponentByPosition( 0, msgID, verifyConstraints=False ) snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') # 7.1.7c # XXX need to coerce MIB value as it has incompatible constraints set headerData.setComponentByPosition( 1, snmpEngineMaxMessageSize.syntax, verifyConstraints=False ) # 7.1.7d msgFlags = 0 if securityLevel == 1: pass elif securityLevel == 2: msgFlags = msgFlags | 0x01 elif securityLevel == 3: msgFlags = msgFlags | 0x03 else: raise error.ProtocolError( 'Unknown securityLevel %s' % securityLevel ) if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX not needed? msgFlags = msgFlags | 0x04 headerData.setComponentByPosition( 2, self._msgFlags[msgFlags], verifyConstraints=False ) # 7.1.7e headerData.setComponentByPosition( 3, securityModel, verifyConstraints=False ) debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: %s' % (msg.prettyPrint(),)) if securityModel in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[securityModel] else: raise error.StatusInformation( errorIndication = errind.unsupportedSecurityModel ) 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) return ( transportDomain, transportAddress, wholeMsg ) # 7.2.1 def prepareDataElements( self, snmpEngine, transportDomain, transportAddress, wholeMsg ): # 7.2.2 try: msg, restOfwholeMsg = decoder.decode( wholeMsg, asn1Spec=self._snmpMsgSpec ) except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 raise error.StatusInformation( errorIndication = errind.parseError ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) # 7.2.3 headerData = msg.getComponentByPosition(1) msgVersion = messageProcessingModel = msg.getComponentByPosition(0) msgID = headerData.getComponentByPosition(0) msgFlags, = headerData.getComponentByPosition(2).asNumbers() maxMessageSize = headerData.getComponentByPosition(1) securityModel = headerData.getComponentByPosition(3) securityParameters = msg.getComponentByPosition(2) debug.logger & debug.flagMP and debug.logger('prepareDataElements: msg data msgVersion %s msgID %s securityModel %s' % (msgVersion, msgID, securityModel)) # 7.2.4 if securityModel not in snmpEngine.securityModels: snmpUnknownSecurityModels, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpUnknownSecurityModels') snmpUnknownSecurityModels.syntax = snmpUnknownSecurityModels.syntax + 1 raise error.StatusInformation( errorIndication = errind.unsupportedSecurityModel ) # 7.2.5 if msgFlags & 0x03 == 0x00: securityLevel = 1 elif (msgFlags & 0x03) == 0x01: securityLevel = 2 elif (msgFlags & 0x03) == 0x03: securityLevel = 3 else: snmpInvalidMsgs = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInvalidMsgs') snmpInvalidMsgs.syntax = snmpInvalidMsgs.syntax + 1 raise error.StatusInformation( errorIndication = errind.invalidMsg ) if msgFlags & 0x04: reportableFlag = 1 else: reportableFlag = 0 # 7.2.6 smHandler = snmpEngine.securityModels[securityModel] try: ( securityEngineId, securityName, scopedPDU, maxSizeResponseScopedPDU, securityStateReference ) = smHandler.processIncomingMsg( snmpEngine, messageProcessingModel, maxMessageSize, securityParameters, securityModel, securityLevel, wholeMsg, msg ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded') except error.StatusInformation: statusInformation, origTraceback = sys.exc_info()[1:3] debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM failed, statusInformation %s' % statusInformation) if 'errorIndication' in statusInformation: # 7.2.6a if 'oid' in statusInformation: # 7.2.6a1 securityStateReference = statusInformation[ 'securityStateReference' ] contextEngineId = statusInformation['contextEngineId'] contextName = statusInformation['contextName'] if 'scopedPDU' in statusInformation: scopedPDU = statusInformation['scopedPDU'] pdu = scopedPDU.getComponentByPosition(2).getComponent() else: pdu = None maxSizeResponseScopedPDU = statusInformation[ 'maxSizeResponseScopedPDU' ] securityName = None # XXX secmod cache used # 7.2.6a2 stateReference = self._cache.newStateReference() self._cache.pushByStateRef( stateReference, msgVersion=messageProcessingModel, msgID=msgID, contextEngineId=contextEngineId, contextName=contextName, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, reportableFlag=reportableFlag, msgMaxSize=maxMessageSize, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress ) # 7.2.6a3 try: snmpEngine.msgAndPduDsp.returnResponsePdu( snmpEngine, 3, securityModel, securityName, securityLevel, contextEngineId, contextName, 1, pdu, maxSizeResponseScopedPDU, stateReference, statusInformation ) except error.StatusInformation: pass debug.logger & debug.flagMP and debug.logger('prepareDataElements: error reported') # 7.2.6b if sys.version_info[0] <= 2: raise statusInformation else: try: raise statusInformation.with_traceback(origTraceback) finally: # Break cycle between locals and traceback object # (seems to be irrelevant on Py3 but just in case) del origTraceback else: # Sniff for engineIdCache k = (transportDomain, transportAddress) if k not in self.__engineIdCache: contextEngineId, contextName, pdus = scopedPDU pdu = pdus.getComponent() # Here we assume that authentic/default EngineIDs # come only in the course of engine-to-engine communication. if pdu.tagSet in rfc3411.internalClassPDUs: self.__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, contextName, pdu = scopedPDU pdu = pdu.getComponent() # PDUs # 7.2.8 pduVersion = api.protoVersion2c # 7.2.9 pduType = pdu.tagSet # 7.2.10 if pduType in rfc3411.responseClassPDUs or \ pduType in rfc3411.internalClassPDUs: # 7.2.10a try: cachedReqParams = self._cache.popByMsgId(msgID) except error.ProtocolError: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.dataMismatch ) # 7.2.10b sendPduHandle = cachedReqParams['sendPduHandle'] else: sendPduHandle = None debug.logger & debug.flagMP and debug.logger('prepareDataElements: using sendPduHandle %s for msgID %s' % (sendPduHandle, msgID)) # 7.2.11 if pduType in rfc3411.internalClassPDUs: # 7.2.11a varBinds = pMod.apiPDU.getVarBinds(pdu) if varBinds: statusInformation = error.StatusInformation( errorIndication=_snmpErrors.get( varBinds[0][0], 'errorReportReceived' ), oid=varBinds[0][0], val=varBinds[0][1], sendPduHandle=sendPduHandle ) # 7.2.11b (incomplete implementation) # 7.2.11c smHandler.releaseStateInformation(securityStateReference) # 7.2.11d stateReference = None # 7.2.11e XXX may need to pass Reports up to app in some cases... raise statusInformation statusInformation = None # no errors ahead # 7.2.12 if pduType in rfc3411.responseClassPDUs: # 7.2.12a -> noop # 7.2.12b if securityModel != cachedReqParams['securityModel'] or \ securityName != cachedReqParams['securityName'] or \ securityLevel != cachedReqParams['securityLevel'] or \ contextEngineId != cachedReqParams['contextEngineId'] or \ contextName != cachedReqParams['contextName']: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.dataMismatch ) # 7.2.12c smHandler.releaseStateInformation(securityStateReference) stateReference = None # 7.2.12d return ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) # 7.2.13 if pduType in rfc3411.confirmedClassPDUs: # 7.2.13a if securityEngineId != snmpEngineID: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.engineIDMismatch ) # 7.2.13b stateReference = self._cache.newStateReference() self._cache.pushByStateRef( stateReference, msgVersion=messageProcessingModel, msgID=msgID, contextEngineId=contextEngineId, contextName=contextName, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, reportableFlag=reportableFlag, msgMaxSize=maxMessageSize, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: new stateReference %s' % stateReference) # 7.2.13c return ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) # 7.2.14 if pduType in rfc3411.unconfirmedClassPDUs: # Pass new stateReference to let app browse request details stateReference = self._cache.newStateReference() # This is not specified explicitly in RFC smHandler.releaseStateInformation(securityStateReference) return ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.unsupportedPDUtype ) def __expireEnginesInfo(self): if self.__expirationTimer in self.__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 = self.__expirationTimer + 1 def receiveTimerTick(self, snmpEngine, timeNow): self.__expireEnginesInfo() AbstractMessageProcessingModel.receiveTimerTick( self, snmpEngine, timeNow ) pysnmp-4.2.5/pysnmp/proto/mpmod/cache.py0000644000076400001440000000753412003212611020410 0ustar ilyausers00000000000000from pysnmp.proto import error from pysnmp import nextid class Cache: __stateReference = nextid.Integer(0xffffff) __msgID = nextid.Integer(0xffffff) def __init__(self): self.__msgIdIndex = {} self.__stateReferenceIndex = {} self.__sendPduHandleIdx = {} # Message expiration mechanics self.__expirationQueue = {} self.__expirationTimer = 0 # Server mode cache handling def newStateReference(self): return self.__stateReference() def pushByStateRef(self, stateReference, **msgInfo): if stateReference in self.__stateReferenceIndex: raise error.ProtocolError( 'Cache dup for stateReference=%s at %s' % (stateReference, self) ) expireAt = self.__expirationTimer+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 = self.__expirationTimer + 1 pysnmp-4.2.5/pysnmp/proto/mpmod/base.py0000644000076400001440000000316412153626041020266 0ustar ilyausers00000000000000# MP-specific cache management from pysnmp.proto.mpmod import cache from pysnmp.proto import error class AbstractMessageProcessingModel: snmpMsgSpec = NotImplementedError def __init__(self): self._snmpMsgSpec = self.snmpMsgSpec() # local copy self._cache = cache.Cache() 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.2.5/pysnmp/proto/mpmod/rfc2576.py0000644000076400001440000003612512222117726020457 0ustar ilyausers00000000000000# SNMP v1 & v2c message processing models implementation import sys from pyasn1.codec.ber import decoder from pyasn1.type import univ from pyasn1.compat.octets import null from pyasn1.error import PyAsn1Error from pysnmp.proto.mpmod.base import AbstractMessageProcessingModel from pysnmp.proto import rfc3411, errind, error from pysnmp.proto.api import v1, v2c from pysnmp import debug # Since I have not found a detailed reference to v1MP/v2cMP # inner workings, the following has been patterned from v3MP. Most # references here goes to RFC3412. class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): messageProcessingModelID = univ.Integer(0) # SNMPv1 snmpMsgSpec = v1.Message # rfc3412: 7.1 def prepareOutgoingMessage( self, snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, expectResponse, sendPduHandle ): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # rfc3412: 7.1.1b if pdu.tagSet in rfc3411.confirmedClassPDUs: pdu.setComponentByPosition(1) msgID = pdu.getComponentByPosition(0) # rfc3412: 7.1.4 # Since there's no SNMP engine identification in v1/2c, # set destination contextEngineId to ours if not contextEngineId: contextEngineId = snmpEngineID # rfc3412: 7.1.5 if not contextName: contextName = null debug.logger & debug.flagMP and debug.logger('prepareOutgoingMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) # rfc3412: 7.1.6 scopedPDU = ( contextEngineId, contextName, pdu ) msg = self._snmpMsgSpec msg.setComponentByPosition(0, self.messageProcessingModelID) msg.setComponentByPosition(2) msg.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False ) # rfc3412: 7.1.7 globalData = ( msg, ) k = int(securityModel) if k in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[k] else: raise error.StatusInformation( errorIndication = errind.unsupportedSecurityModel ) # rfc3412: 7.1.9.a & rfc2576: 5.2.1 --> no-op snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') # rfc3412: 7.1.9.b ( securityParameters, wholeMsg ) = smHandler.generateRequestMsg( snmpEngine, self.messageProcessingModelID, globalData, snmpEngineMaxMessageSize.syntax, securityModel, snmpEngineID, securityName, securityLevel, scopedPDU ) # rfc3412: 7.1.9.c if pdu.tagSet in rfc3411.confirmedClassPDUs: # XXX rfc bug? why stateReference should be created? self._cache.pushByMsgId( int(msgID), sendPduHandle=sendPduHandle, msgID=msgID, snmpEngineID=snmpEngineID, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, transportDomain=transportDomain, transportAddress=transportAddress ) return ( transportDomain, transportAddress, wholeMsg ) # rfc3412: 7.1 def prepareResponseMessage( self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, maxSizeResponseScopedPDU, stateReference, statusInformation ): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpEngineID = snmpEngineID.syntax # rfc3412: 7.1.2.b if stateReference is None: raise error.StatusInformation( errorIndication = errind.nonReportable ) cachedParams = self._cache.popByStateRef(stateReference) msgID = cachedParams['msgID'] contextEngineId = cachedParams['contextEngineId'] contextName = cachedParams['contextName'] securityModel = cachedParams['securityModel'] securityName = cachedParams['securityName'] securityLevel = cachedParams['securityLevel'] securityStateReference = cachedParams['securityStateReference'] maxMessageSize = cachedParams['msgMaxSize'] transportDomain = cachedParams['transportDomain'] transportAddress = cachedParams['transportAddress'] debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: cache read msgID %s transportDomain %s transportAddress %s by stateReference %s' % (msgID, transportDomain, transportAddress, stateReference)) # rfc3412: 7.1.3 if statusInformation: # rfc3412: 7.1.3a (N/A) # rfc3412: 7.1.3b (always discard) raise error.StatusInformation( errorIndication = errind.nonReportable ) # rfc3412: 7.1.4 # Since there's no SNMP engine identification in v1/2c, # set destination contextEngineId to ours if not contextEngineId: contextEngineId = snmpEngineID # rfc3412: 7.1.5 if not contextName: contextName = null # rfc3412: 7.1.6 scopedPDU = ( contextEngineId, contextName, pdu ) debug.logger & debug.flagMP and debug.logger('prepareResponseMessage: using contextEngineId %r contextName %r' % (contextEngineId, contextName)) msg = self._snmpMsgSpec msg.setComponentByPosition(0, messageProcessingModel) msg.setComponentByPosition(2) msg.getComponentByPosition(2).setComponentByType( pdu.tagSet, pdu, verifyConstraints=False ) # att: msgId not set back to PDU as it's up to responder app # rfc3412: 7.1.7 globalData = ( msg, ) k = int(securityModel) if k in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[k] else: raise error.StatusInformation( errorIndication = errind.unsupportedSecurityModel ) securityEngineId = snmpEngineID # rfc3412: 7.1.8.a ( securityParameters, wholeMsg ) = smHandler.generateResponseMsg( snmpEngine, self.messageProcessingModelID, globalData, maxMessageSize, securityModel, snmpEngineID, securityName, securityLevel, scopedPDU, securityStateReference ) return ( transportDomain, transportAddress, wholeMsg ) # rfc3412: 7.2.1 def prepareDataElements( self, snmpEngine, transportDomain, transportAddress, wholeMsg ): # rfc3412: 7.2.2 try: msg, restOfwholeMsg = decoder.decode( wholeMsg, asn1Spec=self._snmpMsgSpec ) except PyAsn1Error: debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 raise error.StatusInformation( errorIndication = errind.parseError ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: %s' % (msg.prettyPrint(),)) # rfc3412: 7.2.3 msgVersion = messageProcessingModel = msg.getComponentByPosition(0) # rfc2576: 5.2.1 snmpEngineMaxMessageSize, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') securityParameters = ( msg.getComponentByPosition(1), # transportDomain identifies local enpoint (transportDomain, transportAddress) ) messageProcessingModel = int(msg.getComponentByPosition(0)) securityModel = messageProcessingModel + 1 securityLevel = 1 # rfc3412: 7.2.4 -- 7.2.5 -> noop k = int(securityModel) if k in snmpEngine.securityModels: smHandler = snmpEngine.securityModels[k] else: raise error.StatusInformation( errorIndication = errind.unsupportedSecurityModel ) # rfc3412: 7.2.6 ( securityEngineID, securityName, scopedPDU, maxSizeResponseScopedPDU, securityStateReference ) = smHandler.processIncomingMsg( snmpEngine, messageProcessingModel, snmpEngineMaxMessageSize.syntax, securityParameters, securityModel, securityLevel, wholeMsg, msg ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM returned securityEngineID %r securityName %r' % (securityEngineID, securityName)) # rfc3412: 7.2.6a --> noop # rfc3412: 7.2.7 contextEngineId, contextName, pdu = scopedPDU # rfc2576: 5.2.1 pduVersion = msgVersion pduType = pdu.tagSet # rfc3412: 7.2.8, 7.2.9 -> noop # rfc3412: 7.2.10 if pduType in rfc3411.responseClassPDUs: # (wild hack: use PDU reqID at MsgID) msgID = pdu.getComponentByPosition(0) # 7.2.10a try: cachedReqParams = self._cache.popByMsgId(int(msgID)) except error.ProtocolError: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.dataMismatch ) # 7.2.10b sendPduHandle = cachedReqParams['sendPduHandle'] else: sendPduHandle = None # no error by default statusInformation = None # rfc3412: 7.2.11 -> noop # rfc3412: 7.2.12 if pduType in rfc3411.responseClassPDUs: # rfc3412: 7.2.12a -> noop # rfc3412: 7.2.12b if securityModel != cachedReqParams['securityModel'] or \ securityName != cachedReqParams['securityName'] or \ securityLevel != cachedReqParams['securityLevel'] or \ contextEngineId != cachedReqParams['contextEngineId'] or \ contextName != cachedReqParams['contextName']: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.dataMismatch ) stateReference = None # rfc3412: 7.2.12c smHandler.releaseStateInformation(securityStateReference) # rfc3412: 7.2.12d return ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) # rfc3412: 7.2.13 if pduType in rfc3411.confirmedClassPDUs: # (wild hack: use PDU reqID at MsgID) msgID = pdu.getComponentByPosition(0) # rfc3412: 7.2.13a snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if securityEngineID != snmpEngineID.syntax: smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.engineIDMismatch ) # rfc3412: 7.2.13b stateReference = self._cache.newStateReference() self._cache.pushByStateRef( stateReference, msgVersion=messageProcessingModel, msgID=msgID, contextEngineId=contextEngineId, contextName=contextName, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, securityStateReference=securityStateReference, msgMaxSize=snmpEngineMaxMessageSize.syntax, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, transportDomain=transportDomain, transportAddress=transportAddress ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: cached by new stateReference %s' % stateReference) # rfc3412: 7.2.13c return ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) # rfc3412: 7.2.14 if pduType in rfc3411.unconfirmedClassPDUs: # Pass new stateReference to let app browse request details stateReference = self._cache.newStateReference() # This is not specified explicitly in RFC smHandler.releaseStateInformation(securityStateReference) return ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, pdu, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) smHandler.releaseStateInformation(securityStateReference) raise error.StatusInformation( errorIndication = errind.unsupportedPDUtype ) class SnmpV2cMessageProcessingModel(SnmpV1MessageProcessingModel): messageProcessingModelID = univ.Integer(1) # SNMPv2c snmpMsgSpec = v2c.Message pysnmp-4.2.5/pysnmp/proto/error.py0000644000076400001440000000166411516046734017403 0ustar ilyausers00000000000000from 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.2.5/pysnmp/proto/rfc3412.py0000644000076400001440000004506312153626041017330 0ustar ilyausers00000000000000"""SNMP v3 Message Processing and Dispatching (RFC3412)""" import sys from pyasn1.compat.octets import null from pysnmp.smi import builder, instrum from pysnmp.proto import errind, error, cache from pysnmp.proto.api import verdec # XXX from pysnmp.error import PySnmpError from pysnmp import nextid, debug class MsgAndPduDispatcher: """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 self.__transportInfo = {} 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 -> noop # 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, # timeout expressed in dispatcher ticks cbFun=None, cbCtx=None ): """PDU dispatcher -- prepare and serialize a request or notification""" # 4.1.1.2 k = int(messageProcessingModel) if k in snmpEngine.messageProcessingSubsystems: mpHandler = snmpEngine.messageProcessingSubsystems[k] else: raise error.StatusInformation( errorIndication=errind.unsupportedMsgProcessingModel ) debug.logger & debug.flagDsp and debug.logger('sendPdu: securityName %s, PDU\n%s' % (securityName, PDU.prettyPrint())) # 4.1.1.3 sendPduHandle = self.__sendPduHandle() if expectResponse: self.__cache.add( sendPduHandle, messageProcessingModel=messageProcessingModel, sendPduHandle=sendPduHandle, timeout=timeout+snmpEngine.transportDispatcher.getTimerTicks(), cbFun=cbFun, cbCtx=cbCtx ) debug.logger & debug.flagDsp and debug.logger('sendPdu: current time %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)) # 4.1.1.4 & 4.1.1.5 try: ( destTransportDomain, destTransportAddress, outgoingMessage ) = mpHandler.prepareOutgoingMessage( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, expectResponse, sendPduHandle ) debug.logger & debug.flagDsp and debug.logger('sendPdu: MP succeeded') except error.StatusInformation: if expectResponse: self.__cache.pop(sendPduHandle) # XXX is it still needed here? # 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') try: snmpEngine.transportDispatcher.sendMessage( outgoingMessage, destTransportDomain, destTransportAddress ) except PySnmpError: if expectResponse: self.__cache.pop(sendPduHandle) raise # Update cache with orignal req params (used for retrying) if expectResponse: self.__cache.update( sendPduHandle, transportDomain=transportDomain, transportAddress=transportAddress, securityModel=securityModel, securityName=securityName, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, pduVersion=pduVersion, PDU=PDU ) return sendPduHandle # 4.1.2.1 def returnResponsePdu( self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference, statusInformation ): """PDU dispatcher -- prepare and serialize a response""" # Extract input values and initialize defaults k = int(messageProcessingModel) if k in snmpEngine.messageProcessingSubsystems: mpHandler = snmpEngine.messageProcessingSubsystems[k] else: raise error.StatusInformation( errorIndication=errind.unsupportedMsgProcessingModel ) debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: PDU %s' % (PDU and PDU.prettyPrint() or "",)) # 4.1.2.2 try: ( destTransportDomain, destTransportAddress, outgoingMessage ) = mpHandler.prepareResponseMessage( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference, statusInformation ) debug.logger & debug.flagDsp and debug.logger('returnResponsePdu: MP suceeded') except error.StatusInformation: # 4.1.2.3 raise # Handle oversized messages XXX transport constrains? snmpEngineMaxMessageSize, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') if snmpEngineMaxMessageSize.syntax and \ len(outgoingMessage) > snmpEngineMaxMessageSize.syntax: snmpSilentDrops, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 raise error.StatusInformation(errorIndication=errind.tooBig) # 4.1.2.4 snmpEngine.transportDispatcher.sendMessage( outgoingMessage, destTransportDomain, destTransportAddress ) # 4.2.1 def receiveMessage( self, snmpEngine, transportDomain, transportAddress, wholeMsg ): """Message dispatcher -- de-serialize message into PDU""" # 4.2.1.1 snmpInPkts, = self.mibInstrumController.mibBuilder.importSymbols( '__SNMPv2-MIB', 'snmpInPkts' ) snmpInPkts.syntax = snmpInPkts.syntax + 1 # 4.2.1.2 try: restOfWholeMsg = null # XXX fix decoder non-recursive return msgVersion = verdec.decodeMessageVersion(wholeMsg) except error.ProtocolError: snmpInASNParseErrs, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax = 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 k = int(messageProcessingModel) if k in snmpEngine.messageProcessingSubsystems: mpHandler = snmpEngine.messageProcessingSubsystems[k] else: snmpInBadVersions, = self.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadVersions') snmpInBadVersions.syntax = snmpInBadVersions.syntax + 1 return restOfWholeMsg # 4.2.1.3 -- no-op # 4.2.1.4 try: ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, pduType, sendPduHandle, maxSizeResponseScopedPDU, statusInformation, stateReference ) = mpHandler.prepareDataElements( snmpEngine, transportDomain, transportAddress, wholeMsg ) debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded') except error.StatusInformation: statusInformation = sys.exc_info()[1] if 'sendPduHandle' in statusInformation: # Dropped REPORT -- re-run pending reqs queue as some # of them may be waiting for this REPORT debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP failed, statusInformation %s, forcing a retry' % statusInformation) self.__expireRequest( statusInformation['sendPduHandle'], self.__cache.pop(statusInformation['sendPduHandle']), snmpEngine, statusInformation ) return restOfWholeMsg debug.logger & debug.flagDsp and debug.logger('receiveMessage: PDU %s' % PDU.prettyPrint()) # 4.2.2 if sendPduHandle is None: # 4.2.2.1 (request or notification) debug.logger & debug.flagDsp and debug.logger('receiveMessage: pduType %s' % pduType) # 4.2.2.1.1 processPdu = self.getRegisteredApp(contextEngineId, pduType) # 4.2.2.1.2 if processPdu is None: # 4.2.2.1.2.a snmpUnknownPDUHandlers, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownPDUHandlers') snmpUnknownPDUHandlers.syntax = snmpUnknownPDUHandlers.syntax+1 # 4.2.2.1.2.b statusInformation = { 'errorIndication': errind.unknownPDUHandler, 'oid': snmpUnknownPDUHandlers.name, 'val': snmpUnknownPDUHandlers.syntax } debug.logger & debug.flagDsp and debug.logger('receiveMessage: unhandled PDU type') # XXX fails on unknown PDU try: ( destTransportDomain, destTransportAddress, outgoingMessage ) = mpHandler.prepareResponseMessage( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference, statusInformation ) except error.StatusInformation: debug.logger & debug.flagDsp and debug.logger('receiveMessage: report failed, statusInformation %s' % sys.exc_info()[1]) return restOfWholeMsg # 4.2.2.1.2.c try: snmpEngine.transportDispatcher.sendMessage( outgoingMessage, destTransportDomain, destTransportAddress ) except PySnmpError: # XXX pass debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded') # 4.2.2.1.2.d return restOfWholeMsg else: # Pass transport info to app if stateReference is not None: self.__transportInfo[stateReference] = ( transportDomain, transportAddress ) # 4.2.2.1.3 processPdu( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference ) if stateReference is not None: del self.__transportInfo[stateReference] debug.logger & debug.flagDsp and debug.logger('receiveMessage: processPdu succeeded') return restOfWholeMsg else: # 4.2.2.2 (response) # 4.2.2.2.1 cachedParams = self.__cache.pop(sendPduHandle) # 4.2.2.2.2 if cachedParams is None: snmpUnknownPDUHandlers, = self.mibInstrumController.mibBuilder.importSymbols('__SNMP-MPD-MIB', 'snmpUnknownPDUHandlers') snmpUnknownPDUHandlers.syntax = snmpUnknownPDUHandlers.syntax+1 return restOfWholeMsg debug.logger & debug.flagDsp and debug.logger('receiveMessage: cache read by sendPduHandle %s' % sendPduHandle) # 4.2.2.2.3 # no-op ? XXX # 4.2.2.2.4 processResponsePdu = cachedParams['cbFun'] processResponsePdu( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, cachedParams['sendPduHandle'], cachedParams['cbCtx'] ) debug.logger & debug.flagDsp and debug.logger('receiveMessage: processResponsePdu succeeded') return restOfWholeMsg def releaseStateInformation( self, snmpEngine, sendPduHandle, messageProcessingModel ): k = int(messageProcessingModel) if k in snmpEngine.messageProcessingSubsystems: mpHandler = snmpEngine.messageProcessingSubsystems[k] mpHandler.releaseStateInformation(sendPduHandle) # Cache expiration stuff def __expireRequest(self, cacheKey, cachedParams, snmpEngine, statusInformation=None): timeNow = snmpEngine.transportDispatcher.getTimerTicks() timeoutAt = cachedParams['timeout'] if statusInformation is None and timeNow < timeoutAt: return processResponsePdu = cachedParams['cbFun'] debug.logger & debug.flagDsp and debug.logger('__expireRequest: req cachedParams %s' % cachedParams) # Fail timed-out requests if not statusInformation: statusInformation = error.StatusInformation( errorIndication=errind.requestTimedOut ) self.releaseStateInformation( snmpEngine, cachedParams['sendPduHandle'], cachedParams['messageProcessingModel'] ) processResponsePdu( snmpEngine, None, None, None, None, None, None, None, None, statusInformation, cachedParams['sendPduHandle'], cachedParams['cbCtx'] ) return 1 def receiveTimerTick(self, snmpEngine, timeNow): self.__cache.expire(self.__expireRequest, snmpEngine) pysnmp-4.2.5/pysnmp/proto/rfc3411.py0000644000076400001440000000235610722354502017325 0ustar ilyausers00000000000000# SNMP PDU taxonomy 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.2.5/pysnmp/proto/rfc1905.py0000644000076400001440000001173311777312136017342 0ustar ilyausers00000000000000from pyasn1.type import univ, tag, constraint, namedtype, namedval from pysnmp.proto import rfc1902 # Value reference -- max bindings in VarBindList max_bindings = rfc1902.Integer(2147483647) # Take SNMP exception values out of BindValue structure for convenience 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', univ.Null()), 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.2.5/pysnmp/proto/cache.py0000644000076400001440000000167311655706725017324 0ustar ilyausers00000000000000from pysnmp.proto import error class Cache: def __init__(self): self.__cacheRepository = {} def add(self, index, **kwargs): self.__cacheRepository[index] = kwargs return index def pop(self, index): if index in self.__cacheRepository: cachedParams = self.__cacheRepository[index] else: return del self.__cacheRepository[index] return cachedParams def update(self, index, **kwargs): if index not in self.__cacheRepository: raise error.ProtocolError( 'Cache miss on update for %s' % kwargs ) self.__cacheRepository[index].update(kwargs) def expire(self, cbFun, cbCtx): for index, cachedParams in list(self.__cacheRepository.items()): if cbFun: if cbFun(index, cachedParams, cbCtx): del self.__cacheRepository[index] pysnmp-4.2.5/pysnmp/proto/rfc1155.py0000644000076400001440000000720011656240243017324 0ustar ilyausers00000000000000from pyasn1.type import univ, tag, constraint, namedtype from pyasn1.error import PyAsn1Error from pysnmp.proto import error class IpAddress(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00) ) subtypeSpec = univ.OctetString.subtypeSpec+constraint.ValueSizeConstraint( 4, 4 ) def prettyIn(self, value): if isinstance(value, str) and len(value) != 4: try: value = [ int(x) for x in value.split('.') ] except: raise error.ProtocolError('Bad IP address syntax %s' % value) if len(value) != 4: raise error.ProtocolError('Bad IP address syntax') return univ.OctetString.prettyIn(self, value) def prettyOut(self, value): if value: return '.'.join( [ '%d' % x for x in self.__class__(value).asNumbers() ] ) else: return '' class Counter(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x01) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class NetworkAddress(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('internet', IpAddress()) ) class Gauge(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x02) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class TimeTicks(univ.Integer): tagSet = univ.Integer.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03) ) subtypeSpec = univ.Integer.subtypeSpec+constraint.ValueRangeConstraint( 0, 4294967295 ) class Opaque(univ.OctetString): tagSet = univ.OctetString.tagSet.tagImplicitly( tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04) ) class ObjectName(univ.ObjectIdentifier): pass class TypeCoercionHackMixIn: # XXX # Reduce ASN1 type check to simple tag check as SMIv2 objects may # not be constraints-compatible with those used in SNMP PDU. def _verifyComponent(self, idx, value): componentType = self._componentType if componentType: if idx >= len(componentType): raise PyAsn1Error( 'Component type error out of range' ) t = componentType[idx].getType() if not t.getTagSet().isSuperTagSetOf(value.getTagSet()): raise PyAsn1Error('Component type error %r vs %r' % (t, value)) class SimpleSyntax(TypeCoercionHackMixIn, univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('number', univ.Integer()), namedtype.NamedType('string', univ.OctetString()), namedtype.NamedType('object', univ.ObjectIdentifier()), namedtype.NamedType('empty', univ.Null()) ) class ApplicationSyntax(TypeCoercionHackMixIn, univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('address', NetworkAddress()), namedtype.NamedType('counter', Counter()), namedtype.NamedType('gauge', Gauge()), namedtype.NamedType('ticks', TimeTicks()), namedtype.NamedType('arbitrary', Opaque()) ) class ObjectSyntax(univ.Choice): componentType = namedtype.NamedTypes( namedtype.NamedType('simple', SimpleSyntax()), namedtype.NamedType('application-wide', ApplicationSyntax()) ) pysnmp-4.2.5/pysnmp/proto/rfc1901.py0000644000076400001440000000063311777313644017340 0ustar ilyausers00000000000000from 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.2.5/pysnmp/proto/rfc1157.py0000644000076400001440000000572011777310116017334 0ustar ilyausers00000000000000from pyasn1.type import univ, tag, namedtype, namedval from pysnmp.proto import rfc1155 class VarBind(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('name', rfc1155.ObjectName()), namedtype.NamedType('value', rfc1155.ObjectSyntax()) ) class VarBindList(univ.SequenceOf): componentType = VarBind() _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.2.5/pysnmp/proto/errind.py0000644000076400001440000001214512061413245017520 0ustar ilyausers00000000000000# SNMPv3 error-indication values. # Object below could be compared with literals thus are backward-compatible # with original pysnmperror-indication values. class ErrorIndication: def __init__(self, descr=None): self.__value = self.__descr = self.__class__.__name__[0].lower() + self.__class__.__name__[1:] if descr: self.__descr = descr def __eq__(self, other): return self.__value == other def __ne__(self, other): return self.__value != other def __lt__(self, other): return self.__value < other def __le__(self, other): return self.__value <= other def __gt__(self, other): return self.__value > other def __ge__(self, other): return self.__value >= other def __str__(self): return self.__descr # SNMP message processing errors class 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 unsupportedSecurityLevel = UnsupportedSecurityLevel('Unsupported SNMP security level') class NotInTimeWindow(ErrorIndication): pass notInTimeWindow = NotInTimeWindow('SNMP message timing parameters not in windows of trust') # SNMP access-control errors class NoSuchView(ErrorIndication): pass noSuchView = NoSuchView('No such MIB view currently exists') class NoAccessEntry(ErrorIndication): pass noAccessEntry = NoAccessEntry('Access to MIB node denined') class NoGroupName(ErrorIndication): pass noGroupName = NoGroupName('No such VACM group configured') class NoSuchContext(ErrorIndication): pass noSuchContext = NoSuchContext('SNMP context now found') class NotInView(ErrorIndication): pass notInView = NotInView('Requested OID is out of MIB view') class AccessAllowed(ErrorIndication): pass accessAllowed = AccessAllowed() class OtherError(ErrorIndication): pass otherError = OtherError('Unspecified SNMP engine error occurred') # SNMP Apps errors class OidNotIncreasing(ErrorIndication): pass oidNotIncreasing = OidNotIncreasing('OIDs are not increasing') pysnmp-4.2.5/pysnmp/proto/proxy/0000755000076400001440000000000012222743671017051 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/proxy/__init__.py0000644000076400001440000000007311775057770021174 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/proxy/rfc2576.py0000644000076400001440000002266312153626041020524 0ustar ilyausers00000000000000# PDU v1/v2c two-way proxy from pysnmp.proto import rfc1905, rfc3411, error from pysnmp.proto.api import v1, v2c from pysnmp import debug # 2.1.1 __v1ToV2ValueMap = { v1.Integer.tagSet: v2c.Integer32(), v1.OctetString.tagSet: v2c.OctetString(), v1.Null.tagSet: v2c.Null(), v1.ObjectIdentifier.tagSet: v2c.ObjectIdentifier(), v1.IpAddress.tagSet: v2c.IpAddress(), v1.Counter.tagSet: v2c.Counter32(), v1.Gauge.tagSet: v2c.Gauge32(), v1.TimeTicks.tagSet: v2c.TimeTicks(), v1.Opaque.tagSet: v2c.Opaque() } __v2ToV1ValueMap = { # XXX do not re-create same-type items? v2c.Integer32.tagSet: v1.Integer(), v2c.OctetString.tagSet: v1.OctetString(), v2c.Null.tagSet: v1.Null(), v2c.ObjectIdentifier.tagSet: v1.ObjectIdentifier(), v2c.IpAddress.tagSet: v1.IpAddress(), v2c.Counter32.tagSet: v1.Counter(), v2c.Gauge32.tagSet: v1.Gauge(), v2c.TimeTicks.tagSet: v1.TimeTicks(), v2c.Opaque.tagSet: v1.Opaque() } # PDU map __v1ToV2PduMap = { v1.GetRequestPDU.tagSet: v2c.GetRequestPDU(), v1.GetNextRequestPDU.tagSet: v2c.GetNextRequestPDU(), v1.SetRequestPDU.tagSet: v2c.SetRequestPDU(), v1.GetResponsePDU.tagSet: v2c.ResponsePDU(), v1.TrapPDU.tagSet: v2c.SNMPv2TrapPDU() } __v2ToV1PduMap = { v2c.GetRequestPDU.tagSet: v1.GetRequestPDU(), v2c.GetNextRequestPDU.tagSet: v1.GetNextRequestPDU(), v2c.SetRequestPDU.tagSet: v1.SetRequestPDU(), v2c.ResponsePDU.tagSet: v1.GetResponsePDU(), v2c.SNMPv2TrapPDU.tagSet: v1.TrapPDU(), v2c.GetBulkRequestPDU.tagSet: v1.GetNextRequestPDU() # 4.1.1 } # Trap map __v1ToV2TrapMap = { 0: (1,3,6,1,6,3,1,1,5,1), 1: (1,3,6,1,6,3,1,1,5,2), 2: (1,3,6,1,6,3,1,1,5,3), 3: (1,3,6,1,6,3,1,1,5,4), 4: (1,3,6,1,6,3,1,1,5,5), 5: (1,3,6,1,6,3,1,1,5,6) } __v2ToV1TrapMap = { (1,3,6,1,6,3,1,1,5,1): 0, (1,3,6,1,6,3,1,1,5,2): 1, (1,3,6,1,6,3,1,1,5,3): 2, (1,3,6,1,6,3,1,1,5,4): 3, (1,3,6,1,6,3,1,1,5,5): 4, (1,3,6,1,6,3,1,1,5,6): 5 } # 4.3 __v2ToV1ErrorMap = { 0: 0, 1: 1, 5: 5, 10: 3, 9: 3, 7: 3, 8: 3, 12: 3, 6: 2, 17: 2, 11: 2, 18: 2, 13: 5, 14: 5, 15: 5, 16: 2 } __zeroInt = v1.Integer(0) def v1ToV2(v1Pdu, origV2Pdu=None): pduType = v1Pdu.tagSet v2Pdu = __v1ToV2PduMap[pduType].clone() debug.logger & debug.flagPrx and debug.logger('v1ToV2: v1Pdu %s' % v1Pdu.prettyPrint()) v2VarBinds = [] # 3.1 if pduType in rfc3411.notificationClassPDUs: # 3.1.1 sysUpTime = v1.apiTrapPDU.getTimeStamp(v1Pdu) # 3.1.2 genericTrap = v1.apiTrapPDU.getGenericTrap(v1Pdu) if genericTrap == 6: snmpTrapOIDParam = v1.apiTrapPDU.getEnterprise(v1Pdu) + (0,) + \ (int(v1.apiTrapPDU.getSpecificTrap(v1Pdu)),) # 3.1.3 else: snmpTrapOIDParam = v2c.ObjectIdentifier( __v1ToV2TrapMap[genericTrap] ) # 3.1.4 (XXX snmpTrapCommunity.0 is missing here) v2VarBinds.append((v2c.apiTrapPDU.sysUpTime, sysUpTime)) v2VarBinds.append((v2c.apiTrapPDU.snmpTrapOID, snmpTrapOIDParam)) v2VarBinds.append( (v2c.apiTrapPDU.snmpTrapAddress, v1.apiTrapPDU.getAgentAddr(v1Pdu)) ) v2VarBinds.append((v2c.apiTrapPDU.snmpTrapCommunity, v2c.OctetString(""))) v2VarBinds.append((v2c.apiTrapPDU.snmpTrapEnterprise, v1.apiTrapPDU.getEnterprise(v1Pdu))) varBinds = v1.apiTrapPDU.getVarBinds(v1Pdu) else: varBinds = v1.apiPDU.getVarBinds(v1Pdu) # Translate Var-Binds for oid, v1Val in varBinds: # 2.1.1.11 if v1Val.tagSet == v1.NetworkAddress.tagSet: v1Val = v1Val.getComponent() v2VarBinds.append( (oid, __v1ToV2ValueMap[v1Val.tagSet].clone(v1Val)) ) if pduType in rfc3411.responseClassPDUs: # 4.1.2.2.1&2 errorStatus = int(v1.apiPDU.getErrorStatus(v1Pdu)) errorIndex = int(v1.apiPDU.getErrorIndex(v1Pdu, muteErrors=True)) 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 ] # one-to-one mapping v2c.apiPDU.setErrorStatus(v2Pdu, errorStatus) v2c.apiPDU.setErrorIndex(v2Pdu, errorIndex) # 4.1.2.1 --> no-op if pduType not in rfc3411.notificationClassPDUs: v2c.apiPDU.setRequestID(v2Pdu, int(v1.apiPDU.getRequestID(v1Pdu))) v2c.apiPDU.setVarBinds(v2Pdu, v2VarBinds) debug.logger & debug.flagPrx and debug.logger('v1ToV2: v2Pdu %s' % v2Pdu.prettyPrint()) return v2Pdu def v2ToV1(v2Pdu, origV1Pdu=None): debug.logger & debug.flagPrx and debug.logger('v2ToV1: v2Pdu %s' % v2Pdu.prettyPrint()) pduType = v2Pdu.tagSet if pduType in __v2ToV1PduMap: v1Pdu = __v2ToV1PduMap[pduType].clone() else: raise error.ProtocolError('Unsupported PDU type') v2VarBinds = v2c.apiPDU.getVarBinds(v2Pdu) v1VarBinds = [] # 3.2 if pduType in rfc3411.notificationClassPDUs: # 3.2.1 (snmpTrapOID, snmpTrapOIDParam) = v2VarBinds[1] if snmpTrapOID != v2c.apiTrapPDU.snmpTrapOID: raise error.ProtocolError('Second OID not snmpTrapOID') if snmpTrapOIDParam in __v2ToV1TrapMap: for oid, val in v2VarBinds: if oid == v2c.apiTrapPDU.snmpTrapEnterprise: v1.apiTrapPDU.setEnterprise(v1Pdu, val) break else: # snmpTraps v1.apiTrapPDU.setEnterprise(v1Pdu, (1, 3, 6, 1, 6, 3, 1, 1, 5)) else: if snmpTrapOIDParam[-2] == 0: v1.apiTrapPDU.setEnterprise(v1Pdu, snmpTrapOIDParam[:-2]) else: v1.apiTrapPDU.setEnterprise(v1Pdu, snmpTrapOIDParam[:-1]) # 3.2.2 for oid, val in v2VarBinds: # snmpTrapAddress if oid == v2c.apiTrapPDU.snmpTrapAddress: v1.apiTrapPDU.setAgentAddr(v1Pdu, val) break else: v1.apiTrapPDU.setAgentAddr(v1Pdu, v1.apiTrapPDU.agentAddress) # 3.2.3 if snmpTrapOIDParam in __v2ToV1TrapMap: v1.apiTrapPDU.setGenericTrap(v1Pdu, __v2ToV1TrapMap[snmpTrapOIDParam]) else: v1.apiTrapPDU.setGenericTrap(v1Pdu, 6) # 3.2.4 if snmpTrapOIDParam in __v2ToV1TrapMap: v1.apiTrapPDU.setSpecificTrap(v1Pdu, __zeroInt) else: v1.apiTrapPDU.setSpecificTrap(v1Pdu, snmpTrapOIDParam[-1]) # 3.2.5 v1.apiTrapPDU.setTimeStamp(v1Pdu, v2VarBinds[0][1]) __v2VarBinds = [] for oid, val in v2VarBinds[2:]: if oid in __v2ToV1TrapMap or \ oid in (v2c.apiTrapPDU.sysUpTime, v2c.apiTrapPDU.snmpTrapAddress, v2c.apiTrapPDU.snmpTrapEnterprise): continue __v2VarBinds.append((oid, val)) v2VarBinds = __v2VarBinds # 3.2.6 --> done below else: v1.apiPDU.setErrorStatus(v1Pdu, __zeroInt) v1.apiPDU.setErrorIndex(v1Pdu, __zeroInt) if pduType in rfc3411.responseClassPDUs: idx = len(v2VarBinds)-1 while idx >= 0: # 4.1.2.1 oid, val = v2VarBinds[idx] if v2c.Counter64.tagSet == val.tagSet: if origV1Pdu.tagSet == v1.GetRequestPDU.tagSet: v1.apiPDU.setErrorStatus(v1Pdu, 2) v1.apiPDU.setErrorIndex(v1Pdu, idx+1) break elif origV1Pdu.tagSet == v1.GetNextRequestPDU.tagSet: raise error.StatusInformation(idx=idx, pdu=v2Pdu) else: raise error.ProtocolError('Counter64 on the way') # 4.1.2.2.1&2 if val.tagSet in (v2c.NoSuchObject.tagSet, v2c.NoSuchInstance.tagSet, v2c.EndOfMibView.tagSet): v1.apiPDU.setErrorStatus(v1Pdu, 2) v1.apiPDU.setErrorIndex(v1Pdu, idx+1) idx = idx - 1 # 4.1.2.3.1 v2ErrorStatus = v2c.apiPDU.getErrorStatus(v2Pdu) if v2ErrorStatus: v1.apiPDU.setErrorStatus( v1Pdu, __v2ToV1ErrorMap[v2ErrorStatus] ) v1.apiPDU.setErrorIndex(v1Pdu, v2c.apiPDU.getErrorIndex(v2Pdu, muteErrors=True)) # 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.2.5/pysnmp/proto/secmod/0000755000076400001440000000000012222743671017142 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/eso/0000755000076400001440000000000012222743671017730 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/eso/__init__.py0000644000076400001440000000007311775057774022057 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/eso/priv/0000755000076400001440000000000012222743671020710 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/eso/priv/aes256.py0000644000076400001440000000222512153626041022262 0ustar ilyausers00000000000000# AES 192/256 bit encryption (Internet draft) # http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 from pysnmp.proto.secmod.rfc3826.priv import aes from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import error class Aes256(aes.Aes): serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2) # cusmAESCfb256PrivProtocol keySize = 32 # 3.1.2.1 def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) localPrivKey = localPrivKey + localkey.localizeKeyMD5( localPrivKey, snmpEngineID ) elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) localPrivKey = localPrivKey + localkey.localizeKeySHA( localPrivKey, snmpEngineID ) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localPrivKey[:32] pysnmp-4.2.5/pysnmp/proto/secmod/eso/priv/__init__.py0000644000076400001440000000007311775057777023042 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/eso/priv/aes192.py0000644000076400001440000000222512153626041022261 0ustar ilyausers00000000000000# AES 192/256 bit encryption (Internet draft) # http://tools.ietf.org/html/draft-blumenthal-aes-usm-04 from pysnmp.proto.secmod.rfc3826.priv import aes from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import error class Aes192(aes.Aes): serviceID = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1) # cusmAESCfb192PrivProtocol keySize = 24 # 3.1.2.1 def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) localPrivKey = localPrivKey + localkey.localizeKeyMD5( localPrivKey, snmpEngineID ) elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) localPrivKey = localPrivKey + localkey.localizeKeySHA( localPrivKey, snmpEngineID ) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localPrivKey[:24] pysnmp-4.2.5/pysnmp/proto/secmod/eso/priv/des3.py0000644000076400001440000001205512162602665022123 0ustar ilyausers00000000000000# Reeder 3DES-EDE for USM (Internet draft) # http://www.snmp.com/eso/draft-reeder-snmpv3-usm-3desede-00.txt import random from pysnmp.proto.secmod.rfc3414.priv import base from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import errind, error from pyasn1.type import univ from pyasn1.compat.octets import null try: from Crypto.Cipher import DES3 except ImportError: DES3 = None random.seed() # 5.1.1 class Des3(base.AbstractEncryptionService): serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3) # usm3DESEDEPrivProtocol _localInt = random.randrange(0, 0xffffffff) def hashPassphrase(self, authProtocol, privKey): if authProtocol == hmacmd5.HmacMd5.serviceID: return localkey.hashPassphraseMD5(privKey) elif authProtocol == hmacsha.HmacSha.serviceID: return localkey.hashPassphraseSHA(privKey) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) localPrivKey = localPrivKey + localkey.localizeKeyMD5( localPrivKey, snmpEngineID ) elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) localPrivKey = localPrivKey + localkey.localizeKeySHA( localPrivKey, snmpEngineID ) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localPrivKey[:32] # key+IV # 5.1.1.1 def __getEncryptionKey(self, privKey, snmpEngineBoots): # 5.1.1.1.1 des3Key = privKey[:24] preIV = privKey[24:32] securityEngineBoots = int(snmpEngineBoots) salt = [ securityEngineBoots>>24&0xff, securityEngineBoots>>16&0xff, securityEngineBoots>>8&0xff, securityEngineBoots&0xff, self._localInt>>24&0xff, self._localInt>>16&0xff, self._localInt>>8&0xff, self._localInt&0xff ] if self._localInt == 0xffffffff: self._localInt = 0 else: self._localInt = self._localInt + 1 # salt not yet hashed XXX return des3Key.asOctets(), \ univ.OctetString(salt).asOctets(), \ univ.OctetString(map(lambda x,y:x^y, salt, preIV.asNumbers())).asOctets() def __getDecryptionKey(self, privKey, salt): return privKey[:24].asOctets(), \ univ.OctetString(map(lambda x,y:x^y, salt.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() cipherblock = iv ciphertext = null while plaintext: cipherblock = des3Obj.encrypt( univ.OctetString(map(lambda x,y:x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(plaintext[:8]).asNumbers())).asOctets() ) ciphertext = ciphertext + cipherblock plaintext = plaintext[8:] return univ.OctetString(ciphertext), privParameters # 5.1.1.3 def decryptData(self, decryptKey, privParameters, encryptedData): if DES3 is None: raise error.StatusInformation( errorIndication=errind.decryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError ) des3Key, iv = self.__getDecryptionKey(decryptKey, salt) if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError ) des3Obj = DES3.new(des3Key, DES3.MODE_CBC, iv) plaintext = null ciphertext = encryptedData.asOctets() cipherblock = iv while ciphertext: plaintext = plaintext + univ.OctetString(map(lambda x,y: x^y, univ.OctetString(cipherblock).asNumbers(), univ.OctetString(des3Obj.decrypt(ciphertext[:8])).asNumbers())).asOctets() cipherblock = ciphertext[:8] ciphertext = ciphertext[8:] return plaintext pysnmp-4.2.5/pysnmp/proto/secmod/__init__.py0000644000076400001440000000007311775060003021244 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/0000755000076400001440000000000012222743671020230 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/auth/0000755000076400001440000000000012222743671021171 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/auth/__init__.py0000644000076400001440000000007311775060006023276 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/auth/hmacmd5.py0000644000076400001440000000634411655706726023101 0ustar ilyausers00000000000000try: from hashlib import md5 except ImportError: import md5 md5 = md5.new from pyasn1.type import univ from pysnmp.proto.secmod.rfc3414.auth import base from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import errind, error _twelveZeros = univ.OctetString((0,)*12).asOctets() _fortyEightZeros = (0,)*48 # rfc3414: 6.2.4 class HmacMd5(base.AbstractAuthenticationService): serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2) # usmHMACMD5AuthProtocol __ipad = [0x36]*64 __opad = [0x5C]*64 def hashPassphrase(self, authKey): return localkey.hashPassphraseMD5(authKey) def localizeKey(self, authKey, snmpEngineID): return localkey.localizeKeyMD5(authKey, snmpEngineID) # 6.3.1 def authenticateOutgoingMsg(self, authKey, wholeMsg): # Here we expect calling secmod to indicate where the digest # should be in the substrate. Also, it pre-sets digest placeholder # so we hash wholeMsg out of the box. # Yes, that's ugly but that's rfc... l = wholeMsg.find(_twelveZeros) if l == -1: raise error.ProtocolError('Cant locate digest placeholder') wholeHead = wholeMsg[:l] wholeTail = wholeMsg[l+12:] # 6.3.1.1 # 6.3.1.2a extendedAuthKey = authKey.asNumbers() + _fortyEightZeros # 6.3.1.2b --> noop # 6.3.1.2c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) ) # 6.3.1.2d --> noop # 6.3.1.2e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) ) # 6.3.1.3 d1 = md5(k1.asOctets()+wholeMsg).digest() # 6.3.1.4 d2 = md5(k2.asOctets()+d1).digest() mac = d2[:12] # 6.3.1.5 & 6 return wholeHead + mac + wholeTail # 6.3.2 def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): # 6.3.2.1 & 2 if len(authParameters) != 12: raise error.StatusInformation( errorIndication=errind.authenticationError ) # 6.3.2.3 l = wholeMsg.find(authParameters.asOctets()) if l == -1: raise error.ProtocolError('Cant locate digest in wholeMsg') wholeHead = wholeMsg[:l] wholeTail = wholeMsg[l+12:] authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail # 6.3.2.4a extendedAuthKey = authKey.asNumbers() + _fortyEightZeros # 6.3.2.4b --> noop # 6.3.2.4c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) ) # 6.3.2.4d --> noop # 6.3.2.4e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) ) # 6.3.2.5a d1 = md5(k1.asOctets()+authenticatedWholeMsg).digest() # 6.3.2.5b d2 = md5(k2.asOctets()+d1).digest() # 6.3.2.5c mac = d2[:12] # 6.3.2.6 if mac != authParameters: raise error.StatusInformation( errorIndication=errind.authenticationFailure ) return authenticatedWholeMsg pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/auth/noauth.py0000644000076400001440000000120411514704777023045 0ustar ilyausers00000000000000from 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.2.5/pysnmp/proto/secmod/rfc3414/auth/base.py0000644000076400001440000000112311514704777022461 0ustar ilyausers00000000000000from pysnmp.proto import errind, error class AbstractAuthenticationService: serviceID = None def hashPassphrase(self, authKey): raise error.ProtocolError(errind.noAuthentication) def localizeKey(self, authKey, snmpEngineID): raise error.ProtocolError(errind.noAuthentication) # 7.2.4.1 def authenticateOutgoingMsg(self, authKey, wholeMsg): raise error.ProtocolError(errind.noAuthentication) # 7.2.4.2 def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): raise error.ProtocolError(errind.noAuthentication) pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/auth/hmacsha.py0000644000076400001440000000634211655706726023165 0ustar ilyausers00000000000000try: from hashlib import sha1 except ImportError: import sha sha1 = sha.new from pyasn1.type import univ from pysnmp.proto.secmod.rfc3414.auth import base from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import errind, error _twelveZeros = univ.OctetString((0,)*12).asOctets() _fortyFourZeros = (0,)*44 # 7.2.4 class HmacSha(base.AbstractAuthenticationService): serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3) # usmHMACSHAAuthProtocol __ipad = [0x36]*64 __opad = [0x5C]*64 def hashPassphrase(self, authKey): return localkey.hashPassphraseSHA(authKey) def localizeKey(self, authKey, snmpEngineID): return localkey.localizeKeySHA(authKey, snmpEngineID) # 7.3.1 def authenticateOutgoingMsg(self, authKey, wholeMsg): # 7.3.1.1 # Here we expect calling secmod to indicate where the digest # should be in the substrate. Also, it pre-sets digest placeholder # so we hash wholeMsg out of the box. # Yes, that's ugly but that's rfc... l = wholeMsg.find(_twelveZeros) if l == -1: raise error.ProtocolError('Cant locate digest placeholder') wholeHead = wholeMsg[:l] wholeTail = wholeMsg[l+12:] # 7.3.1.2a extendedAuthKey = authKey.asNumbers() + _fortyFourZeros # 7.3.1.2b -- noop # 7.3.1.2c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) ) # 7.3.1.2d -- noop # 7.3.1.2e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) ) # 7.3.1.3 d1 = sha1(k1.asOctets()+wholeMsg).digest() # 7.3.1.4 d2 = sha1(k2.asOctets()+d1).digest() mac = d2[:12] # 7.3.1.5 & 6 return wholeHead + mac + wholeTail # 7.3.2 def authenticateIncomingMsg(self, authKey, authParameters, wholeMsg): # 7.3.2.1 & 2 if len(authParameters) != 12: raise error.StatusInformation( errorIndication=errind.authenticationError ) # 7.3.2.3 l = wholeMsg.find(authParameters.asOctets()) if l == -1: raise error.ProtocolError('Cant locate digest in wholeMsg') wholeHead = wholeMsg[:l] wholeTail = wholeMsg[l+12:] authenticatedWholeMsg = wholeHead + _twelveZeros + wholeTail # 7.3.2.4a extendedAuthKey = authKey.asNumbers() + _fortyFourZeros # 7.3.2.4b --> noop # 7.3.2.4c k1 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__ipad) ) # 7.3.2.4d --> noop # 7.3.2.4e k2 = univ.OctetString( map(lambda x,y: x^y, extendedAuthKey, self.__opad) ) # 7.3.2.5a d1 = sha1(k1.asOctets()+authenticatedWholeMsg).digest() # 7.3.2.5b d2 = sha1(k2.asOctets()+d1).digest() # 7.3.2.5c mac = d2[:12] # 7.3.2.6 if mac != authParameters: raise error.StatusInformation( errorIndication=errind.authenticationFailure ) return authenticatedWholeMsg pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/__init__.py0000644000076400001440000000014510253533125022332 0ustar ilyausers00000000000000from pysnmp.proto.secmod.rfc3414 import service SnmpUSMSecurityModel = service.SnmpUSMSecurityModel pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/service.py0000644000076400001440000013755512220315673022255 0ustar ilyausers00000000000000# SNMP v3 USM model services import time, sys from pysnmp.proto.secmod.base import AbstractSecurityModel from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha, noauth from pysnmp.proto.secmod.rfc3414.priv import des, nopriv from pysnmp.proto.secmod.rfc3826.priv import aes from pysnmp.proto.secmod.eso.priv import des3, aes192, aes256 from pysnmp.smi.error import NoSuchInstanceError from pysnmp.proto import rfc1155, errind, error from pysnmp import debug from pyasn1.type import univ, namedtype, constraint from pyasn1.codec.ber import encoder, decoder from pyasn1.error import PyAsn1Error from pyasn1.compat.octets import null # USM security params class UsmSecurityParameters(rfc1155.TypeCoercionHackMixIn, univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('msgAuthoritativeEngineID', univ.OctetString()), namedtype.NamedType('msgAuthoritativeEngineBoots', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), namedtype.NamedType('msgAuthoritativeEngineTime', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, 2147483647))), namedtype.NamedType('msgUserName', univ.OctetString().subtype(subtypeSpec=constraint.ValueSizeConstraint(0, 32))), namedtype.NamedType('msgAuthenticationParameters', univ.OctetString()), namedtype.NamedType('msgPrivacyParameters', univ.OctetString()) ) class SnmpUSMSecurityModel(AbstractSecurityModel): securityModelID = 3 authServices = { hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), noauth.NoAuth.serviceID: noauth.NoAuth() } privServices = { des.Des.serviceID: des.Des(), des3.Des3.serviceID: des3.Des3(), aes.Aes.serviceID: aes.Aes(), aes192.Aes192.serviceID: aes192.Aes192(), aes256.Aes256.serviceID: aes256.Aes256(), nopriv.NoPriv.serviceID: nopriv.NoPriv() } def __init__(self): AbstractSecurityModel.__init__(self) self.__securityParametersSpec = UsmSecurityParameters() self.__timeline = {} self.__timelineExpQueue = {} self.__expirationTimer = 0 self.__paramsBranchId = -1 def __sec2usr(self, snmpEngine, securityName, securityEngineID=None): usmUserEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEngineID') if self.__paramsBranchId != usmUserEngineID.branchVersionId: usmUserName, usmUserSecurityName = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserName', 'usmUserSecurityName') self.__securityToUserMap = {} nextMibNode = usmUserEngineID while 1: 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, = snmpEngine.msgAndPduDsp.mibInstrumController.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 def __getUserInfo( self, 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 ): snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax # 3.1.1 if securityStateReference is not None: # 3.1.1a cachedSecurityData = self._cache.pop(securityStateReference) usmUserName = cachedSecurityData['msgUserName'] if '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: user info read from cache') elif securityName: # 3.1.1b try: ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized ) = self.__getUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, securityEngineID, self.__sec2usr(snmpEngine, securityName, securityEngineID) ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read user info') except NoSuchInstanceError: pysnmpUsmDiscovery, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscovery') __reportUnknownName = not pysnmpUsmDiscovery.syntax if not __reportUnknownName: try: ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized ) = self.__cloneUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, securityEngineID, self.__sec2usr(snmpEngine, securityName) ) except NoSuchInstanceError: __reportUnknownName = 1 if __reportUnknownName: raise error.StatusInformation( errorIndication = errind.unknownSecurityName ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info') except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInGenErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax = 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('__generateRequestOrResponseMsg: use empty USM data') debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: local usmUserName %r usmUserSecurityName %r usmUserAuthProtocol %s usmUserPrivProtocol %s securityEngineID %r securityName %r' % (usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserPrivProtocol, securityEngineID, securityName)) msg = globalData # 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 ) # 3.1.6a if securityStateReference is None and ( # request type check added securityLevel == 3 or securityLevel == 2 ): if securityEngineID in self.__timeline: ( snmpEngineBoots, snmpEngineTime, latestReceivedEngineTime, latestUpdateTimestamp) = self.__timeline[ securityEngineID ] debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from timeline') else: # 2.3 XXX is this correct? snmpEngineBoots = snmpEngineTime = 0 debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: no timeline for securityEngineID %r' % (securityEngineID,)) # 3.1.6.b elif securityStateReference is not None: # XXX Report? ( snmpEngineBoots, snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') snmpEngineBoots = snmpEngineBoots.syntax snmpEngineTime = snmpEngineTime.syntax.clone() debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: read snmpEngineBoots, snmpEngineTime from LCD') # 3.1.6.c else: snmpEngineBoots = snmpEngineTime = 0 debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: assuming zero snmpEngineBoots, snmpEngineTime') debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: use snmpEngineBoots %s snmpEngineTime %s for securityEngineID %r' % (snmpEngineBoots, snmpEngineTime, securityEngineID)) # 3.1.4a if securityLevel == 3: if usmUserPrivProtocol in self.privServices: privHandler = self.privServices[usmUserPrivProtocol] else: raise error.StatusInformation( errorIndication = errind.encryptionError ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU %s' % scopedPDU.prettyPrint()) 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)) ( encryptedData, privParameters ) = privHandler.encryptData( usmUserPrivKeyLocalized, ( snmpEngineBoots, snmpEngineTime, None ), dataToEncrypt ) securityParameters.setComponentByPosition( 5, privParameters, verifyConstraints=False ) scopedPDUData.setComponentByPosition( 1, encryptedData, verifyConstraints=False ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: scopedPDU ciphered 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 ) securityParameters.setComponentByPosition( 1, snmpEngineBoots, verifyConstraints=False ) securityParameters.setComponentByPosition( 2, snmpEngineTime, verifyConstraints=False ) # 3.1.7 securityParameters.setComponentByPosition( 3, usmUserName, verifyConstraints=False ) # 3.1.8a if securityLevel == 3 or securityLevel == 2: if usmUserAuthProtocol in self.authServices: authHandler = self.authServices[usmUserAuthProtocol] else: raise error.StatusInformation( errorIndication = errind.authenticationFailure ) # extra-wild hack to facilitate BER substrate in-place re-write securityParameters.setComponentByPosition( 4, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) 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 ) authenticatedWholeMsg = authHandler.authenticateOutgoingMsg( usmUserAuthKeyLocalized, wholeMsg ) # 3.1.8b else: securityParameters.setComponentByPosition( 4, '', verifyConstraints=False ) debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: %s' % (securityParameters.prettyPrint(),)) try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=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 # XXX ): # 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 try: securityParameters, rest = decoder.decode( securityParameters, asn1Spec=self.__securityParametersSpec ) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax = snmpInASNParseErrs.syntax + 1 raise error.StatusInformation( errorIndication=errind.parseError ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (securityParameters.prettyPrint(),)) # 3.2.2 msgAuthoritativeEngineID = securityParameters.getComponentByPosition(0) securityStateReference = self._cache.push( msgUserName=securityParameters.getComponentByPosition(3) ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cache write securityStateReference %s by msgUserName %s' % (securityStateReference, securityParameters.getComponentByPosition(3))) scopedPduData = msg.getComponentByPosition(3) # Used for error reporting contextEngineId = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax contextName = null # 3.2.3 if msgAuthoritativeEngineID not in self.__timeline: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %r' % (msgAuthoritativeEngineID,)) if not msgAuthoritativeEngineID: # 3.2.3b usmStatsUnknownEngineIDs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownEngineIDs') usmStatsUnknownEngineIDs.syntax = usmStatsUnknownEngineIDs.syntax+1 debug.logger & debug.flagSM and debug.logger('processIncomingMsg: null securityEngineID') pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') if pysnmpUsmDiscoverable.syntax: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: request EngineID discovery') # Report original contextName if scopedPduData.getName() != 'plaintext': debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPduData not plaintext %s' % scopedPduData.prettyPrint()) raise error.StatusInformation( errorIndication = errind.unknownEngineID ) # 7.2.6.a.1 scopedPdu = scopedPduData.getComponent() contextEngineId = scopedPdu.getComponentByPosition(0) contextName = scopedPdu.getComponentByPosition(1) raise error.StatusInformation( errorIndication = errind.unknownEngineID, oid=usmStatsUnknownEngineIDs.name, val=usmStatsUnknownEngineIDs.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, scopedPDU=scopedPdu, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) else: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: will not discover EngineID') # free securityStateReference XXX raise error.StatusInformation( errorIndication = errind.unknownEngineID ) snmpEngineID = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID')[0].syntax msgUserName = securityParameters.getComponentByPosition(3) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read from securityParams msgAuthoritativeEngineID %r msgUserName %r' % (msgAuthoritativeEngineID, msgUserName)) if msgUserName: # 3.2.4 try: ( 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: pysnmpUsmDiscoverable, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable') __reportUnknownName = not pysnmpUsmDiscoverable.syntax if not __reportUnknownName: try: ( usmUserName, usmUserSecurityName, usmUserAuthProtocol, usmUserAuthKeyLocalized, usmUserPrivProtocol, usmUserPrivKeyLocalized ) = self.__cloneUserInfo( snmpEngine.msgAndPduDsp.mibInstrumController, msgAuthoritativeEngineID, msgUserName ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cloned user info') except NoSuchInstanceError: __reportUnknownName = 1 debug.logger & debug.flagSM and debug.logger('processIncomingMsg: unknown securityEngineID %r msgUserName %r' % (msgAuthoritativeEngineID, msgUserName)) if __reportUnknownName: usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 raise error.StatusInformation( errorIndication = errind.unknownSecurityName, oid = usmStatsUnknownUserNames.name, val = usmStatsUnknownUserNames.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) snmpInGenErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax = 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 ) # 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: __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, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnsupportedSecLevels') usmStatsUnsupportedSecLevels.syntax = 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, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) # 3.2.6 if securityLevel == 3 or securityLevel == 2: if usmUserAuthProtocol in self.authServices: authHandler = self.authServices[usmUserAuthProtocol] else: raise error.StatusInformation( errorIndication = errind.authenticationFailure ) try: authenticatedWholeMsg = authHandler.authenticateIncomingMsg( usmUserAuthKeyLocalized, securityParameters.getComponentByPosition(4), wholeMsg ) except error.StatusInformation: usmStatsWrongDigests, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsWrongDigests') usmStatsWrongDigests.syntax = usmStatsWrongDigests.syntax+1 raise error.StatusInformation( errorIndication = errind.authenticationFailure, oid=usmStatsWrongDigests.name, val=usmStatsWrongDigests.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: incoming msg authenticated') if msgAuthoritativeEngineID: # 3.2.3a moved down here to execute only for authed msg self.__timeline[msgAuthoritativeEngineID] = ( securityParameters.getComponentByPosition(1), securityParameters.getComponentByPosition(2), securityParameters.getComponentByPosition(2), int(time.time()) ) expireAt = int(self.__expirationTimer + 300 / snmpEngine.transportDispatcher.getTimerResolution()) if expireAt not in self.__timelineExpQueue: self.__timelineExpQueue[expireAt] = [] self.__timelineExpQueue[expireAt].append( msgAuthoritativeEngineID ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: store timeline for securityEngineID %r' % (msgAuthoritativeEngineID,)) # 3.2.7 if securityLevel == 3 or securityLevel == 2: if msgAuthoritativeEngineID == snmpEngineID: # Authoritative SNMP engine: use local notion (SF bug #1649032) ( snmpEngineBoots, snmpEngineTime ) = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots', 'snmpEngineTime') snmpEngineBoots = snmpEngineBoots.syntax snmpEngineTime = snmpEngineTime.syntax.clone() idleTime = 0 debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read snmpEngineBoots (%s), snmpEngineTime (%s) from LCD' % (snmpEngineBoots, snmpEngineTime)) else: # Non-authoritative SNMP engine: use cached estimates if msgAuthoritativeEngineID in self.__timeline: ( snmpEngineBoots, snmpEngineTime, latestReceivedEngineTime, latestUpdateTimestamp ) = self.__timeline[ msgAuthoritativeEngineID ] # time passed since last talk with this SNMP engine idleTime = int(time.time())-latestUpdateTimestamp debug.logger & debug.flagSM and debug.logger('processIncomingMsg: read timeline snmpEngineBoots %s snmpEngineTime %s for msgAuthoritativeEngineID %r, idle time %s secs' % (snmpEngineBoots, snmpEngineTime, msgAuthoritativeEngineID, idleTime)) else: raise error.ProtocolError('Peer SNMP engine info missing') msgAuthoritativeEngineBoots = securityParameters.getComponentByPosition(1) msgAuthoritativeEngineTime = securityParameters.getComponentByPosition(2) # 3.2.7a if msgAuthoritativeEngineID == snmpEngineID: if snmpEngineBoots == 2147483647 or \ snmpEngineBoots != msgAuthoritativeEngineBoots or \ abs(idleTime + int(snmpEngineTime) - \ int(msgAuthoritativeEngineTime)) > 150: usmStatsNotInTimeWindows, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsNotInTimeWindows') usmStatsNotInTimeWindows.syntax = usmStatsNotInTimeWindows.syntax+1 raise error.StatusInformation( errorIndication = errind.notInTimeWindow, oid=usmStatsNotInTimeWindows.name, val=usmStatsNotInTimeWindows.syntax, securityStateReference=securityStateReference, securityLevel=2, contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) # 3.2.7b else: # 3.2.7b.1 if msgAuthoritativeEngineBoots > snmpEngineBoots or \ msgAuthoritativeEngineBoots == snmpEngineBoots and \ msgAuthoritativeEngineTime > latestReceivedEngineTime: self.__timeline[msgAuthoritativeEngineID] = ( msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineTime, int(time.time()) ) expireAt = int(self.__expirationTimer + 300 / snmpEngine.transportDispatcher.getTimerResolution()) if expireAt not in self.__timelineExpQueue: self.__timelineExpQueue[expireAt] = [] self.__timelineExpQueue[expireAt].append( msgAuthoritativeEngineID ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: stored timeline msgAuthoritativeEngineBoots %s msgAuthoritativeEngineTime %s for msgAuthoritativeEngineID %r' % (msgAuthoritativeEngineBoots, msgAuthoritativeEngineTime, msgAuthoritativeEngineID)) # 3.2.7b.2 if snmpEngineBoots == 2147483647 or \ msgAuthoritativeEngineBoots < snmpEngineBoots or \ msgAuthoritativeEngineBoots == snmpEngineBoots and \ abs(idleTime + int(snmpEngineTime) - \ int(msgAuthoritativeEngineTime)) > 150: raise error.StatusInformation( errorIndication = errind.notInTimeWindow ) # 3.2.8a if securityLevel == 3: if usmUserPrivProtocol in self.privServices: privHandler = self.privServices[usmUserPrivProtocol] else: raise error.StatusInformation( errorIndication = errind.decryptionError ) encryptedPDU = scopedPduData.getComponentByPosition(1) if encryptedPDU is None: # no ciphertext raise error.StatusInformation( errorIndication = errind.decryptionError ) try: decryptedData = privHandler.decryptData( usmUserPrivKeyLocalized, ( securityParameters.getComponentByPosition(1), securityParameters.getComponentByPosition(2), securityParameters.getComponentByPosition(5) ), encryptedPDU ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: PDU deciphered into %s' % debug.hexdump(decryptedData)) except error.StatusInformation: usmStatsDecryptionErrors, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsDecryptionErrors') usmStatsDecryptionErrors.syntax = usmStatsDecryptionErrors.syntax+1 raise error.StatusInformation( errorIndication = errind.decryptionError, oid=usmStatsDecryptionErrors.name, val=usmStatsDecryptionErrors.syntax, securityStateReference=securityStateReference, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) scopedPduSpec = scopedPduData.setComponentByPosition(0).getComponentByPosition(0) try: scopedPDU, rest = decoder.decode( decryptedData, asn1Spec=scopedPduSpec ) except PyAsn1Error: debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoder failed %s' % sys.exc_info()[0]) raise error.StatusInformation( errorIndication = errind.decryptionError ) else: # 3.2.8b scopedPDU = scopedPduData.getComponentByPosition(0) if scopedPDU is None: # no plaintext raise error.StatusInformation( errorIndication = errind.decryptionError ) debug.logger & debug.flagSM and debug.logger('processIncomingMsg: scopedPDU decoded %s' % scopedPDU.prettyPrint()) # 3.2.10 securityName = usmUserSecurityName debug.logger & debug.flagSM and debug.logger('processIncomingMsg: cached msgUserName %s info by securityStateReference %s' % (msgUserName, securityStateReference)) # Delayed to include details if not msgUserName and not msgAuthoritativeEngineID: usmStatsUnknownUserNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-USER-BASED-SM-MIB', 'usmStatsUnknownUserNames') usmStatsUnknownUserNames.syntax = usmStatsUnknownUserNames.syntax+1 raise error.StatusInformation( errorIndication=errind.unknownSecurityName, oid=usmStatsUnknownUserNames.name, val=usmStatsUnknownUserNames.syntax, securityStateReference=securityStateReference, securityEngineID=msgAuthoritativeEngineID, securityLevel=securityLevel, contextEngineId=contextEngineId, contextName=contextName, maxSizeResponseScopedPDU=maxSizeResponseScopedPDU, PDU=scopedPDU ) # 3.2.12 return ( msgAuthoritativeEngineID, securityName, scopedPDU, maxSizeResponseScopedPDU, securityStateReference ) def __expireTimelineInfo(self): if self.__expirationTimer in self.__timelineExpQueue: for engineIdKey in self.__timelineExpQueue[self.__expirationTimer]: if engineIdKey in self.__timeline: del self.__timeline[engineIdKey] debug.logger & debug.flagSM and debug.logger('__expireTimelineInfo: expiring %r' % (engineIdKey,)) del self.__timelineExpQueue[self.__expirationTimer] self.__expirationTimer = self.__expirationTimer + 1 def receiveTimerTick(self, snmpEngine, timeNow): self.__expireTimelineInfo() pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/localkey.py0000644000076400001440000000370711655706726022425 0ustar ilyausers00000000000000# Convert plaintext passphrase into a localized key try: from hashlib import md5, sha1 except ImportError: import md5, sha md5 = md5.new sha1 = sha.new from pyasn1.type import univ # RFC3414: A.2.1 def hashPassphraseMD5(passphrase): passphrase = univ.OctetString(passphrase).asOctets() md = md5() ringBuffer = passphrase * (passphrase and (64//len(passphrase)+1) or 1) ringBufferLen = len(ringBuffer) count = 0 mark = 0 while count < 16384: e = mark + 64 if e < ringBufferLen: md.update(ringBuffer[mark:e]) mark = e else: md.update( ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] ) mark = e-ringBufferLen count = count + 1 return md.digest() def localizeKeyMD5(passKey, snmpEngineId): passKey = univ.OctetString(passKey).asOctets() return md5(passKey + snmpEngineId.asOctets()+ passKey).digest() def passwordToKeyMD5(passphrase, snmpEngineId): return localizeKeyMD5(hashPassphraseMD5(passphrase), snmpEngineId) # RFC3414: A.2.2 def hashPassphraseSHA(passphrase): passphrase = univ.OctetString(passphrase).asOctets() md = sha1() ringBuffer = passphrase * (64//len(passphrase)+1) ringBufferLen = len(ringBuffer) count = 0 mark = 0 while count < 16384: e = mark + 64 if e < ringBufferLen: md.update(ringBuffer[mark:e]) mark = e else: md.update( ringBuffer[mark:ringBufferLen] + ringBuffer[0:e-ringBufferLen] ) mark = e-ringBufferLen count = count + 1 return md.digest() def localizeKeySHA(passKey, snmpEngineId): passKey = univ.OctetString(passKey).asOctets() return sha1(passKey + snmpEngineId.asOctets()+ passKey).digest() def passwordToKeySHA(passphrase, snmpEngineId): return localizeKeySHA(hashPassphraseSHA(passphrase), snmpEngineId) pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/priv/0000755000076400001440000000000012222743671021210 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/priv/__init__.py0000644000076400001440000000007311775060020023311 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/priv/nopriv.py0000644000076400001440000000122011514704777023101 0ustar ilyausers00000000000000from 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.2.5/pysnmp/proto/secmod/rfc3414/priv/des.py0000644000076400001440000001042311743227504022334 0ustar ilyausers00000000000000import random from pysnmp.proto.secmod.rfc3414.priv import base from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pysnmp.proto import errind, error from pyasn1.type import univ try: from sys import version_info except ImportError: version_info = ( 0, 0 ) # a really early version try: from Crypto.Cipher import DES except ImportError: DES = None random.seed() # 8.2.4 class Des(base.AbstractEncryptionService): serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2) # usmDESPrivProtocol if version_info < (2, 3): _localInt = int(random.random()*0xffffffff) else: _localInt = random.randrange(0, 0xffffffff) def hashPassphrase(self, authProtocol, privKey): if authProtocol == hmacmd5.HmacMd5.serviceID: return localkey.hashPassphraseMD5(privKey) elif authProtocol == hmacsha.HmacSha.serviceID: return localkey.hashPassphraseSHA(privKey) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localPrivKey[:32] # key+IV # 8.1.1.1 def __getEncryptionKey(self, privKey, snmpEngineBoots): desKey = privKey[:8] preIV = privKey[8:16] securityEngineBoots = int(snmpEngineBoots) salt = [ securityEngineBoots>>24&0xff, securityEngineBoots>>16&0xff, securityEngineBoots>>8&0xff, securityEngineBoots&0xff, self._localInt>>24&0xff, self._localInt>>16&0xff, self._localInt>>8&0xff, self._localInt&0xff ] if self._localInt == 0xffffffff: self._localInt = 0 else: self._localInt = self._localInt + 1 return desKey.asOctets(), \ univ.OctetString(salt).asOctets(), \ univ.OctetString(map(lambda x,y:x^y,salt,preIV.asNumbers())).asOctets() def __getDecryptionKey(self, privKey, salt): return privKey[:8].asOctets(), univ.OctetString( map(lambda x,y:x^y, salt.asNumbers(), privKey[8:16].asNumbers()) ).asOctets() # 8.2.4.1 def encryptData(self, encryptKey, privParameters, dataToEncrypt): if DES is None: raise error.StatusInformation( errorIndication=errind.encryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 8.3.1.1 desKey, salt, iv = self.__getEncryptionKey( encryptKey, snmpEngineBoots ) # 8.3.1.2 privParameters = univ.OctetString(salt) # 8.1.1.2 desObj = DES.new(desKey, DES.MODE_CBC, iv) plaintext = dataToEncrypt + univ.OctetString((0,) * (8 - len(dataToEncrypt) % 8)).asOctets() ciphertext = desObj.encrypt(plaintext) # 8.3.1.3 & 4 return univ.OctetString(ciphertext), privParameters # 8.2.4.2 def decryptData(self, decryptKey, privParameters, encryptedData): if DES is None: raise error.StatusInformation( errorIndication=errind.decryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 8.3.2.1 if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError ) # 8.3.2.2 noop # 8.3.2.3 desKey, iv = self.__getDecryptionKey(decryptKey, salt) # 8.3.2.4 -> 8.1.1.3 if len(encryptedData) % 8 != 0: raise error.StatusInformation( errorIndication=errind.decryptionError ) desObj = DES.new(desKey, DES.MODE_CBC, iv) # 8.3.2.6 return desObj.decrypt(encryptedData.asOctets()) pysnmp-4.2.5/pysnmp/proto/secmod/rfc3414/priv/base.py0000644000076400001440000000106411514704777022504 0ustar ilyausers00000000000000from pysnmp.proto import error class AbstractEncryptionService: serviceID = None def hashPassphrase(self, authProtocol, privKey): raise error.ProtocolError('no encryption') def localizeKey(self, authProtocol, privKey, snmpEngineID): raise error.ProtocolError('no encryption') def encryptData(self, encryptKey, privParameters, dataToEncrypt): raise error.ProtocolError('no encryption') def decryptData(self, decryptKey, privParameters, encryptedData): raise error.ProtocolError('no encryption') pysnmp-4.2.5/pysnmp/proto/secmod/rfc3826/0000755000076400001440000000000012222743671020237 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/rfc3826/__init__.py0000644000076400001440000000007311775060023022343 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/rfc3826/priv/0000755000076400001440000000000012222743671021217 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/secmod/rfc3826/priv/__init__.py0000644000076400001440000000007311775060027023327 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/proto/secmod/rfc3826/priv/aes.py0000644000076400001440000001067111655706726022357 0ustar ilyausers00000000000000import random from pyasn1.type import univ from pysnmp.proto.secmod.rfc3414.priv import base from pysnmp.proto.secmod.rfc3414.auth import hmacmd5, hmacsha from pysnmp.proto.secmod.rfc3414 import localkey from pyasn1.type import univ from pysnmp.proto import errind, error try: from Crypto.Cipher import AES except ImportError: AES = None random.seed() # RFC3826 # class Aes(base.AbstractEncryptionService): serviceID = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4) # usmAesCfb128Protocol keySize = 16 _localInt = random.randrange(0, 0xffffffffffffffff) # 3.1.2.1 def __getEncryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime): salt = [ self._localInt>>56&0xff, self._localInt>>48&0xff, self._localInt>>40&0xff, self._localInt>>32&0xff, self._localInt>>24&0xff, self._localInt>>16&0xff, self._localInt>>8&0xff, self._localInt&0xff ] if self._localInt == 0xffffffffffffffff: self._localInt = 0 else: self._localInt = self._localInt + 1 return self.__getDecryptionKey( privKey, snmpEngineBoots, snmpEngineTime, salt ) + ( univ.OctetString(salt).asOctets(), ) def __getDecryptionKey(self, privKey, snmpEngineBoots, snmpEngineTime, salt): snmpEngineBoots, snmpEngineTime, salt = ( int(snmpEngineBoots), int(snmpEngineTime), salt ) iv = [ snmpEngineBoots>>24&0xff, snmpEngineBoots>>16&0xff, snmpEngineBoots>>8&0xff, snmpEngineBoots&0xff, snmpEngineTime>>24&0xff, snmpEngineTime>>16&0xff, snmpEngineTime>>8&0xff, snmpEngineTime&0xff ] + salt return privKey[:self.keySize].asOctets(), univ.OctetString(iv).asOctets() def hashPassphrase(self, authProtocol, privKey): if authProtocol == hmacmd5.HmacMd5.serviceID: return localkey.hashPassphraseMD5(privKey) elif authProtocol == hmacsha.HmacSha.serviceID: return localkey.hashPassphraseSHA(privKey) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) def localizeKey(self, authProtocol, privKey, snmpEngineID): if authProtocol == hmacmd5.HmacMd5.serviceID: localPrivKey = localkey.localizeKeyMD5(privKey, snmpEngineID) elif authProtocol == hmacsha.HmacSha.serviceID: localPrivKey = localkey.localizeKeySHA(privKey, snmpEngineID) else: raise error.ProtocolError( 'Unknown auth protocol %s' % (authProtocol,) ) return localPrivKey[:16] # 3.2.4.1 def encryptData(self, encryptKey, privParameters, dataToEncrypt): if AES is None: raise error.StatusInformation( errorIndication=errind.encryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 3.3.1.1 aesKey, iv, salt = self.__getEncryptionKey( encryptKey, snmpEngineBoots, snmpEngineTime ) # 3.3.1.3 aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128) # PyCrypto seems to require padding dataToEncrypt = dataToEncrypt + univ.OctetString((0,) * (16-len(dataToEncrypt)%16)).asOctets() ciphertext = aesObj.encrypt(dataToEncrypt) # 3.3.1.4 return univ.OctetString(ciphertext), univ.OctetString(salt) # 3.2.4.2 def decryptData(self, decryptKey, privParameters, encryptedData): if AES is None: raise error.StatusInformation( errorIndication=errind.decryptionError ) snmpEngineBoots, snmpEngineTime, salt = privParameters # 3.3.2.1 if len(salt) != 8: raise error.StatusInformation( errorIndication=errind.decryptionError ) # 3.3.2.3 aesKey, iv = self.__getDecryptionKey( decryptKey, snmpEngineBoots, snmpEngineTime, salt ) aesObj = AES.new(aesKey, AES.MODE_CFB, iv, segment_size=128) # PyCrypto seems to require padding encryptedData = encryptedData + univ.OctetString((0,) * (16-len(encryptedData)%16)).asOctets() # 3.3.2.4-6 return aesObj.decrypt(encryptedData.asOctets()) pysnmp-4.2.5/pysnmp/proto/secmod/cache.py0000644000076400001440000000135511525167363020566 0ustar ilyausers00000000000000from pysnmp import nextid from pysnmp.proto import error class Cache: __stateReference = nextid.Integer(0xffffff) def __init__(self): self.__cacheEntries = {} def push(self, **securityData): stateReference = self.__stateReference() self.__cacheEntries[stateReference] = securityData return stateReference def pop(self, stateReference): if stateReference in self.__cacheEntries: securityData = self.__cacheEntries[stateReference] else: raise error.ProtocolError( 'Cache miss for stateReference=%s at %s' % (stateReference, self) ) del self.__cacheEntries[stateReference] return securityData pysnmp-4.2.5/pysnmp/proto/secmod/base.py0000644000076400001440000000265611525167370020440 0ustar ilyausers00000000000000from pysnmp.proto.secmod import cache from pysnmp.proto import error class AbstractSecurityModel: securityModelID = None def __init__(self): self._cache = cache.Cache() def processIncomingMsg( self, snmpEngine, messageProcessingModel, maxMessageSize, securityParameters, securityModel, securityLevel, wholeMsg, msg, ): raise error.ProtocolError( 'Security model %s not implemented' % self ) def generateRequestMsg( self, snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineID, securityName, securityLevel, scopedPDU, ): raise error.ProtocolError( 'Security model %s not implemented' % self ) def generateResponseMsg( self, snmpEngine, messageProcessingModel, globalData, maxMessageSize, securityModel, securityEngineID, securityName, securityLevel, scopedPDU, securityStateReference ): raise error.ProtocolError( 'Security model %s not implemented' % self ) def releaseStateInformation(self, stateReference): self._cache.pop(stateReference) def receiveTimerTick(self, snmpEngine, timeNow): pass pysnmp-4.2.5/pysnmp/proto/secmod/rfc2576.py0000644000076400001440000004566312143766557020642 0ustar ilyausers00000000000000# SNMP v1 & v2c security models implementation import sys from pyasn1.codec.ber import encoder from pyasn1.error import PyAsn1Error from pysnmp.proto.secmod import base from pysnmp.carrier.asynsock.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 1: try: nextMibNode = snmpTargetParamsSecurityName.getNextNode( nextMibNode.name ) except NoSuchInstanceError: break instId = nextMibNode.name[ len(snmpTargetParamsSecurityName.name): ] mibNode = snmpTargetParamsSecurityModel.getNode( snmpTargetParamsSecurityModel.name + instId ) if mibNode.syntax not in self.__nameToModelMap: self.__nameToModelMap[nextMibNode.syntax] = set() self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax) 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 1: 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 self.__securityMap[(_securityName, _contextEngineId, _contextName)] = nextMibNode.syntax 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 1: try: nextMibNode = snmpTargetAddrTagList.getNextNode( nextMibNode.name ) except NoSuchInstanceError: break instId = nextMibNode.name[len(snmpTargetAddrTagList.name):] targetAddrTDomain = snmpTargetAddrTDomain.getNode( snmpTargetAddrTDomain.name + instId ).syntax targetAddrTAddress = snmpTargetAddrTAddress.getNode( snmpTargetAddrTAddress.name + instId ).syntax targetAddrTDomain = tuple(targetAddrTDomain) if targetAddrTDomain[:len(udp.snmpUDPDomain)] == udp.snmpUDPDomain: SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') targetAddrTAddress = tuple( SnmpUDPAddress(targetAddrTAddress) ) elif targetAddrTDomain[:len(udp6.snmpUDP6Domain)] == udp6.snmpUDP6Domain: TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') targetAddrTAddress = tuple( TransportAddressIPv6(targetAddrTAddress) ) 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() if targetAddrTagList: self.__transportToTagMap[targetAddr].update( [ SnmpTagValue(x) for x in targetAddrTagList.asOctets().split() ] ) else: self.__transportToTagMap[targetAddr].add(self.__emptyTag) 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 1: try: nextMibNode = snmpTargetParamsSecurityName.getNextNode( nextMibNode.name ) except NoSuchInstanceError: break instId = nextMibNode.name[ len(snmpTargetParamsSecurityName.name): ] mibNode = snmpTargetParamsSecurityModel.getNode( snmpTargetParamsSecurityModel.name + instId ) if nextMibNode.syntax not in self.__nameToModelMap: self.__nameToModelMap[nextMibNode.syntax] = set() self.__nameToModelMap[nextMibNode.syntax].add(mibNode.syntax) 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 1: 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 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) 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 ) 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 ) 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 try: securityName, contextEngineId, contextName = self._com2sec( snmpEngine, communityName, transportInformation ) except error.StatusInformation: snmpInBadCommunityNames, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInBadCommunityNames') snmpInBadCommunityNames.syntax = snmpInBadCommunityNames.syntax+1 raise error.StatusInformation( errorIndication = errind.unknownCommunityName ) snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') securityEngineID = snmpEngineID.syntax 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.2.5/pysnmp/proto/api/0000755000076400001440000000000012222743671016441 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/proto/api/__init__.py0000644000076400001440000000032510253532010020533 0ustar ilyausers00000000000000from pysnmp.proto.api import v1, v2c, verdec # Protocol versions protoVersion1 = 0 protoVersion2c = 1 protoModules = { protoVersion1: v1, protoVersion2c: v2c } decodeMessageVersion = verdec.decodeMessageVersion pysnmp-4.2.5/pysnmp/proto/api/v1.py0000644000076400001440000001757112106205177017347 0ustar ilyausers00000000000000from pyasn1.type import univ from pysnmp.proto import rfc1155, rfc1157, error from pysnmp import nextid # Shortcuts to SNMP types Integer = univ.Integer OctetString = univ.OctetString Null = univ.Null null = Null('') ObjectIdentifier = univ.ObjectIdentifier IpAddress = rfc1155.IpAddress NetworkAddress = rfc1155.NetworkAddress Counter = rfc1155.Counter Gauge = rfc1155.Gauge TimeTicks = rfc1155.TimeTicks Opaque = rfc1155.Opaque VarBind = rfc1157.VarBind VarBindList = rfc1157.VarBindList GetRequestPDU = rfc1157.GetRequestPDU GetNextRequestPDU = rfc1157.GetNextRequestPDU GetResponsePDU = rfc1157.GetResponsePDU SetRequestPDU = rfc1157.SetRequestPDU TrapPDU = rfc1157.TrapPDU Message = rfc1157.Message class VarBindAPI: def setOIDVal(self, varBind, oidVal): (oid, val) = oidVal varBind.setComponentByPosition(0, oid) if val is None: val = null varBind.setComponentByPosition(1).getComponentByPosition(1).setComponentByType(val.getTagSet(), val, 1, verifyConstraints=False) return varBind def getOIDVal(self, varBind): return varBind[0], varBind[1].getComponent(1) apiVarBind = VarBindAPI() getNextRequestID = nextid.Integer(0xffffff) class PDUAPI: _errorStatus = rfc1157._errorStatus.clone(0) _errorIndex = Integer(0) def setDefaults(self, pdu): pdu.setComponentByPosition( 0, getNextRequestID(), verifyConstraints=False ) pdu.setComponentByPosition( 1, self._errorStatus, verifyConstraints=False ) pdu.setComponentByPosition( 2, self._errorIndex, verifyConstraints=False ) pdu.setComponentByPosition(3) def getRequestID(self, pdu): return pdu.getComponentByPosition(0) def setRequestID(self, pdu, value): pdu.setComponentByPosition(0, value) def getErrorStatus(self, pdu): return pdu.getComponentByPosition(1) def setErrorStatus(self, pdu, value): pdu.setComponentByPosition(1, value) def getErrorIndex(self, pdu, 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 def setErrorIndex(self, pdu, value): pdu.setComponentByPosition(2, value) def setEndOfMibError(self, pdu, errorIndex): self.setErrorIndex(pdu, errorIndex) self.setErrorStatus(pdu, 2) def setNoSuchInstanceError(self, pdu, errorIndex): self.setEndOfMibError(pdu, errorIndex) def getVarBindList(self, pdu): return pdu.getComponentByPosition(3) def setVarBindList(self, pdu, varBindList): varBindList = pdu.setComponentByPosition(3, varBindList) def getVarBinds(self, pdu): varBinds = [] for varBind in pdu.getComponentByPosition(3): varBinds.append(apiVarBind.getOIDVal(varBind)) return varBinds def setVarBinds(self, pdu, varBinds): varBindList = pdu.setComponentByPosition(3).getComponentByPosition(3) varBindList.clear() idx = 0 for varBind in varBinds: if isinstance(varBind, VarBind): varBindList.setComponentByPosition(idx, varBind) else: varBindList.setComponentByPosition(idx) apiVarBind.setOIDVal( varBindList.getComponentByPosition(idx), varBind ) idx = idx + 1 def getResponse(self, reqPDU): rspPDU = GetResponsePDU() self.setDefaults(rspPDU) self.setRequestID(rspPDU, self.getRequestID(reqPDU)) return rspPDU def getVarBindTable(self, reqPDU, rspPDU): if apiPDU.getErrorStatus(rspPDU) == 2: varBindRow = [] for varBind in apiPDU.getVarBinds(reqPDU): varBindRow.append((varBind[0], null)) return [ varBindRow ] else: return [ apiPDU.getVarBinds(rspPDU) ] apiPDU = PDUAPI() class TrapPDUAPI: try: import socket agentAddress = IpAddress(socket.gethostbyname(socket.gethostname())) except: agentAddress = IpAddress('0.0.0.0') _networkAddress = NetworkAddress().setComponentByPosition(0, agentAddress) _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): pdu.setComponentByPosition(0, self._entOid, verifyConstraints=False) pdu.setComponentByPosition(1, self._networkAddress, verifyConstraints=False) pdu.setComponentByPosition(2, self._genericTrap,verifyConstraints=False) pdu.setComponentByPosition(3, self._zeroInt, verifyConstraints=False) pdu.setComponentByPosition(4, self._zeroTime, verifyConstraints=False) pdu.setComponentByPosition(5) def getEnterprise(self, pdu): return pdu.getComponentByPosition(0) def setEnterprise(self, pdu, value): pdu.setComponentByPosition(0, value) def getAgentAddr(self, pdu): return pdu.getComponentByPosition(1).getComponentByPosition(0) def setAgentAddr(self, pdu, value): pdu.setComponentByPosition(1).getComponentByPosition(1).setComponentByPosition(0, value) def getGenericTrap(self, pdu): return pdu.getComponentByPosition(2) def setGenericTrap(self, pdu, value): pdu.setComponentByPosition(2, value) def getSpecificTrap(self, pdu): return pdu.getComponentByPosition(3) def setSpecificTrap(self, pdu, value): pdu.setComponentByPosition(3, value) def getTimeStamp(self, pdu): return pdu.getComponentByPosition(4) def setTimeStamp(self, pdu, value): pdu.setComponentByPosition(4, value) def getVarBindList(self, pdu): return pdu.getComponentByPosition(5) def setVarBindList(self, pdu, varBindList): varBindList = pdu.setComponentByPosition(5, varBindList) def getVarBinds(self, pdu): varBinds = [] for varBind in pdu.getComponentByPosition(5): varBinds.append(apiVarBind.getOIDVal(varBind)) return varBinds def setVarBinds(self, pdu, varBinds): varBindList = pdu.setComponentByPosition(5).getComponentByPosition(5) varBindList.clear() idx = 0 for varBind in varBinds: if isinstance(varBind, VarBind): varBindList.setComponentByPosition(idx, varBind) else: varBindList.setComponentByPosition(idx) apiVarBind.setOIDVal( varBindList.getComponentByPosition(idx), varBind ) idx = idx + 1 apiTrapPDU = TrapPDUAPI() class MessageAPI: _version = rfc1157._version.clone(0) _community = univ.OctetString('public') def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False) return msg def getVersion(self, msg): return msg.getComponentByPosition(0) def setVersion(self, msg, value): msg.setComponentByPosition(0, value) def getCommunity(self, msg): return msg.getComponentByPosition(1) def setCommunity(self, msg, value): msg.setComponentByPosition(1, value) def getPDU(self, msg): return msg.getComponentByPosition(2).getComponent() def setPDU(self, msg, value): msg.setComponentByPosition(2).getComponentByPosition(2).setComponentByType(value.getTagSet(), value, 1, verifyConstraints=False) def getResponse(self, reqMsg): rspMsg = Message() self.setDefaults(rspMsg) self.setVersion(rspMsg, self.getVersion(reqMsg)) self.setCommunity(rspMsg, self.getCommunity(reqMsg)) self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) return rspMsg apiMessage = MessageAPI() pysnmp-4.2.5/pysnmp/proto/api/verdec.py0000644000076400001440000000063111754432123020257 0ustar ilyausers00000000000000from pyasn1.codec.ber import decoder from pyasn1.error import PyAsn1Error from pysnmp.proto.error import ProtocolError def decodeMessageVersion(wholeMsg): try: seq, wholeMsg = decoder.decode(wholeMsg, recursiveFlag=0) ver, wholeMsg = decoder.decode(wholeMsg, recursiveFlag=0) return ver except PyAsn1Error: raise ProtocolError('Invalid BER at SNMP version component') pysnmp-4.2.5/pysnmp/proto/api/v2c.py0000644000076400001440000001166412153626041017507 0ustar ilyausers00000000000000from 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 ) def setNoSuchInstanceError(self, pdu, errorIndex): varBindList = self.getVarBindList(pdu) varBindList[errorIndex-1].setComponentByPosition( 1, rfc1905.noSuchInstance, verifyConstraints=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 ) pdu.setComponentByPosition( 1, self._nonRepeaters, verifyConstraints=False ) pdu.setComponentByPosition( 2, self._maxRepetitions, verifyConstraints=False ) pdu.setComponentByPosition(3) def getNonRepeaters(self, pdu): return pdu.getComponentByPosition(1) def setNonRepeaters(self, pdu, value): pdu.setComponentByPosition(1, value) def getMaxRepetitions(self, pdu): return pdu.getComponentByPosition(2) def setMaxRepetitions(self,pdu,value): pdu.setComponentByPosition(2,value) def getVarBindTable(self, reqPDU, rspPDU): nonRepeaters = self.getNonRepeaters(reqPDU) maxRepetitions = self.getMaxRepetitions(reqPDU) reqVarBinds = self.getVarBinds(reqPDU) N = min(int(nonRepeaters), len(reqVarBinds)) M = int(maxRepetitions) R = max(len(reqVarBinds)-N, 0) rspVarBinds = self.getVarBinds(rspPDU) varBindTable = [] if R: for i in range(0, len(rspVarBinds)-N, R): varBindRow = rspVarBinds[:N] + rspVarBinds[N+i:N+R+i] # ignore stray OIDs / non-rectangular table if len(varBindRow) == N + R: varBindTable.append(varBindRow) elif N: varBindTable.append(rspVarBinds[:N]) return varBindTable apiBulkPDU = BulkPDUAPI() class TrapPDUAPI(v1.PDUAPI): sysUpTime = (1,3,6,1,2,1,1,3,0) snmpTrapAddress = (1,3,6,1,6,3,18,1,3,0) snmpTrapCommunity = (1,3,6,1,6,3,18,1,4,0) snmpTrapOID = (1,3,6,1,6,3,1,1,4,1,0) snmpTrapEnterprise = (1,3,6,1,6,3,1,1,4,3,0) _zeroTime = TimeTicks(0) _genTrap = ObjectIdentifier((1,3,6,1,6,3,1,1,5,1)) def setDefaults(self, pdu): v1.PDUAPI.setDefaults(self, pdu) varBinds = [ ( self.sysUpTime, self._zeroTime), # generic trap ( self.snmpTrapOID, self._genTrap) ] self.setVarBinds(pdu, varBinds) apiTrapPDU = TrapPDUAPI() class MessageAPI(v1.MessageAPI): _version = rfc1901._version.clone(1) def setDefaults(self, msg): msg.setComponentByPosition(0, self._version, verifyConstraints=False) msg.setComponentByPosition(1, self._community, verifyConstraints=False) return msg def getResponse(self, reqMsg): rspMsg = Message() self.setDefaults(rspMsg) self.setVersion(rspMsg, self.getVersion(reqMsg)) self.setCommunity(rspMsg, self.getCommunity(reqMsg)) self.setPDU(rspMsg, apiPDU.getResponse(self.getPDU(reqMsg))) return rspMsg apiMessage = MessageAPI() pysnmp-4.2.5/pysnmp/smi/0000755000076400001440000000000012222743671015315 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/smi/__init__.py0000644000076400001440000000007311775060037017426 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/smi/error.py0000644000076400001440000000310112061413246017004 0ustar ilyausers00000000000000from pyasn1.error import PyAsn1Error from pysnmp.error import PySnmpError class SmiError(PySnmpError, PyAsn1Error): pass class MibOperationError(SmiError): def __init__(self, **kwargs): self.__outArgs = kwargs def __str__(self): return '%s(%s)' % ( self.__class__.__name__, self.__outArgs ) def __getitem__(self, key): return self.__outArgs[key] def __contains__(self, key): return key in self.__outArgs def get(self, key, defVal=None): return self.__outArgs.get(key, defVal) def keys(self): return self.__outArgs.keys() def update(self, d): self.__outArgs.update(d) # Aligned with SNMPv2 PDU error-status class GenError(MibOperationError): pass class NoAccessError(MibOperationError): pass class WrongTypeError(MibOperationError): pass class WrongValueError(MibOperationError): pass class NoCreationError(MibOperationError): pass class InconsistentValueError(MibOperationError): pass class ResourceUnavailableError(MibOperationError): pass class CommitFailedError(MibOperationError): pass class UndoFailedError(MibOperationError): pass class AuthorizationError(MibOperationError): pass class NotWritableError(MibOperationError): pass class InconsistentNameError(MibOperationError): pass # Aligned with SNMPv2 Var-Bind exceptions class NoSuchObjectError(MibOperationError): pass class NoSuchInstanceError(MibOperationError): pass class EndOfMibViewError(MibOperationError): pass # Row management class TableRowManagement(MibOperationError): pass class RowCreationWanted(TableRowManagement): pass class RowDestructionWanted(TableRowManagement): pass pysnmp-4.2.5/pysnmp/smi/instrum.py0000644000076400001440000002214412155700771017372 0ustar ilyausers00000000000000# MIB modules management import sys import traceback from pysnmp.smi import error from pysnmp import debug __all__ = [ 'AbstractMibInstrumController', 'MibInstrumController' ] class AbstractMibInstrumController: def readVars(self, vars, acInfo=(None, None)): raise error.NoSuchInstanceError(idx=0) def readNextVars(self, vars, acInfo=(None, None)): raise error.EndOfMibViewError(idx=0) def writeVars(self, vars, 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, MibTree ) = self.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance', 'MibScalar', 'MibTableColumn', 'MibTableRow', 'MibTable', 'MibTree' ) mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') # # Management Instrumentation gets organized as follows: # # MibTree # | # +----MibScalar # | | # | +-----MibScalarInstance # | # +----MibTable # | # +----MibTableRow # | # +-------MibTableColumn # | # +------MibScalarInstance(s) # # Mind you, only Managed Objects get indexed here, various MIB defs and # constants can't be SNMP managed so we drop them. # scalars = {}; instances = {}; tables = {}; rows = {}; cols = {} # Sort by module name to give user a chance to slip-in # custom MIB modules (that would be sorted out first) mibSymbols = list(self.mibBuilder.mibSymbols.items()) mibSymbols.sort(key=lambda x: x[0], reverse=True) for modName, mibMod in mibSymbols: for symObj in mibMod.values(): if isinstance(symObj, MibTable): tables[symObj.name] = symObj elif isinstance(symObj, MibTableRow): rows[symObj.name] = symObj elif isinstance(symObj, MibTableColumn): cols[symObj.name] = symObj elif isinstance(symObj, MibScalarInstance): instances[symObj.name] = symObj elif isinstance(symObj, MibScalar): scalars[symObj.name] = symObj # Detach items from each other for symName, parentName in self.lastBuildSyms.items(): if parentName in scalars: scalars[parentName].unregisterSubtrees(symName) elif parentName in cols: cols[parentName].unregisterSubtrees(symName) elif parentName in rows: rows[parentName].unregisterSubtrees(symName) else: mibTree.unregisterSubtrees(symName) lastBuildSyms = {} # Attach Managed Objects Instances to Managed Objects for inst in instances.values(): if inst.typeName in scalars: scalars[inst.typeName].registerSubtrees(inst) elif inst.typeName in cols: cols[inst.typeName].registerSubtrees(inst) else: raise error.SmiError( 'Orphan MIB scalar instance %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, inputNameVals, acInfo): self.__indexMib() debug.logger & debug.flagIns and debug.logger('flipFlopFsm: inputNameVals %r' % (inputNameVals,)) mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso') outputNameVals = [] state, status = 'start', 'ok' origExc = None while 1: k = (state, status) if k in fsmTable: fsmState = fsmTable[k] else: k = ('*', status) if k in fsmTable: fsmState = fsmTable[k] else: raise error.SmiError( 'Unresolved FSM state %s, %s' % (state, status) ) debug.logger & debug.flagIns and debug.logger('flipFlopFsm: state %s status %s -> fsmState %s' % (state, status, fsmState)) state = fsmState status = 'ok' if state == 'stop': break idx = 0 for name, val in inputNameVals: f = getattr(mibTree, state, None) if f is None: raise error.SmiError( 'Unsupported state handler %s at %s' % (state, self) ) try: # Convert to tuple to avoid ObjectName instantiation # on subscription rval = f(tuple(name), val, idx, acInfo) except error.SmiError: 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: outputNameVals.append((rval[0], rval[1])) idx = idx + 1 if origExc: if sys.version_info[0] <= 2: raise origExc else: try: raise origExc.with_traceback(origTraceback) finally: # Break cycle between locals and traceback object # (seems to be irrelevant on Py3 but just in case) del origTraceback return outputNameVals def readVars(self, vars, acInfo=(None, None)): return self.flipFlopFsm(self.fsmReadVar, vars, acInfo) def readNextVars(self, vars, acInfo=(None, None)): return self.flipFlopFsm(self.fsmReadNextVar, vars, acInfo) def writeVars(self, vars, acInfo=(None, None)): return self.flipFlopFsm(self.fsmWriteVar, vars, acInfo) pysnmp-4.2.5/pysnmp/smi/view.py0000644000076400001440000002725112141543400016634 0ustar ilyausers00000000000000# MIB modules management import sys from pysnmp.smi.indices import OrderedDict, OidOrderedDict from pysnmp.smi import error from pysnmp import debug __all__ = [ 'MibViewController' ] if sys.version_info[0] <= 2: import types classTypes = (types.ClassType, type) instanceTypes = (types.InstanceType, object) else: classTypes = (type,) instanceTypes = (object,) class MibViewController: def __init__(self, mibBuilder): self.mibBuilder = mibBuilder self.lastBuildId = -1 # Indexing part def indexMib(self): if self.lastBuildId == self.mibBuilder.lastBuildId: return debug.logger & debug.flagMIB and debug.logger('indexMib: re-indexing MIB view') MibScalarInstance, = self.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance' ) # # Create indices # # Module name -> module-scope indices self.__mibSymbolsIdx = OrderedDict() # Oid <-> label indices # This is potentionally ambiguous mapping. Sort modules in # ascending age for resolution def __sortFun(x, b=self.mibBuilder): if b.moduleID in b.mibSymbols[x]: m = b.mibSymbols[x][b.moduleID] r = m.getRevisions() if r: return r[0] else: return "1970-01-01 00:00" modNames = list(self.mibBuilder.mibSymbols.keys()) modNames.sort(key=__sortFun) # Index modules names for modName in [ '' ] + modNames: # Modules index self.__mibSymbolsIdx[modName] = mibMod = { 'oidToLabelIdx': OidOrderedDict(), 'labelToOidIdx': {}, 'varToNameIdx': {}, 'typeToModIdx': OrderedDict(), 'oidToModIdx': {} } if not modName: globMibMod = mibMod continue # Types & MIB vars indices for n, v in self.mibBuilder.mibSymbols[modName].items(): if n == self.mibBuilder.moduleID: # do not index this continue # special symbol if isinstance(v, classTypes): if n in mibMod['typeToModIdx']: raise error.SmiError( 'Duplicate SMI type %s::%s, has %s' % \ (modName, n, mibMod['typeToModIdx'][n]) ) globMibMod['typeToModIdx'][n] = modName mibMod['typeToModIdx'][n] = modName elif isinstance(v, instanceTypes): if isinstance(v, MibScalarInstance): continue if n in mibMod['varToNameIdx']: raise error.SmiError( 'Duplicate MIB variable %s::%s has %s' % \ (modName, n, mibMod['varToNameIdx'][n]) ) globMibMod['varToNameIdx'][n] = v.name mibMod['varToNameIdx'][n] = v.name # Potentionally ambiguous mapping ahead globMibMod['oidToModIdx'][v.name] = modName mibMod['oidToModIdx'][v.name] = modName globMibMod['oidToLabelIdx'][v.name] = (n, ) mibMod['oidToLabelIdx'][v.name] = (n, ) else: raise error.SmiError( 'Unexpected object %s::%s' % (modName, n) ) # Build oid->long-label index oidToLabelIdx = self.__mibSymbolsIdx['']['oidToLabelIdx'] labelToOidIdx = self.__mibSymbolsIdx['']['labelToOidIdx'] if oidToLabelIdx: prevOid = oidToLabelIdx.keys()[0] else: prevOid = () baseLabel = () for key in oidToLabelIdx.keys(): keydiff = len(key) - len(prevOid) if keydiff > 0: baseLabel = oidToLabelIdx[prevOid] if keydiff > 1: baseLabel = baseLabel + key[-keydiff:-1] if keydiff < 0: keyLen = len(key) i = keyLen-1 while i: k = key[:i] if k in oidToLabelIdx: baseLabel = oidToLabelIdx[k] if i != keyLen-1: baseLabel = baseLabel + key[i:-1] break i = i - 1 # Build oid->long-label index oidToLabelIdx[key] = baseLabel + oidToLabelIdx[key] # Build label->oid index labelToOidIdx[oidToLabelIdx[key]] = key prevOid = key # Build module-scope oid->long-label index for mibMod in self.__mibSymbolsIdx.values(): for oid in mibMod['oidToLabelIdx'].keys(): mibMod['oidToLabelIdx'][oid] = oidToLabelIdx[oid] mibMod['labelToOidIdx'][oidToLabelIdx[oid]] = oid self.lastBuildId = self.mibBuilder.lastBuildId # Module management def getFirstModuleName(self): self.indexMib() modNames = self.__mibSymbolsIdx.keys() if modNames: return modNames[0] raise error.SmiError('No modules loaded at %s' % self) def getNextModuleName(self, modName): self.indexMib() try: return self.__mibSymbolsIdx.nextKey(modName) except KeyError: raise error.SmiError( 'No module next to %s at %s' % (modName, self) ) # MIB tree node management def __getOidLabel(self, nodeName, oidToLabelIdx, labelToOidIdx): """getOidLabel(nodeName) -> (oid, label, suffix)""" if not nodeName: return nodeName, nodeName, () if nodeName in labelToOidIdx: return labelToOidIdx[nodeName], nodeName, () if nodeName in oidToLabelIdx: return nodeName, oidToLabelIdx[nodeName], () if len(nodeName) < 2: return nodeName, nodeName, () oid, label, suffix = self.__getOidLabel( nodeName[:-1], oidToLabelIdx, labelToOidIdx ) suffix = suffix + nodeName[-1:] resLabel = label + tuple([ str(x) for x in suffix ]) if resLabel in labelToOidIdx: return labelToOidIdx[resLabel], resLabel, () resOid = oid + suffix if resOid in oidToLabelIdx: return resOid, oidToLabelIdx[resOid], () return oid, label, suffix def getNodeNameByOid(self, nodeName, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError( 'No module %s at %s' % (modName, self) ) oid, label, suffix = self.__getOidLabel( nodeName, mibMod['oidToLabelIdx'], mibMod['labelToOidIdx'] ) if oid == label: raise error.NoSuchObjectError( str='Can\'t resolve node name %s::%s at %s' % (modName, nodeName, self) ) debug.logger & debug.flagMIB and debug.logger('getNodeNameByOid: resolved %s:%s -> %s.%s' % (modName, nodeName, label, suffix)) return oid, label, suffix def getNodeNameByDesc(self, nodeName, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError( 'No module %s at %s' % (modName, self) ) if nodeName in mibMod['varToNameIdx']: oid = mibMod['varToNameIdx'][nodeName] else: raise error.NoSuchObjectError( str='No such symbol %s::%s at %s' % (modName, nodeName, self) ) debug.logger & debug.flagMIB and debug.logger('getNodeNameByDesc: resolved %s:%s -> %s' % (modName, nodeName, oid)) return self.getNodeNameByOid(oid, modName) def getNodeName(self, nodeName, modName=''): # nodeName may be either an absolute OID/label or a # ( MIB-symbol, su, ff, ix) try: # First try nodeName as an OID/label return self.getNodeNameByOid(nodeName, modName) except error.NoSuchObjectError: # ...on failure, try as MIB symbol oid, label, suffix = self.getNodeNameByDesc( nodeName[0], modName ) # ...with trailing suffix return self.getNodeNameByOid( oid + suffix + nodeName[1:], modName ) def getFirstNodeName(self, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError( 'No module %s at %s' % (modName, self) ) if not mibMod['oidToLabelIdx']: raise error.NoSuchObjectError( str='No variables at MIB module %s at %s' % (modName, self) ) oid, label = mibMod['oidToLabelIdx'].items()[0] return oid, label, () def getNextNodeName(self, nodeName, modName=''): oid, label, suffix = self.getNodeName(nodeName, modName) try: return self.getNodeName( self.__mibSymbolsIdx[modName]['oidToLabelIdx'].nextKey(oid) + suffix, modName ) except KeyError: raise error.NoSuchObjectError( str='No name next to %s::%s at %s' % (modName, nodeName, self) ) def getParentNodeName(self, nodeName, modName=''): oid, label, suffix = self.getNodeName(nodeName, modName) if len(oid) < 2: raise error.NoSuchObjectError( str='No parent name for %s::%s at %s' % (modName, nodeName, self) ) return oid[:-1], label[:-1], oid[-1:] + suffix def getNodeLocation(self, nodeName, modName=''): oid, label, suffix = self.getNodeName(nodeName, modName) return self.__mibSymbolsIdx['']['oidToModIdx'][oid], label[-1], suffix # MIB type management def getTypeName(self, typeName, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError( 'No module %s at %s' % (modName, self) ) if typeName in mibMod['typeToModIdx']: m = mibMod['typeToModIdx'][typeName] else: raise error.NoSuchObjectError( str='No such type %s::%s at %s' % (modName, typeName, self) ) return m, typeName def getFirstTypeName(self, modName=''): self.indexMib() if modName in self.__mibSymbolsIdx: mibMod = self.__mibSymbolsIdx[modName] else: raise error.SmiError( 'No module %s at %s' % (modName, self) ) if not mibMod['typeToModIdx']: raise error.NoSuchObjectError( str='No types at MIB module %s at %s' % (modName, self) ) t = mibMod['typeToModIdx'].keys()[0] return mibMod['typeToModIdx'][t], t def getNextType(self, typeName, modName=''): m, t = self.getTypeName(typeName, modName) try: return self.__mibSymbolsIdx[m]['typeToModIdx'].nextKey(t) except KeyError: raise error.NoSuchObjectError( str='No type next to %s::%s at %s' % (modName, typeName, self) ) pysnmp-4.2.5/pysnmp/smi/mibs/0000755000076400001440000000000012222743671016247 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-USER-BASED-SM-MIB.py0000644000076400001440000006413412155541254021716 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USER-BASED-SM-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:13:22 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( SnmpAdminString, SnmpEngineID, snmpAuthProtocols, snmpPrivProtocols, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID", "snmpAuthProtocols", "snmpPrivProtocols") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( AutonomousType, RowPointer, RowStatus, StorageType, TextualConvention, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "AutonomousType", "RowPointer", "RowStatus", "StorageType", "TextualConvention", "TestAndIncr") # Types class KeyChange(OctetString): pass # Objects usmNoAuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 1)) if mibBuilder.loadTexts: usmNoAuthProtocol.setDescription("No Authentication Protocol.") usmHMACMD5AuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 2)) if mibBuilder.loadTexts: usmHMACMD5AuthProtocol.setDescription("The HMAC-MD5-96 Digest Authentication Protocol.") usmHMACSHAAuthProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1, 3)) if mibBuilder.loadTexts: usmHMACSHAAuthProtocol.setDescription("The HMAC-SHA-96 Digest Authentication Protocol.") usmNoPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 1)) if mibBuilder.loadTexts: usmNoPrivProtocol.setDescription("No Privacy Protocol.") usmDESPrivProtocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 2)) if mibBuilder.loadTexts: usmDESPrivProtocol.setDescription("The CBC-DES Symmetric Encryption Protocol.") snmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 15)).setRevisions(("2002-10-16 00:00","1999-01-20 00:00","1997-11-20 00:00",)) if mibBuilder.loadTexts: snmpUsmMIB.setOrganization("SNMPv3 Working Group") if mibBuilder.loadTexts: snmpUsmMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In msg body: subscribe snmpv3\n\nChair: Russ Mundy\n Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nemail: mundy@tislabs.com\n\nphone: +1 301-947-7107\n\nCo-Chair: David Harrington\n Enterasys Networks\nPostal: 35 Industrial Way\n P. O. Box 5004\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nPhone: +1 603-337-2614\n\nCo-editor Uri Blumenthal\n Lucent Technologies\npostal: 67 Whippany Rd.\n Whippany, NJ 07981\n USA\nemail: uri@lucent.com\nphone: +1-973-386-2163\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nemail: bwijnen@lucent.com\nphone: +31-348-480-685") if mibBuilder.loadTexts: snmpUsmMIB.setDescription("The management information definitions for the\nSNMP User-based Security Model.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3414;\nsee the RFC itself for full legal notices.") usmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1)) usmStats = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1, 1)) usmStatsUnsupportedSecLevels = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsUnsupportedSecLevels.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they requested a\nsecurityLevel that was unknown to the SNMP engine\nor otherwise unavailable.") usmStatsNotInTimeWindows = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsNotInTimeWindows.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they appeared\noutside of the authoritative SNMP engine's window.") usmStatsUnknownUserNames = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsUnknownUserNames.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they referenced a\nuser that was not known to the SNMP engine.") usmStatsUnknownEngineIDs = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsUnknownEngineIDs.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they referenced an\nsnmpEngineID that was not known to the SNMP engine.") usmStatsWrongDigests = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsWrongDigests.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they didn't\ncontain the expected digest value.") usmStatsDecryptionErrors = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: usmStatsDecryptionErrors.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they could not be\ndecrypted.") usmUser = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 1, 2)) usmUserSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 15, 1, 2, 1), TestAndIncr()).setMaxAccess("readwrite") if mibBuilder.loadTexts: usmUserSpinLock.setDescription("An advisory lock used to allow several cooperating\nCommand Generator Applications to coordinate their\nuse of facilities to alter secrets in the\nusmUserTable.") usmUserTable = MibTable((1, 3, 6, 1, 6, 3, 15, 1, 2, 2)) if mibBuilder.loadTexts: usmUserTable.setDescription("The table of users configured in the SNMP engine's\nLocal Configuration Datastore (LCD).\n\nTo create a new user (i.e., to instantiate a new\nconceptual row in this table), it is recommended to\nfollow this procedure:\n\n 1) GET(usmUserSpinLock.0) and save in sValue.\n\n 2) SET(usmUserSpinLock.0=sValue,\n usmUserCloneFrom=templateUser,\n usmUserStatus=createAndWait)\n You should use a template user to clone from\n which has the proper auth/priv protocol defined.\n\nIf the new user is to use privacy:\n\n 3) generate the keyChange value based on the secret\n privKey of the clone-from user and the secret key\n to be used for the new user. Let us call this\n pkcValue.\n 4) GET(usmUserSpinLock.0) and save in sValue.\n 5) SET(usmUserSpinLock.0=sValue,\n usmUserPrivKeyChange=pkcValue\n usmUserPublic=randomValue1)\n 6) GET(usmUserPulic) and check it has randomValue1.\n If not, repeat steps 4-6.\n\nIf the new user will never use privacy:\n\n 7) SET(usmUserPrivProtocol=usmNoPrivProtocol)\n\nIf the new user is to use authentication:\n\n 8) generate the keyChange value based on the secret\n authKey of the clone-from user and the secret key\n to be used for the new user. Let us call this\n akcValue.\n 9) GET(usmUserSpinLock.0) and save in sValue.\n 10) SET(usmUserSpinLock.0=sValue,\n usmUserAuthKeyChange=akcValue\n usmUserPublic=randomValue2)\n 11) GET(usmUserPulic) and check it has randomValue2.\n If not, repeat steps 9-11.\n\nIf the new user will never use authentication:\n\n 12) SET(usmUserAuthProtocol=usmNoAuthProtocol)\n\nFinally, activate the new user:\n\n 13) SET(usmUserStatus=active)\n\nThe new user should now be available and ready to be\nused for SNMPv3 communication. Note however that access\nto MIB data must be provided via configuration of the\nSNMP-VIEW-BASED-ACM-MIB.\n\nThe use of usmUserSpinlock is to avoid conflicts with\nanother SNMP command generator application which may\nalso be acting on the usmUserTable.") usmUserEntry = MibTableRow((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1)).setIndexNames((0, "SNMP-USER-BASED-SM-MIB", "usmUserEngineID"), (0, "SNMP-USER-BASED-SM-MIB", "usmUserName")) if mibBuilder.loadTexts: usmUserEntry.setDescription("A user configured in the SNMP engine's Local\nConfiguration Datastore (LCD) for the User-based\nSecurity Model.") usmUserEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 1), SnmpEngineID()).setMaxAccess("noaccess") if mibBuilder.loadTexts: usmUserEngineID.setDescription("An SNMP engine's administratively-unique identifier.\n\nIn a simple agent, this value is always that agent's\nown snmpEngineID value.\n\nThe value can also take the value of the snmpEngineID\nof a remote SNMP engine with which this user can\ncommunicate.") usmUserName = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: usmUserName.setDescription("A human readable string representing the name of\nthe user.\n\nThis is the (User-based Security) Model dependent\nsecurity ID.") usmUserSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 3), SnmpAdminString()).setMaxAccess("noaccess") if mibBuilder.loadTexts: usmUserSecurityName.setDescription("A human readable string representing the user in\nSecurity Model independent format.\n\nThe default transformation of the User-based Security\nModel dependent security ID to the securityName and\nvice versa is the identity function so that the\nsecurityName is the same as the userName.") usmUserCloneFrom = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 4), RowPointer((0,0))).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserCloneFrom.setDescription("A pointer to another conceptual row in this\nusmUserTable. The user in this other conceptual\nrow is called the clone-from user.\n\nWhen a new user is created (i.e., a new conceptual\nrow is instantiated in this table), the privacy and\nauthentication parameters of the new user must be\ncloned from its clone-from user. These parameters are:\n - authentication protocol (usmUserAuthProtocol)\n - privacy protocol (usmUserPrivProtocol)\nThey will be copied regardless of what the current\nvalue is.\n\nCloning also causes the initial values of the secret\nauthentication key (authKey) and the secret encryption\n\nkey (privKey) of the new user to be set to the same\nvalues as the corresponding secrets of the clone-from\nuser to allow the KeyChange process to occur as\nrequired during user creation.\n\nThe first time an instance of this object is set by\na management operation (either at or after its\ninstantiation), the cloning process is invoked.\nSubsequent writes are successful but invoke no\naction to be taken by the receiver.\nThe cloning process fails with an 'inconsistentName'\nerror if the conceptual row representing the\nclone-from user does not exist or is not in an active\nstate when the cloning process is invoked.\n\nWhen this object is read, the ZeroDotZero OID\nis returned.") usmUserAuthProtocol = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 5), AutonomousType().clone('1.3.6.1.6.3.10.1.1.1')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserAuthProtocol.setDescription("An indication of whether messages sent on behalf of\nthis user to/from the SNMP engine identified by\nusmUserEngineID, can be authenticated, and if so,\nthe type of authentication protocol which is used.\n\nAn instance of this object is created concurrently\nwith the creation of any other object instance for\nthe same user (i.e., as part of the processing of\nthe set operation which creates the first object\ninstance in the same conceptual row).\n\nIf an initial set operation (i.e. at row creation time)\ntries to set a value for an unknown or unsupported\nprotocol, then a 'wrongValue' error must be returned.\n\nThe value will be overwritten/set when a set operation\nis performed on the corresponding instance of\nusmUserCloneFrom.\n\nOnce instantiated, the value of such an instance of\nthis object can only be changed via a set operation to\nthe value of the usmNoAuthProtocol.\n\nIf a set operation tries to change the value of an\n\nexisting instance of this object to any value other\nthan usmNoAuthProtocol, then an 'inconsistentValue'\nerror must be returned.\n\nIf a set operation tries to set the value to the\nusmNoAuthProtocol while the usmUserPrivProtocol value\nin the same row is not equal to usmNoPrivProtocol,\nthen an 'inconsistentValue' error must be returned.\nThat means that an SNMP command generator application\nmust first ensure that the usmUserPrivProtocol is set\nto the usmNoPrivProtocol value before it can set\nthe usmUserAuthProtocol value to usmNoAuthProtocol.") usmUserAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 6), KeyChange().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserAuthKeyChange.setDescription("An object, which when modified, causes the secret\nauthentication key used for messages sent on behalf\nof this user to/from the SNMP engine identified by\nusmUserEngineID, to be modified via a one-way\nfunction.\n\nThe associated protocol is the usmUserAuthProtocol.\nThe associated secret key is the user's secret\nauthentication key (authKey). The associated hash\nalgorithm is the algorithm used by the user's\nusmUserAuthProtocol.\n\nWhen creating a new user, it is an 'inconsistentName'\nerror for a set operation to refer to this object\nunless it is previously or concurrently initialized\nthrough a set operation on the corresponding instance\nof usmUserCloneFrom.\n\nWhen the value of the corresponding usmUserAuthProtocol\nis usmNoAuthProtocol, then a set is successful, but\neffectively is a no-op.\n\nWhen this object is read, the zero-length (empty)\nstring is returned.\n\nThe recommended way to do a key change is as follows:\n\n 1) GET(usmUserSpinLock.0) and save in sValue.\n 2) generate the keyChange value based on the old\n (existing) secret key and the new secret key,\n let us call this kcValue.\n\nIf you do the key change on behalf of another user:\n\n 3) SET(usmUserSpinLock.0=sValue,\n usmUserAuthKeyChange=kcValue\n usmUserPublic=randomValue)\n\nIf you do the key change for yourself:\n\n 4) SET(usmUserSpinLock.0=sValue,\n usmUserOwnAuthKeyChange=kcValue\n usmUserPublic=randomValue)\n\nIf you get a response with error-status of noError,\nthen the SET succeeded and the new key is active.\nIf you do not get a response, then you can issue a\nGET(usmUserPublic) and check if the value is equal\nto the randomValue you did send in the SET. If so, then\nthe key change succeeded and the new key is active\n(probably the response got lost). If not, then the SET\nrequest probably never reached the target and so you\ncan start over with the procedure above.") usmUserOwnAuthKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 7), KeyChange().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserOwnAuthKeyChange.setDescription("Behaves exactly as usmUserAuthKeyChange, with one\nnotable difference: in order for the set operation\nto succeed, the usmUserName of the operation\nrequester must match the usmUserName that\nindexes the row which is targeted by this\noperation.\nIn addition, the USM security model must be\nused for this operation.\n\nThe idea here is that access to this column can be\npublic, since it will only allow a user to change\nhis own secret authentication key (authKey).\nNote that this can only be done once the row is active.\n\nWhen a set is received and the usmUserName of the\nrequester is not the same as the umsUserName that\nindexes the row which is targeted by this operation,\nthen a 'noAccess' error must be returned.\n\nWhen a set is received and the security model in use\nis not USM, then a 'noAccess' error must be returned.") usmUserPrivProtocol = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 8), AutonomousType().clone('1.3.6.1.6.3.10.1.2.1')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserPrivProtocol.setDescription("An indication of whether messages sent on behalf of\nthis user to/from the SNMP engine identified by\nusmUserEngineID, can be protected from disclosure,\nand if so, the type of privacy protocol which is used.\n\nAn instance of this object is created concurrently\nwith the creation of any other object instance for\nthe same user (i.e., as part of the processing of\nthe set operation which creates the first object\ninstance in the same conceptual row).\n\nIf an initial set operation (i.e. at row creation time)\ntries to set a value for an unknown or unsupported\nprotocol, then a 'wrongValue' error must be returned.\n\nThe value will be overwritten/set when a set operation\nis performed on the corresponding instance of\nusmUserCloneFrom.\n\nOnce instantiated, the value of such an instance of\nthis object can only be changed via a set operation to\nthe value of the usmNoPrivProtocol.\n\nIf a set operation tries to change the value of an\nexisting instance of this object to any value other\nthan usmNoPrivProtocol, then an 'inconsistentValue'\nerror must be returned.\n\nNote that if any privacy protocol is used, then you\nmust also use an authentication protocol. In other\nwords, if usmUserPrivProtocol is set to anything else\nthan usmNoPrivProtocol, then the corresponding instance\nof usmUserAuthProtocol cannot have a value of\n\nusmNoAuthProtocol. If it does, then an\n'inconsistentValue' error must be returned.") usmUserPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 9), KeyChange().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserPrivKeyChange.setDescription("An object, which when modified, causes the secret\nencryption key used for messages sent on behalf\nof this user to/from the SNMP engine identified by\nusmUserEngineID, to be modified via a one-way\nfunction.\n\nThe associated protocol is the usmUserPrivProtocol.\nThe associated secret key is the user's secret\nprivacy key (privKey). The associated hash\nalgorithm is the algorithm used by the user's\nusmUserAuthProtocol.\n\nWhen creating a new user, it is an 'inconsistentName'\nerror for a set operation to refer to this object\nunless it is previously or concurrently initialized\nthrough a set operation on the corresponding instance\nof usmUserCloneFrom.\n\nWhen the value of the corresponding usmUserPrivProtocol\nis usmNoPrivProtocol, then a set is successful, but\neffectively is a no-op.\n\nWhen this object is read, the zero-length (empty)\nstring is returned.\nSee the description clause of usmUserAuthKeyChange for\na recommended procedure to do a key change.") usmUserOwnPrivKeyChange = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 10), KeyChange().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserOwnPrivKeyChange.setDescription("Behaves exactly as usmUserPrivKeyChange, with one\nnotable difference: in order for the Set operation\nto succeed, the usmUserName of the operation\nrequester must match the usmUserName that indexes\n\nthe row which is targeted by this operation.\nIn addition, the USM security model must be\nused for this operation.\n\nThe idea here is that access to this column can be\npublic, since it will only allow a user to change\nhis own secret privacy key (privKey).\nNote that this can only be done once the row is active.\n\nWhen a set is received and the usmUserName of the\nrequester is not the same as the umsUserName that\nindexes the row which is targeted by this operation,\nthen a 'noAccess' error must be returned.\n\nWhen a set is received and the security model in use\nis not USM, then a 'noAccess' error must be returned.") usmUserPublic = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserPublic.setDescription("A publicly-readable value which can be written as part\nof the procedure for changing a user's secret\nauthentication and/or privacy key, and later read to\ndetermine whether the change of the secret was\neffected.") usmUserStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 12), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserStorageType.setDescription("The storage type for this conceptual row.\n\nConceptual rows having the value 'permanent' must\nallow write-access at a minimum to:\n\n- usmUserAuthKeyChange, usmUserOwnAuthKeyChange\n and usmUserPublic for a user who employs\n authentication, and\n- usmUserPrivKeyChange, usmUserOwnPrivKeyChange\n and usmUserPublic for a user who employs\n privacy.\n\nNote that any user who employs authentication or\nprivacy must allow its secret(s) to be updated and\nthus cannot be 'readOnly'.\n\nIf an initial set operation tries to set the value to\n'readOnly' for a user who employs authentication or\nprivacy, then an 'inconsistentValue' error must be\nreturned. Note that if the value has been previously\nset (implicit or explicit) to any value, then the rules\nas defined in the StorageType Textual Convention apply.\n\nIt is an implementation issue to decide if a SET for\na readOnly or permanent row is accepted at all. In some\ncontexts this may make sense, in others it may not. If\na SET for a readOnly or permanent row is not accepted\nat all, then a 'wrongValue' error must be returned.") usmUserStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 15, 1, 2, 2, 1, 13), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: usmUserStatus.setDescription("The status of this conceptual row.\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the usmUserStatus column\nis 'notReady'.\n\nIn particular, a newly created row for a user who\nemploys authentication, cannot be made active until the\ncorresponding usmUserCloneFrom and usmUserAuthKeyChange\nhave been set.\n\nFurther, a newly created row for a user who also\nemploys privacy, cannot be made active until the\nusmUserPrivKeyChange has been set.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified,\nexcept for usmUserOwnAuthKeyChange and\nusmUserOwnPrivKeyChange. For these 2 objects, the\n\nvalue of usmUserStatus MUST be active.") usmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2)) usmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 1)) usmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 15, 2, 2)) # Augmentions # Groups usmMIBBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 15, 2, 2, 1)).setObjects(*(("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownEngineIDs"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmStatsNotInTimeWindows"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnknownUserNames"), ("SNMP-USER-BASED-SM-MIB", "usmUserSecurityName"), ("SNMP-USER-BASED-SM-MIB", "usmStatsUnsupportedSecLevels"), ("SNMP-USER-BASED-SM-MIB", "usmStatsDecryptionErrors"), ("SNMP-USER-BASED-SM-MIB", "usmUserStatus"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserOwnPrivKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserStorageType"), ("SNMP-USER-BASED-SM-MIB", "usmUserSpinLock"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthKeyChange"), ("SNMP-USER-BASED-SM-MIB", "usmUserCloneFrom"), ("SNMP-USER-BASED-SM-MIB", "usmUserPrivProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmUserAuthProtocol"), ("SNMP-USER-BASED-SM-MIB", "usmStatsWrongDigests"), ("SNMP-USER-BASED-SM-MIB", "usmUserPublic"), ) ) if mibBuilder.loadTexts: usmMIBBasicGroup.setDescription("A collection of objects providing for configuration\nof an SNMP engine which implements the SNMP\nUser-based Security Model.") # Compliances usmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 15, 2, 1, 1)).setObjects(*(("SNMP-USER-BASED-SM-MIB", "usmMIBBasicGroup"), ) ) if mibBuilder.loadTexts: usmMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP-USER-BASED-SM-MIB.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", PYSNMP_MODULE_ID=snmpUsmMIB) # Types mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", KeyChange=KeyChange) # Objects mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmNoAuthProtocol=usmNoAuthProtocol, usmHMACMD5AuthProtocol=usmHMACMD5AuthProtocol, usmHMACSHAAuthProtocol=usmHMACSHAAuthProtocol, usmNoPrivProtocol=usmNoPrivProtocol, usmDESPrivProtocol=usmDESPrivProtocol, snmpUsmMIB=snmpUsmMIB, usmMIBObjects=usmMIBObjects, usmStats=usmStats, usmStatsUnsupportedSecLevels=usmStatsUnsupportedSecLevels, usmStatsNotInTimeWindows=usmStatsNotInTimeWindows, usmStatsUnknownUserNames=usmStatsUnknownUserNames, usmStatsUnknownEngineIDs=usmStatsUnknownEngineIDs, usmStatsWrongDigests=usmStatsWrongDigests, usmStatsDecryptionErrors=usmStatsDecryptionErrors, usmUser=usmUser, usmUserSpinLock=usmUserSpinLock, usmUserTable=usmUserTable, usmUserEntry=usmUserEntry, usmUserEngineID=usmUserEngineID, usmUserName=usmUserName, usmUserSecurityName=usmUserSecurityName, usmUserCloneFrom=usmUserCloneFrom, usmUserAuthProtocol=usmUserAuthProtocol, usmUserAuthKeyChange=usmUserAuthKeyChange, usmUserOwnAuthKeyChange=usmUserOwnAuthKeyChange, usmUserPrivProtocol=usmUserPrivProtocol, usmUserPrivKeyChange=usmUserPrivKeyChange, usmUserOwnPrivKeyChange=usmUserOwnPrivKeyChange, usmUserPublic=usmUserPublic, usmUserStorageType=usmUserStorageType, usmUserStatus=usmUserStatus, usmMIBConformance=usmMIBConformance, usmMIBCompliances=usmMIBCompliances, usmMIBGroups=usmMIBGroups) # Groups mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmMIBBasicGroup=usmMIBBasicGroup) # Compliances mibBuilder.exportSymbols("SNMP-USER-BASED-SM-MIB", usmMIBCompliance=usmMIBCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/__init__.py0000644000076400001440000000007311775060042020354 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-PROXY-MIB.py0000644000076400001440000002317211736556026020734 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-PROXY-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 15:16:38 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( SnmpAdminString, SnmpEngineID, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID") ( SnmpTagValue, snmpTargetBasicGroup, snmpTargetResponseGroup, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetBasicGroup", "snmpTargetResponseGroup") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( RowStatus, StorageType, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType") # Objects snmpProxyMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 14)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) if mibBuilder.loadTexts: snmpProxyMIB.setOrganization("IETF SNMPv3 Working Group") if mibBuilder.loadTexts: snmpProxyMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In message body: subscribe snmpv3\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\nPostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nEMail: mundy@tislabs.com\nPhone: +1 301-947-7107\n\nCo-Chair: David Harrington\n Enterasys Networks\nPostal: 35 Industrial Way\n P. O. Box 5004\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nPhone: +1 603-337-2614\n\nCo-editor: David B. Levi\n Nortel Networks\nPostal: 3505 Kesterwood Drive\n Knoxville, Tennessee 37918\nEMail: dlevi@nortelnetworks.com\nPhone: +1 865 686 0432\n\nCo-editor: Paul Meyer\n Secure Computing Corporation\nPostal: 2675 Long Lake Road\n Roseville, Minnesota 55113\nEMail: paul_meyer@securecomputing.com\nPhone: +1 651 628 1592\n\nCo-editor: Bob Stewart\n Retired") if mibBuilder.loadTexts: snmpProxyMIB.setDescription("This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by a proxy forwarding application.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.") snmpProxyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 1)) snmpProxyTable = MibTable((1, 3, 6, 1, 6, 3, 14, 1, 2)) if mibBuilder.loadTexts: snmpProxyTable.setDescription("The table of translation parameters used by proxy forwarder\napplications for forwarding SNMP messages.") snmpProxyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 14, 1, 2, 1)).setIndexNames((1, "SNMP-PROXY-MIB", "snmpProxyName")) if mibBuilder.loadTexts: snmpProxyEntry.setDescription("A set of translation parameters used by a proxy forwarder\napplication for forwarding SNMP messages.\n\nEntries in the snmpProxyTable are created and deleted\nusing the snmpProxyRowStatus object.") snmpProxyName = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: snmpProxyName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpProxyEntry.") snmpProxyType = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 2), Integer().subtype(subtypeSpec=SingleValueConstraint(1,2,4,3,)).subtype(namedValues=NamedValues(("read", 1), ("write", 2), ("trap", 3), ("inform", 4), ))).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyType.setDescription("The type of message that may be forwarded using\nthe translation parameters defined by this entry.") snmpProxyContextEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 3), SnmpEngineID()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyContextEngineID.setDescription("The contextEngineID contained in messages that\nmay be forwarded using the translation parameters\ndefined by this entry.") snmpProxyContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 4), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyContextName.setDescription("The contextName contained in messages that may be\nforwarded using the translation parameters defined\nby this entry.\n\nThis object is optional, and if not supported, the\ncontextName contained in a message is ignored when\nselecting an entry in the snmpProxyTable.") snmpProxyTargetParamsIn = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 5), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyTargetParamsIn.setDescription("This object selects an entry in the snmpTargetParamsTable.\nThe selected entry is used to determine which row of the\nsnmpProxyTable to use for forwarding received messages.") snmpProxySingleTargetOut = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 6), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxySingleTargetOut.setDescription("This object selects a management target defined in the\nsnmpTargetAddrTable (in the SNMP-TARGET-MIB). The\nselected target is defined by an entry in the\nsnmpTargetAddrTable whose index value (snmpTargetAddrName)\nis equal to this object.\n\nThis object is only used when selection of a single\ntarget is required (i.e. when forwarding an incoming\nread or write request).") snmpProxyMultipleTargetOut = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7), SnmpTagValue()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyMultipleTargetOut.setDescription("This object selects a set of management targets defined\nin the snmpTargetAddrTable (in the SNMP-TARGET-MIB).\n\nThis object is only used when selection of multiple\ntargets is required (i.e. when forwarding an incoming\nnotification).") snmpProxyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyStorageType.setDescription("The storage type of this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") snmpProxyRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpProxyRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\n\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nThe following objects may not be modified while the\nvalue of this object is active(1):\n - snmpProxyType\n - snmpProxyContextEngineID\n - snmpProxyContextName\n - snmpProxyTargetParamsIn\n - snmpProxySingleTargetOut\n - snmpProxyMultipleTargetOut") snmpProxyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3)) snmpProxyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3, 1)) snmpProxyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 14, 3, 2)) # Augmentions # Groups snmpProxyGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 14, 3, 2, 3)).setObjects(*(("SNMP-PROXY-MIB", "snmpProxyRowStatus"), ("SNMP-PROXY-MIB", "snmpProxyTargetParamsIn"), ("SNMP-PROXY-MIB", "snmpProxyContextName"), ("SNMP-PROXY-MIB", "snmpProxySingleTargetOut"), ("SNMP-PROXY-MIB", "snmpProxyContextEngineID"), ("SNMP-PROXY-MIB", "snmpProxyStorageType"), ("SNMP-PROXY-MIB", "snmpProxyType"), ("SNMP-PROXY-MIB", "snmpProxyMultipleTargetOut"), ) ) if mibBuilder.loadTexts: snmpProxyGroup.setDescription("A collection of objects providing remote configuration of\nmanagement target translation parameters for use by\nproxy forwarder applications.") # Compliances snmpProxyCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 14, 3, 1, 1)).setObjects(*(("SNMP-TARGET-MIB", "snmpTargetResponseGroup"), ("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-PROXY-MIB", "snmpProxyGroup"), ) ) if mibBuilder.loadTexts: snmpProxyCompliance.setDescription("The compliance statement for SNMP entities which include\na proxy forwarding application.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-PROXY-MIB", PYSNMP_MODULE_ID=snmpProxyMIB) # Objects mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyMIB=snmpProxyMIB, snmpProxyObjects=snmpProxyObjects, snmpProxyTable=snmpProxyTable, snmpProxyEntry=snmpProxyEntry, snmpProxyName=snmpProxyName, snmpProxyType=snmpProxyType, snmpProxyContextEngineID=snmpProxyContextEngineID, snmpProxyContextName=snmpProxyContextName, snmpProxyTargetParamsIn=snmpProxyTargetParamsIn, snmpProxySingleTargetOut=snmpProxySingleTargetOut, snmpProxyMultipleTargetOut=snmpProxyMultipleTargetOut, snmpProxyStorageType=snmpProxyStorageType, snmpProxyRowStatus=snmpProxyRowStatus, snmpProxyConformance=snmpProxyConformance, snmpProxyCompliances=snmpProxyCompliances, snmpProxyGroups=snmpProxyGroups) # Groups mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyGroup=snmpProxyGroup) # Compliances mibBuilder.exportSymbols("SNMP-PROXY-MIB", snmpProxyCompliance=snmpProxyCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/instances/0000755000076400001440000000000012222743671020236 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py0000644000076400001440000001652312072041407022536 0ustar ilyausers00000000000000from 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.2.5/pysnmp/smi/mibs/instances/__SNMP-USER-BASED-SM-MIB.py0000644000076400001440000000354610447055255024206 0ustar ilyausers00000000000000( 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.2.5/pysnmp/smi/mibs/instances/__SNMP-MPD-MIB.py0000644000076400001440000000155210447055255022712 0ustar ilyausers00000000000000( 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.2.5/pysnmp/smi/mibs/instances/__init__.py0000644000076400001440000000007311775060045022346 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/smi/mibs/instances/__SNMP-FRAMEWORK-MIB.py0000644000076400001440000000175610564540530023630 0ustar ilyausers00000000000000import 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.2.5/pysnmp/smi/mibs/instances/__SNMP-TARGET-MIB.py0000644000076400001440000000160310447055255023255 0ustar ilyausers00000000000000( 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.2.5/pysnmp/smi/mibs/instances/__PYSNMP-USM-MIB.py0000644000076400001440000000115610447055255023207 0ustar ilyausers00000000000000( MibScalarInstance, ) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance' ) ( pysnmpUsmDiscoverable, pysnmpUsmDiscovery ) = mibBuilder.importSymbols( 'PYSNMP-USM-MIB', 'pysnmpUsmDiscoverable', 'pysnmpUsmDiscovery' ) __pysnmpUsmDiscoverable = MibScalarInstance(pysnmpUsmDiscoverable.name, (0,), pysnmpUsmDiscoverable.syntax) __pysnmpUsmDiscovery = MibScalarInstance(pysnmpUsmDiscovery.name, (0,), pysnmpUsmDiscovery.syntax) mibBuilder.exportSymbols( "__PYSNMP-USM-MIB", pysnmpUsmDiscoverable = __pysnmpUsmDiscoverable, pysnmpUsmDiscovery = __pysnmpUsmDiscovery ) pysnmp-4.2.5/pysnmp/smi/mibs/instances/__SNMP-VIEW-BASED-ACM-MIB.py0000644000076400001440000000063410447055255024256 0ustar ilyausers00000000000000( 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.2.5/pysnmp/smi/mibs/SNMPv2-TM.py0000644000076400001440000000620211777524251020171 0ustar ilyausers00000000000000try: 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(snmpModules.name + (19,)).setRevisions(("2002-10-16 00:00",)) snmpUDPDomain = ObjectIdentity(snmpDomains.name + (1,)) class SnmpUDPAddress(TextualConvention, OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6) displayHint = "1d.1d.1d.1d/2d" def prettyIn(self, value): if isinstance(value, tuple): # Wild hack -- need to implement TextualConvention.prettyIn value = 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 __getitem__(self, i): 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[i] snmpCLNSDomain = ObjectIdentity(snmpDomains.name + (2,)) snmpCONSDomain = ObjectIdentity(snmpDomains.name + (3,)) class SnmpOSIAddress(TextualConvention, OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 85) displayHint = "*1x:/1x:" snmpDDPDomain = ObjectIdentity(snmpDomains.name + (4,)) class SnmpNBPAddress(OctetString, TextualConvention): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(3, 99) snmpIPXDomain = ObjectIdentity(snmpDomains.name + (5,)) class SnmpIPXAddress(TextualConvention, OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(12, 12) displayHint = "4x.1x:1x:1x:1x:1x:1x.2d" rfc1157Proxy = MibIdentifier(snmpProxys.name + (1,)) rfc1157Domain = MibIdentifier(rfc1157Proxy.name + (1,)) # Module identity mibBuilder.exportSymbols("SNMPv2-TM", PYSNMP_MODULE_ID=snmpv2tm) mibBuilder.exportSymbols( 'SNMPv2-TM', snmpv2tm=snmpv2tm, snmpUDPDomain=snmpUDPDomain, SnmpUDPAddress=SnmpUDPAddress, snmpCLNSDomain=snmpCLNSDomain, snmpCONSDomain=snmpCONSDomain, SnmpOSIAddress=SnmpOSIAddress, snmpDDPDomain=snmpDDPDomain, SnmpNBPAddress=SnmpNBPAddress, snmpIPXDomain=snmpIPXDomain, SnmpIPXAddress=SnmpIPXAddress, rfc1157Proxy=rfc1157Proxy, rfc1157Domain=rfc1157Domain ) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-COMMUNITY-MIB.py0000644000076400001440000003460511737241667021405 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-COMMUNITY-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 12:47:45 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( SnmpAdminString, SnmpEngineID, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpEngineID") ( SnmpTagValue, snmpTargetAddrEntry, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetAddrEntry") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Integer32, Integer32, IpAddress, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "Integer32", "IpAddress", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( RowStatus, StorageType, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType") # Objects snmpCommunityMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 18)).setRevisions(("2000-03-06 00:00","1999-05-13 00:00",)) if mibBuilder.loadTexts: snmpCommunityMIB.setOrganization("SNMPv3 Working Group") if mibBuilder.loadTexts: snmpCommunityMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In msg body: subscribe snmpv3\n\nChair: Russ Mundy\n TIS Labs at Network Associates\nPostal: 3060 Washington Rd\n Glenwood MD 21738\n USA\nEmail: mundy@tislabs.com\nPhone: +1-301-854-6889\n\nCo-editor: Rob Frye\n CoSine Communications\nPostal: 1200 Bridge Parkway\n Redwood City, CA 94065\n USA\nE-mail: rfrye@cosinecom.com\nPhone: +1 703 725 1130\n\nCo-editor: David B. Levi\n Nortel Networks\nPostal: 3505 Kesterwood Drive\n Knoxville, TN 37918\nE-mail: dlevi@nortelnetworks.com\nPhone: +1 423 686 0432\n\nCo-editor: Shawn A. Routhier\n Integrated Systems Inc.\nPostal: 333 North Ave 4th Floor\n Wakefield, MA 01880\nE-mail: sar@epilogue.com\nPhone: +1 781 245 0804\n\nCo-editor: Bert Wijnen\n Lucent Technologies\nPostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nEmail: bwijnen@lucent.com\nPhone: +31-348-407-775") if mibBuilder.loadTexts: snmpCommunityMIB.setDescription("This MIB module defines objects to help support coexistence\nbetween SNMPv1, SNMPv2c, and SNMPv3.") snmpCommunityMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 1)) snmpCommunityTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 1)) if mibBuilder.loadTexts: snmpCommunityTable.setDescription("The table of community strings configured in the SNMP\nengine's Local Configuration Datastore (LCD).") snmpCommunityEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 1, 1)).setIndexNames((1, "SNMP-COMMUNITY-MIB", "snmpCommunityIndex")) if mibBuilder.loadTexts: snmpCommunityEntry.setDescription("Information about a particular community string.") snmpCommunityIndex = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: snmpCommunityIndex.setDescription("The unique index value of a row in this table.") snmpCommunityName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 2), OctetString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityName.setDescription("The community string for which a row in this table\nrepresents a configuration.") snmpCommunitySecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunitySecurityName.setDescription("A human readable string representing the corresponding\nvalue of snmpCommunityName in a Security Model\nindependent format.") snmpCommunityContextEngineID = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 4), SnmpEngineID()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityContextEngineID.setDescription("The contextEngineID indicating the location of the\ncontext in which management information is accessed\nwhen using the community string specified by the\ncorresponding instance of snmpCommunityName.\n\nThe default value is the snmpEngineID of the entity in\nwhich this object is instantiated.") snmpCommunityContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityContextName.setDescription("The context in which management information is accessed\nwhen using the community string specified by the corresponding\ninstance of snmpCommunityName.") snmpCommunityTransportTag = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 6), SnmpTagValue().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityTransportTag.setDescription("This object specifies a set of transport endpoints\nfrom which a command responder application will accept\nmanagement requests. If a management request containing\nthis community is received on a transport endpoint other\nthan the transport endpoints identified by this object,\nthe request is deemed unauthentic.\n\nThe transports identified by this object are specified\n\nin the snmpTargetAddrTable. Entries in that table\nwhose snmpTargetAddrTagList contains this tag value\nare identified.\n\nIf the value of this object has zero-length, transport\nendpoints are not checked when authenticating messages\ncontaining this community string.") snmpCommunityStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 7), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityStorageType.setDescription("The storage type for this conceptual row in the\nsnmpCommunityTable. Conceptual rows having the value\n'permanent' need not allow write-access to any\ncolumnar object in the row.") snmpCommunityStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 1, 1, 8), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpCommunityStatus.setDescription("The status of this conceptual row in the snmpCommunityTable.\n\nAn entry in this table is not qualified for activation\nuntil instances of all corresponding columns have been\ninitialized, either through default values, or through\nSet operations. The snmpCommunityName and\nsnmpCommunitySecurityName objects must be explicitly set.\n\nThere is no restriction on setting columns in this table\nwhen the value of snmpCommunityStatus is active(1).") snmpTargetAddrExtTable = MibTable((1, 3, 6, 1, 6, 3, 18, 1, 2)) if mibBuilder.loadTexts: snmpTargetAddrExtTable.setDescription("The table of mask and mms values associated with the\n\nsnmpTargetAddrTable.\n\nThe snmpTargetAddrExtTable augments the\nsnmpTargetAddrTable with a transport address mask value\nand a maximum message size value. The transport address\nmask allows entries in the snmpTargetAddrTable to define\na set of addresses instead of just a single address.\nThe maximum message size value allows the maximum\nmessage size of another SNMP entity to be configured for\nuse in SNMPv1 (and SNMPv2c) transactions, where the\nmessage format does not specify a maximum message size.") snmpTargetAddrExtEntry = MibTableRow((1, 3, 6, 1, 6, 3, 18, 1, 2, 1)) if mibBuilder.loadTexts: snmpTargetAddrExtEntry.setDescription("Information about a particular mask and mms value.") snmpTargetAddrTMask = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 2, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTMask.setDescription("The mask value associated with an entry in the\nsnmpTargetAddrTable. The value of this object must\nhave the same length as the corresponding instance of\nsnmpTargetAddrTAddress, or must have length 0. An\nattempt to set it to any other value will result in\nan inconsistentValue error.\n\nThe value of this object allows an entry in the\nsnmpTargetAddrTable to specify multiple addresses.\nThe mask value is used to select which bits of\na transport address must match bits of the corresponding\ninstance of snmpTargetAddrTAddress, in order for the\ntransport address to match a particular entry in the\nsnmpTargetAddrTable. Bits which are 1 in the mask\nvalue indicate bits in the transport address which\nmust match bits in the snmpTargetAddrTAddress value.\n\nBits which are 0 in the mask indicate bits in the\ntransport address which need not match. If the\nlength of the mask is 0, the mask should be treated\nas if all its bits were 1 and its length were equal\nto the length of the corresponding value of\nsnmpTargetAddrTable.\n\nThis object may not be modified while the value of the\ncorresponding instance of snmpTargetAddrRowStatus is\nactive(1). An attempt to set this object in this case\nwill result in an inconsistentValue error.") snmpTargetAddrMMS = MibTableColumn((1, 3, 6, 1, 6, 3, 18, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0,0),ValueRangeConstraint(484,2147483647),)).clone(484)).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrMMS.setDescription("The maximum message size value associated with an entry\nin the snmpTargetAddrTable.") snmpTrapAddress = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 3), IpAddress()).setMaxAccess("notifyonly") if mibBuilder.loadTexts: snmpTrapAddress.setDescription("The value of the agent-addr field of a Trap PDU which\nis forwarded by a proxy forwarder application using\nan SNMP version other than SNMPv1. The value of this\nobject SHOULD contain the value of the agent-addr field\nfrom the original Trap PDU as generated by an SNMPv1\nagent.") snmpTrapCommunity = MibScalar((1, 3, 6, 1, 6, 3, 18, 1, 4), OctetString()).setMaxAccess("notifyonly") if mibBuilder.loadTexts: snmpTrapCommunity.setDescription("The value of the community string field of an SNMPv1\nmessage containing a Trap PDU which is forwarded by a\na proxy forwarder application using an SNMP version\nother than SNMPv1. The value of this object SHOULD\ncontain the value of the community string field from\nthe original SNMPv1 message containing a Trap PDU as\ngenerated by an SNMPv1 agent.") snmpCommunityMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2)) snmpCommunityMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 1)) snmpCommunityMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 18, 2, 2)) # Augmentions snmpTargetAddrEntry, = mibBuilder.importSymbols("SNMP-TARGET-MIB", "snmpTargetAddrEntry") snmpTargetAddrEntry.registerAugmentions(("SNMP-COMMUNITY-MIB", "snmpTargetAddrExtEntry")) snmpTargetAddrExtEntry.setIndexNames(*snmpTargetAddrEntry.getIndexNames()) # Groups snmpCommunityGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 18, 2, 2, 1)).setObjects(*(("SNMP-COMMUNITY-MIB", "snmpCommunitySecurityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityTransportTag"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStorageType"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrMMS"), ("SNMP-COMMUNITY-MIB", "snmpTargetAddrTMask"), ("SNMP-COMMUNITY-MIB", "snmpCommunityName"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextEngineID"), ("SNMP-COMMUNITY-MIB", "snmpCommunityStatus"), ("SNMP-COMMUNITY-MIB", "snmpCommunityContextName"), ) ) if mibBuilder.loadTexts: snmpCommunityGroup.setDescription("A collection of objects providing for configuration\nof community strings for SNMPv1 (and SNMPv2c) usage.") snmpProxyTrapForwardGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 18, 2, 2, 3)).setObjects(*(("SNMP-COMMUNITY-MIB", "snmpTrapAddress"), ("SNMP-COMMUNITY-MIB", "snmpTrapCommunity"), ) ) if mibBuilder.loadTexts: snmpProxyTrapForwardGroup.setDescription("Objects which are used by proxy forwarding applications\nwhen translating traps between SNMP versions. These are\nused to preserve SNMPv1-specific information when\n\ntranslating to SNMPv2c or SNMPv3.") # Compliances snmpCommunityMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 18, 2, 1, 1)).setObjects(*(("SNMP-COMMUNITY-MIB", "snmpCommunityGroup"), ) ) if mibBuilder.loadTexts: snmpCommunityMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP-COMMUNITY-MIB.") snmpProxyTrapForwardCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 18, 2, 1, 2)).setObjects(*(("SNMP-COMMUNITY-MIB", "snmpProxyTrapForwardGroup"), ) ) if mibBuilder.loadTexts: snmpProxyTrapForwardCompliance.setDescription("The compliance statement for SNMP engines which\ncontain a proxy forwarding application which is\ncapable of forwarding SNMPv1 traps using SNMPv2c\nor SNMPv3.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", PYSNMP_MODULE_ID=snmpCommunityMIB) # Objects mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityMIB=snmpCommunityMIB, snmpCommunityMIBObjects=snmpCommunityMIBObjects, snmpCommunityTable=snmpCommunityTable, snmpCommunityEntry=snmpCommunityEntry, snmpCommunityIndex=snmpCommunityIndex, snmpCommunityName=snmpCommunityName, snmpCommunitySecurityName=snmpCommunitySecurityName, snmpCommunityContextEngineID=snmpCommunityContextEngineID, snmpCommunityContextName=snmpCommunityContextName, snmpCommunityTransportTag=snmpCommunityTransportTag, snmpCommunityStorageType=snmpCommunityStorageType, snmpCommunityStatus=snmpCommunityStatus, snmpTargetAddrExtTable=snmpTargetAddrExtTable, snmpTargetAddrExtEntry=snmpTargetAddrExtEntry, snmpTargetAddrTMask=snmpTargetAddrTMask, snmpTargetAddrMMS=snmpTargetAddrMMS, snmpTrapAddress=snmpTrapAddress, snmpTrapCommunity=snmpTrapCommunity, snmpCommunityMIBConformance=snmpCommunityMIBConformance, snmpCommunityMIBCompliances=snmpCommunityMIBCompliances, snmpCommunityMIBGroups=snmpCommunityMIBGroups) # Groups mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityGroup=snmpCommunityGroup, snmpProxyTrapForwardGroup=snmpProxyTrapForwardGroup) # Compliances mibBuilder.exportSymbols("SNMP-COMMUNITY-MIB", snmpCommunityMIBCompliance=snmpCommunityMIBCompliance, snmpProxyTrapForwardCompliance=snmpProxyTrapForwardCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/PYSNMP-USM-MIB.py0000644000076400001440000001616611736534255020735 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-USM-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 12:45:33 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( pysnmpModuleIDs, ) = mibBuilder.importSymbols("PYSNMP-MIB", "pysnmpModuleIDs") ( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ( usmUserEntry, ) = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") ( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks") ( RowStatus, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus") # Objects pysnmpUsmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1)).setRevisions(("2005-05-14 00:00",)) if mibBuilder.loadTexts: pysnmpUsmMIB.setOrganization("The PySNMP project") if mibBuilder.loadTexts: pysnmpUsmMIB.setContactInfo("E-mail: ilya@glas.net\nSubscribe: pysnmp-users-request@lists.sourceforge.net") if mibBuilder.loadTexts: pysnmpUsmMIB.setDescription("This MIB module defines objects specific to User\nSecurity Model (USM) implementation at PySNMP.") pysnmpUsmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1)) pysnmpUsmCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1)) pysnmpUsmDiscoverable = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 1), Integer().subtype(subtypeSpec=SingleValueConstraint(1,0,)).subtype(namedValues=NamedValues(("notDiscoverable", 0), ("discoverable", 1), )).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: pysnmpUsmDiscoverable.setDescription("Whether SNMP engine would support its discovery by\nresponding to unknown clients.") pysnmpUsmDiscovery = MibScalar((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 1, 2), Integer().subtype(subtypeSpec=SingleValueConstraint(1,0,)).subtype(namedValues=NamedValues(("doNotDiscover", 0), ("doDiscover", 1), )).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: pysnmpUsmDiscovery.setDescription("Whether SNMP engine would try to figure out the EngineIDs\nof its peers by sending discover requests.") pysnmpUsmSecretTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2)) if mibBuilder.loadTexts: pysnmpUsmSecretTable.setDescription("The table of USM users passphrases configured in the SNMP \nengine's Local Configuration Datastore (LCD).") pysnmpUsmSecretEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1)).setIndexNames((1, "PYSNMP-USM-MIB", "pysnmpUsmSecretUserName")) if mibBuilder.loadTexts: pysnmpUsmSecretEntry.setDescription("Information about a particular USM user credentials.") pysnmpUsmSecretUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmSecretUserName.setDescription("The username string for which a row in this table\nrepresents a configuration.") pysnmpUsmSecretAuthKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 65535))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmSecretAuthKey.setDescription("User's authentication passphrase used for localized key generation.") pysnmpUsmSecretPrivKey = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 65535))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmSecretPrivKey.setDescription("User's encryption passphrase used for localized key generation.") pysnmpUsmSecretStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: pysnmpUsmSecretStatus.setDescription("Table status") pysnmpUsmUser = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3)) pysnmpUsmKeyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1)) if mibBuilder.loadTexts: pysnmpUsmKeyEntry.setDescription("Information about a particular USM user credentials.") pysnmpUsmKeyAuthLocalized = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmKeyAuthLocalized.setDescription("User's localized key used for authentication.") pysnmpUsmKeyPrivLocalized = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmKeyPrivLocalized.setDescription("User's localized key used for encryption.") pysnmpUsmKeyAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmKeyAuth.setDescription("User's non-localized key used for authentication.") pysnmpUsmKeyPriv = MibTableColumn((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 1, 3, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(8, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: pysnmpUsmKeyPriv.setDescription("User's non-localized key used for encryption.") pysnmpUsmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2)) pysnmpUsmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2, 1)) pysnmpUsmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1, 1, 2, 2)) # Augmentions usmUserEntry, = mibBuilder.importSymbols("SNMP-USER-BASED-SM-MIB", "usmUserEntry") usmUserEntry.registerAugmentions(("PYSNMP-USM-MIB", "pysnmpUsmKeyEntry")) pysnmpUsmKeyEntry.setIndexNames(*usmUserEntry.getIndexNames()) # Exports # Module identity mibBuilder.exportSymbols("PYSNMP-USM-MIB", PYSNMP_MODULE_ID=pysnmpUsmMIB) # Objects mibBuilder.exportSymbols("PYSNMP-USM-MIB", pysnmpUsmMIB=pysnmpUsmMIB, pysnmpUsmMIBObjects=pysnmpUsmMIBObjects, pysnmpUsmCfg=pysnmpUsmCfg, pysnmpUsmDiscoverable=pysnmpUsmDiscoverable, pysnmpUsmDiscovery=pysnmpUsmDiscovery, pysnmpUsmSecretTable=pysnmpUsmSecretTable, pysnmpUsmSecretEntry=pysnmpUsmSecretEntry, pysnmpUsmSecretUserName=pysnmpUsmSecretUserName, pysnmpUsmSecretAuthKey=pysnmpUsmSecretAuthKey, pysnmpUsmSecretPrivKey=pysnmpUsmSecretPrivKey, pysnmpUsmSecretStatus=pysnmpUsmSecretStatus, pysnmpUsmUser=pysnmpUsmUser, pysnmpUsmKeyEntry=pysnmpUsmKeyEntry, pysnmpUsmKeyAuthLocalized=pysnmpUsmKeyAuthLocalized, pysnmpUsmKeyPrivLocalized=pysnmpUsmKeyPrivLocalized, pysnmpUsmKeyAuth=pysnmpUsmKeyAuth, pysnmpUsmKeyPriv=pysnmpUsmKeyPriv, pysnmpUsmMIBConformance=pysnmpUsmMIBConformance, pysnmpUsmMIBCompliances=pysnmpUsmMIBCompliances, pysnmpUsmMIBGroups=pysnmpUsmMIBGroups) pysnmp-4.2.5/pysnmp/smi/mibs/PYSNMP-MIB.py0000644000076400001440000000532411736354302020256 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python PYSNMP-MIB # by libsmi2pysnmp-0.1.3 at Mon Apr 2 20:50:10 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( Bits, Integer32, ModuleIdentity, MibIdentifier, TimeTicks, enterprises, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "TimeTicks", "enterprises") # Objects pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408)).setRevisions(("2005-05-14 00:00",)) if mibBuilder.loadTexts: pysnmp.setOrganization("pysnmp.sf.net") if mibBuilder.loadTexts: pysnmp.setContactInfo("email: ilya@glas.net") if mibBuilder.loadTexts: pysnmp.setDescription("Top-level infrastructure of the PySNMP project enterprise MIB tree") pysnmpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 1)) pysnmpExamples = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 2)) pysnmpEnumerations = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3)) pysnmpModuleIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1)) pysnmpAgentOIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 2)) pysnmpDomains = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 3)) pysnmpNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4)) pysnmpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 0)) pysnmpNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 1)) pysnmpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5)) pysnmpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 1)) pysnmpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 2)) pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999)) # Augmentions # Exports # Module identity mibBuilder.exportSymbols("PYSNMP-MIB", PYSNMP_MODULE_ID=pysnmp) # Objects mibBuilder.exportSymbols("PYSNMP-MIB", pysnmp=pysnmp, pysnmpObjects=pysnmpObjects, pysnmpExamples=pysnmpExamples, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpDomains=pysnmpDomains, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpNotifications=pysnmpNotifications, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpConformance=pysnmpConformance, pysnmpCompliances=pysnmpCompliances, pysnmpGroups=pysnmpGroups, pysnmpExperimental=pysnmpExperimental) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-FRAMEWORK-MIB.py0000644000076400001440000002130312206334611021325 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-FRAMEWORK-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 12:50:45 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) try: import os except ImportError: pass import time # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention") # Types class SnmpAdminString(TextualConvention, OctetString): displayHint = "255t" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) encoding = 'utf-8' class SnmpEngineID(TextualConvention, OctetString): 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: pass try: # Attempt to base engine ID on PID defaultValue += [ os.getpid() >> 8 & 0xff, os.getpid() & 0xff ] except: pass # add pseudo-random text ID defaultValue += [ id(defaultValue) >> 8 & 0xff, id(defaultValue) & 0xff ] defaultValue = OctetString(defaultValue).asOctets() class SnmpEngineTime(Integer32): def clone(self, value=None, tagSet=None, subtypeSpec=None): if value is None: try: value = time.time() - self except: pass return Integer32.clone(self, value, tagSet, subtypeSpec) class SnmpMessageProcessingModel(Integer32): subtypeSpec = Integer32.subtypeSpec+ValueRangeConstraint(0,2147483647) class SnmpSecurityLevel(Integer): subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(1,3,2,) namedValues = NamedValues(("noAuthNoPriv", 1), ("authNoPriv", 2), ("authPriv", 3), ) class SnmpSecurityModel(Integer32): subtypeSpec = Integer32.subtypeSpec+ValueRangeConstraint(0,2147483647) # Objects snmpFrameworkMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 10)).setRevisions(("2002-10-14 00:00","1999-01-19 00:00","1997-11-20 00:00",)) if mibBuilder.loadTexts: snmpFrameworkMIB.setOrganization("SNMPv3 Working Group") if mibBuilder.loadTexts: snmpFrameworkMIB.setContactInfo("WG-EMail: snmpv3@lists.tislabs.com\nSubscribe: snmpv3-request@lists.tislabs.com\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nEMail: mundy@tislabs.com\nphone: +1 301-947-7107\n\nCo-Chair &\nCo-editor: David Harrington\n Enterasys Networks\npostal: 35 Industrial Way\n P. O. Box 5005\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nphone: +1 603-337-2614\n\nCo-editor: Randy Presuhn\n BMC Software, Inc.\npostal: 2141 North First Street\n San Jose, California 95131\n USA\nEMail: randy_presuhn@bmc.com\nphone: +1 408-546-1006\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\n\nEMail: bwijnen@lucent.com\nphone: +31 348-680-485\n ") if mibBuilder.loadTexts: snmpFrameworkMIB.setDescription("The SNMP Management Architecture MIB\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3411;\nsee the RFC itself for full legal notices.") snmpFrameworkAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 1)) snmpAuthProtocols = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 1)) if mibBuilder.loadTexts: snmpAuthProtocols.setDescription("Registration point for standards-track\nauthentication protocols used in SNMP Management\nFrameworks.") snmpPrivProtocols = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2)) if mibBuilder.loadTexts: snmpPrivProtocols.setDescription("Registration point for standards-track privacy\nprotocols used in SNMP Management Frameworks.") snmpFrameworkMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 2)) snmpEngine = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 2, 1)) snmpEngineID = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 1), SnmpEngineID()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpEngineID.setDescription("An SNMP engine's administratively-unique identifier.\n\nThis information SHOULD be stored in non-volatile\nstorage so that it remains constant across\nre-initializations of the SNMP engine.") snmpEngineBoots = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpEngineBoots.setDescription("The number of times that the SNMP engine has\n(re-)initialized itself since snmpEngineID\nwas last configured.") snmpEngineTime = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 3), SnmpEngineTime().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly").setUnits("seconds") if mibBuilder.loadTexts: snmpEngineTime.setDescription("The number of seconds since the value of\nthe snmpEngineBoots object last changed.\nWhen incrementing this object's value would\ncause it to exceed its maximum,\nsnmpEngineBoots is incremented as if a\nre-initialization had occurred, and this\nobject's value consequently reverts to zero.") snmpEngineMaxMessageSize = MibScalar((1, 3, 6, 1, 6, 3, 10, 2, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(484, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpEngineMaxMessageSize.setDescription("The maximum length in octets of an SNMP message\nwhich this SNMP engine can send or receive and\nprocess, determined as the minimum of the maximum\nmessage size values supported among all of the\ntransports available to and supported by the engine.") snmpFrameworkMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3)) snmpFrameworkMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 1)) snmpFrameworkMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 10, 3, 2)) # Augmentions # Groups snmpEngineGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 10, 3, 2, 1)).setObjects(*(("SNMP-FRAMEWORK-MIB", "snmpEngineID"), ("SNMP-FRAMEWORK-MIB", "snmpEngineBoots"), ("SNMP-FRAMEWORK-MIB", "snmpEngineMaxMessageSize"), ("SNMP-FRAMEWORK-MIB", "snmpEngineTime"), ) ) if mibBuilder.loadTexts: snmpEngineGroup.setDescription("A collection of objects for identifying and\ndetermining the configuration and current timeliness\n\nvalues of an SNMP engine.") # Compliances snmpFrameworkMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 10, 3, 1, 1)).setObjects(*(("SNMP-FRAMEWORK-MIB", "snmpEngineGroup"), ) ) if mibBuilder.loadTexts: snmpFrameworkMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP Management Framework MIB.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", PYSNMP_MODULE_ID=snmpFrameworkMIB) # Types mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", SnmpAdminString=SnmpAdminString, SnmpEngineID=SnmpEngineID, SnmpEngineTime=SnmpEngineTime, SnmpMessageProcessingModel=SnmpMessageProcessingModel, SnmpSecurityLevel=SnmpSecurityLevel, SnmpSecurityModel=SnmpSecurityModel) # Objects mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpFrameworkMIB=snmpFrameworkMIB, snmpFrameworkAdmin=snmpFrameworkAdmin, snmpAuthProtocols=snmpAuthProtocols, snmpPrivProtocols=snmpPrivProtocols, snmpFrameworkMIBObjects=snmpFrameworkMIBObjects, snmpEngine=snmpEngine, snmpEngineID=snmpEngineID, snmpEngineBoots=snmpEngineBoots, snmpEngineTime=snmpEngineTime, snmpEngineMaxMessageSize=snmpEngineMaxMessageSize, snmpFrameworkMIBConformance=snmpFrameworkMIBConformance, snmpFrameworkMIBCompliances=snmpFrameworkMIBCompliances, snmpFrameworkMIBGroups=snmpFrameworkMIBGroups) # Groups mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpEngineGroup=snmpEngineGroup) # Compliances mibBuilder.exportSymbols("SNMP-FRAMEWORK-MIB", snmpFrameworkMIBCompliance=snmpFrameworkMIBCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-USM-AES-MIB.py0000644000076400001440000000464011736570774021072 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-USM-AES-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:50:04 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( snmpPrivProtocols, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "snmpPrivProtocols") ( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "TimeTicks", "snmpModules") # Objects usmAesCfb128Protocol = ObjectIdentity((1, 3, 6, 1, 6, 3, 10, 1, 2, 4)) if mibBuilder.loadTexts: usmAesCfb128Protocol.setDescription("The CFB128-AES-128 Privacy Protocol.") snmpUsmAesMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 20)).setRevisions(("2004-06-14 00:00",)) if mibBuilder.loadTexts: snmpUsmAesMIB.setOrganization("IETF") if mibBuilder.loadTexts: snmpUsmAesMIB.setContactInfo("Uri Blumenthal\nLucent Technologies / Bell Labs\n67 Whippany Rd.\n14D-318\nWhippany, NJ 07981, USA\n973-386-2163\nuri@bell-labs.com\n\nFabio Maino\nAndiamo Systems, Inc.\n375 East Tasman Drive\nSan Jose, CA 95134, USA\n408-853-7530\nfmaino@andiamo.com\n\nKeith McCloghrie\nCisco Systems, Inc.\n170 West Tasman Drive\nSan Jose, CA 95134-1706, USA\n\n408-526-5260\nkzm@cisco.com") if mibBuilder.loadTexts: snmpUsmAesMIB.setDescription("Definitions of Object Identities needed for\nthe use of AES by SNMP's User-based Security\nModel.\n\nCopyright (C) The Internet Society (2004).\n\nThis version of this MIB module is part of RFC 3826;\nsee the RFC itself for full legal notices.\nSupplementary information may be available on\nhttp://www.ietf.org/copyrights/ianamib.html.") # Augmentions # Exports # Module identity mibBuilder.exportSymbols("SNMP-USM-AES-MIB", PYSNMP_MODULE_ID=snmpUsmAesMIB) # Objects mibBuilder.exportSymbols("SNMP-USM-AES-MIB", usmAesCfb128Protocol=usmAesCfb128Protocol, snmpUsmAesMIB=snmpUsmAesMIB) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-USER-BASED-SM-3DES-MIB.py0000644000076400001440000000153411736564420022411 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python Eurocrypt # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:12:00 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( Bits, Integer32, MibIdentifier, TimeTicks, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "MibIdentifier", "TimeTicks") # Exports pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-MPD-MIB.py0000644000076400001440000001315211736555511020426 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-MPD-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 15:13:13 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") # Objects snmpMPDMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 11)).setRevisions(("2002-10-14 00:00","1999-05-04 16:36","1997-09-30 00:00",)) if mibBuilder.loadTexts: snmpMPDMIB.setOrganization("SNMPv3 Working Group") if mibBuilder.loadTexts: snmpMPDMIB.setContactInfo("WG-EMail: snmpv3@lists.tislabs.com\nSubscribe: snmpv3-request@lists.tislabs.com\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\n\nEMail: mundy@tislabs.com\nphone: +1 301-947-7107\n\nCo-Chair &\nCo-editor: David Harrington\n Enterasys Networks\npostal: 35 Industrial Way\n P. O. Box 5005\n Rochester NH 03866-5005\n USA\nEMail: dbh@enterasys.com\nphone: +1 603-337-2614\n\nCo-editor: Jeffrey Case\n SNMP Research, Inc.\npostal: 3001 Kimberlin Heights Road\n Knoxville, TN 37920-9716\n USA\nEMail: case@snmp.com\nphone: +1 423-573-1434\n\nCo-editor: Randy Presuhn\n BMC Software, Inc.\npostal: 2141 North First Street\n San Jose, CA 95131\n USA\nEMail: randy_presuhn@bmc.com\nphone: +1 408-546-1006\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nEMail: bwijnen@lucent.com\nphone: +31 348-680-485") if mibBuilder.loadTexts: snmpMPDMIB.setDescription("The MIB for Message Processing and Dispatching\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3412;\nsee the RFC itself for full legal notices.") snmpMPDAdmin = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 1)) snmpMPDMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2)) snmpMPDStats = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 2, 1)) snmpUnknownSecurityModels = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpUnknownSecurityModels.setDescription("The total number of packets received by the SNMP\nengine which were dropped because they referenced a\nsecurityModel that was not known to or supported by\nthe SNMP engine.") snmpInvalidMsgs = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInvalidMsgs.setDescription("The total number of packets received by the SNMP\nengine which were dropped because there were invalid\nor inconsistent components in the SNMP message.") snmpUnknownPDUHandlers = MibScalar((1, 3, 6, 1, 6, 3, 11, 2, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpUnknownPDUHandlers.setDescription("The total number of packets received by the SNMP\nengine which were dropped because the PDU contained\nin the packet could not be passed to an application\nresponsible for handling the pduType, e.g. no SNMP\napplication had registered for the proper\ncombination of the contextEngineID and the pduType.") snmpMPDMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3)) snmpMPDMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 1)) snmpMPDMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 11, 3, 2)) # Augmentions # Groups snmpMPDGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 11, 3, 2, 1)).setObjects(*(("SNMP-MPD-MIB", "snmpInvalidMsgs"), ("SNMP-MPD-MIB", "snmpUnknownPDUHandlers"), ("SNMP-MPD-MIB", "snmpUnknownSecurityModels"), ) ) if mibBuilder.loadTexts: snmpMPDGroup.setDescription("A collection of objects providing for remote\nmonitoring of the SNMP Message Processing and\nDispatching process.") # Compliances snmpMPDCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 11, 3, 1, 1)).setObjects(*(("SNMP-MPD-MIB", "snmpMPDGroup"), ) ) if mibBuilder.loadTexts: snmpMPDCompliance.setDescription("The compliance statement for SNMP entities which\nimplement the SNMP-MPD-MIB.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-MPD-MIB", PYSNMP_MODULE_ID=snmpMPDMIB) # Objects mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDMIB=snmpMPDMIB, snmpMPDAdmin=snmpMPDAdmin, snmpMPDMIBObjects=snmpMPDMIBObjects, snmpMPDStats=snmpMPDStats, snmpUnknownSecurityModels=snmpUnknownSecurityModels, snmpInvalidMsgs=snmpInvalidMsgs, snmpUnknownPDUHandlers=snmpUnknownPDUHandlers, snmpMPDMIBConformance=snmpMPDMIBConformance, snmpMPDMIBCompliances=snmpMPDMIBCompliances, snmpMPDMIBGroups=snmpMPDMIBGroups) # Groups mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDGroup=snmpMPDGroup) # Compliances mibBuilder.exportSymbols("SNMP-MPD-MIB", snmpMPDCompliance=snmpMPDCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/SNMPv2-TC.py0000644000076400001440000003107312155373360020155 0ustar ilyausers00000000000000import sys from pysnmp.smi import error from pysnmp import debug OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols( 'ASN1', 'OctetString', 'Integer', 'ObjectIdentifier' ) ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols( "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" ) Counter32, Unsigned32, TimeTicks, Counter64 = mibBuilder.importSymbols( 'SNMPv2-SMI', 'Counter32', 'Unsigned32', 'TimeTicks', 'Counter64' ) class TextualConvention: displayHint = '' status = 'current' description = '' reference = '' bits = () __integer = Integer() __counter32 = Counter32() __unsigned32 = Unsigned32() __timeticks = TimeTicks() __counter64 = Counter64() __octetString = OctetString() __objectIdentifier = ObjectIdentifier() def getDisplayHint(self): return self.displayHint def getStatus(self): return self.status def getDescription(self): return self.description def getReference(self): return self.reference def getValue(self): return self.clone() def setValue(self, value): return self.clone(value) def prettyOut(self, value): # override asn1 type method """Implements DISPLAY-HINT evaluation""" if self.displayHint and ( self.__integer.isSuperTypeOf(self) or self.__unsigned32.isSuperTypeOf(self) or self.__timeticks.isSuperTypeOf(self) or self.__counter32.isSuperTypeOf(self) or self.__counter64.isSuperTypeOf(self) ): _ = lambda t, f=0: (t, f) t, f = _(*self.displayHint.split('-')) if t == 'x': return '0x%x' % value elif t == 'd': try: return '%.*f' % (int(f), float(value)/pow(10, int(f))) except Exception: raise error.SmiError( 'float num evaluation error: %s' % sys.exc_info()[1] ) elif t == 'o': return '0%o' % value elif t == 'b': v = value; r = ['B'] while v: r.insert(0, '%d' % (v&0x01)) v = v>>1 return ''.join(r) else: raise error.SmiError( 'Unsupported numeric type spec: %s' % t ) elif self.displayHint and self.__octetString.isSuperTypeOf(self): r = '' v = self.__class__(value).asNumbers() d = self.displayHint while v and d: # 1 if d[0] == '*': repeatIndicator = repeatCount = v[0] d = d[1:]; v = v[1:] else: repeatCount = 1; repeatIndicator = None # 2 octetLength = '' while d and d[0] in '0123456789': octetLength = octetLength + d[0] d = d[1:] try: octetLength = int(octetLength) except Exception: raise error.SmiError( 'Bad octet length: %s' % octetLength ) if not d: raise error.SmiError( 'Short octet length: %s' % self.displayHint ) # 3 displayFormat = d[0] d = d[1:] # 4 if d and d[0] not in '0123456789' and d[0] != '*': displaySep = d[0] d = d[1:] else: displaySep = '' # 5 if d and displaySep and repeatIndicator is not None: repeatTerminator = d[0] displaySep = '' d = d[1:] else: repeatTerminator = None while repeatCount: repeatCount = repeatCount - 1 # 't' stands for UTF-8, does it need any special support? if displayFormat == 'a' or displayFormat == 't': r = r + ''.join([ chr(x) for x in v[:octetLength] ]) elif displayFormat in ('x', 'd', 'o'): n = 0; vv = v[:octetLength] while vv: n = n << 8 try: n = n | vv[0] vv = vv[1:] except Exception: raise error.SmiError( 'Display format eval failure: %s: %s' % (vv, sys.exc_info()[1]) ) if displayFormat == 'x': r = r + '%02x' % n elif displayFormat == 'o': r = r + '%03o' % n else: r = r + '%d' % n else: raise error.SmiError( 'Unsupported display format char: %s' % \ displayFormat ) if v and repeatTerminator: r = r + repeatTerminator v = v[octetLength:] if v and displaySep: r = r + displaySep if not d: d = self.displayHint # if d: # raise error.SmiError( # 'Unparsed display hint left: %s' % d # ) return r elif self.__objectIdentifier.isSuperTypeOf(self): return self.__objectIdentifier.prettyOut(value) elif self.__octetString.isSuperTypeOf(self): return self.__octetString.prettyOut(value) else: return str(value) # elif self.bits: # try: # return self.bits[value] # except Exception: # raise error.SmiError( # 'Enumeratin resolution failure for %s: %s' % (self, sys.exc_info()[1]) # ) # XXX # def prettyIn(self, value): # # XXX parse TC syntax # return str(value) class DisplayString(TextualConvention, OctetString): subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) displayHint = "255a" class PhysAddress(TextualConvention, OctetString): displayHint = "1x:" class MacAddress(TextualConvention, OctetString): subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(6,6) displayHint = "1x:" fixedLength = 6 class TruthValue(Integer, TextualConvention): subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(1, 2) namedValues = NamedValues(('true', 1), ('false', 2)) class TestAndIncr(Integer, TextualConvention): subtypeSpec = Integer.subtypeSpec+ValueRangeConstraint(0, 2147483647) defaultValue = 0 def setValue(self, value): if value is not None: if value != self: raise error.InconsistentValueError() value = value + 1 if value > 2147483646: value = 0 return self.clone(self, value) class AutonomousType(ObjectIdentifier, TextualConvention): pass class InstancePointer(ObjectIdentifier, TextualConvention): status = 'obsolete' class VariablePointer(ObjectIdentifier, TextualConvention): pass class RowPointer(ObjectIdentifier, TextualConvention): pass class RowStatus(Integer, TextualConvention): """A special kind of scalar MIB variable responsible for MIB table row creation/destruction. """ subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(0, 1, 2, 3, 4, 5, 6) namedValues = NamedValues( ('notExists', 0), ('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6) ) # Known row states stNotExists, stActive, stNotInService, stNotReady, \ stCreateAndGo, stCreateAndWait, stDestroy = list(range(7)) # States transition matrix (see RFC-1903) stateMatrix = { # (new-state, current-state) -> (error, new-state) ( stCreateAndGo, stNotExists ): ( error.RowCreationWanted, stActive ), ( stCreateAndGo, stNotReady ): ( error.InconsistentValueError, stNotReady ), ( stCreateAndGo, stNotInService ): ( error.InconsistentValueError, stNotInService ), ( stCreateAndGo, stActive ): ( error.InconsistentValueError, stActive ), # ( stCreateAndWait, stNotExists ): ( error.RowCreationWanted, stActive ), ( stCreateAndWait, stNotReady ): ( error.InconsistentValueError, stNotReady ), ( stCreateAndWait, stNotInService ): ( error.InconsistentValueError, stNotInService ), ( stCreateAndWait, stActive ): ( error.InconsistentValueError, stActive ), # ( stActive, stNotExists ): ( error.InconsistentValueError, stNotExists ), ( stActive, stNotReady ): ( error.InconsistentValueError, stNotReady ), ( stActive, stNotInService ): ( None, stActive ), ( stActive, stActive ): ( None, stActive ), # ( stNotInService, stNotExists ): ( error.InconsistentValueError, stNotExists ), ( stNotInService, stNotReady ): ( error.InconsistentValueError, stNotReady ), ( stNotInService, stNotInService ): ( None, stNotInService ), ( stNotInService, stActive ): ( None, stActive ), # ( stDestroy, stNotExists ): ( error.RowDestructionWanted, stNotExists ), ( stDestroy, stNotReady ): ( error.RowDestructionWanted, stNotExists ), ( stDestroy, stNotInService ): ( error.RowDestructionWanted, stNotExists ), ( stDestroy, stActive ): ( error.RowDestructionWanted, stNotExists ), # This is used on instantiation ( stNotExists, stNotExists ): ( None, stNotExists ) } defaultValue = stNotExists def setValue(self, value): value = self.clone(value) # Run through states transition matrix, # resolve new instance value excValue, newState = self.stateMatrix.get( (value, self), (error.MibOperationError, None) ) newState = self.clone(newState) debug.logger & debug.flagIns and debug.logger('RowStatus state change from %r to %s 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 %s to %s yields state %s and exception' % (self, value, newState), syntax=newState ) raise excValue return newState class TimeStamp(TimeTicks, TextualConvention): pass class TimeInterval(Integer, TextualConvention): subtypeSpec = Integer.subtypeSpec+ValueRangeConstraint(0, 2147483647) class DateAndTime(TextualConvention, OctetString): subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(8, 11) displayHint = "2d-1d-1d,1d:1d:1d.1d,1a1d:1d" class StorageType(Integer, TextualConvention): subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(1, 2, 3, 4, 5) namedValues = NamedValues( ('other', 1), ('volatile', 2), ('nonVolatile', 3), ('permanent', 4), ('readOnly', 5) ) class TDomain(ObjectIdentifier, TextualConvention): pass class TAddress(OctetString, TextualConvention): subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1, 255) mibBuilder.exportSymbols( 'SNMPv2-TC', TextualConvention=TextualConvention, DisplayString=DisplayString, PhysAddress=PhysAddress, MacAddress=MacAddress, TruthValue=TruthValue, TestAndIncr=TestAndIncr, AutonomousType=AutonomousType, InstancePointer=InstancePointer, VariablePointer=VariablePointer, RowPointer=RowPointer, RowStatus=RowStatus, TimeStamp=TimeStamp, TimeInterval=TimeInterval, DateAndTime=DateAndTime, StorageType=StorageType, TDomain=TDomain, TAddress=TAddress ) pysnmp-4.2.5/pysnmp/smi/mibs/SNMPv2-CONF.py0000644000076400001440000000412011671666446020401 0ustar ilyausers00000000000000 MibNode, = mibBuilder.importSymbols('SNMPv2-SMI', 'MibNode') class ObjectGroup(MibNode): def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args): self.objects = args return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def asn1Print(self): return '\ OBJECT-GROUP\n\ OBJECTS { %s }\n\ DESCRIPTION \"%s\"\ ' % (', '.join([ x for x in self.getObjects() ]), self.getDescription()) class NotificationGroup(MibNode): def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args): self.objects = args return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def asn1Print(self): return '\ NOTIFICATION-GROUP\n\ NOTIFICATIONS { %s }\n\ DESCRIPTION \"%s\"\ ' % (', '.join([ x for x in self.getObjects() ]), self.getDescription()) class ModuleCompliance(MibNode): def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args): self.objects = args return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def asn1Print(self): return '\ MODULE-COMPLIANCE\n\ OBJECT { %s } \n\ DESCRIPTION \"%s\"\n\ ' % (', '.join([ x for x in self.getObjects() ]), self.getDescription()) class AgentCapabilities(MibNode): def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def asn1Print(self): return '\ AGENT-CAPABILITIES\n\ DESCRIPTION \"%s\"\n\ ' % self.getDescription() mibBuilder.exportSymbols('SNMPv2-CONF', ObjectGroup=ObjectGroup, NotificationGroup=NotificationGroup, ModuleCompliance=ModuleCompliance, AgentCapabilities=AgentCapabilities) pysnmp-4.2.5/pysnmp/smi/mibs/ASN1.py0000644000076400001440000000057611667155417017342 0ustar ilyausers00000000000000# ASN.1 objects used in SNMP from pyasn1.type import univ from pysnmp.proto import rfc1902 mibBuilder.exportSymbols( 'ASN1', ObjectIdentifier=univ.ObjectIdentifier, # Instead of using base ASN,1 types we use SNMPv2 SMI ones to make # SMI objects type-compatible with SNMP protocol values Integer=rfc1902.Integer32, OctetString=rfc1902.OctetString ) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-VIEW-BASED-ACM-MIB.py0000644000076400001440000006630611736571707022010 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-VIEW-BASED-ACM-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:57:42 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( SnmpAdminString, SnmpSecurityLevel, SnmpSecurityModel, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpSecurityLevel", "SnmpSecurityModel") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( RowStatus, StorageType, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TestAndIncr") # Objects snmpVacmMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 16)).setRevisions(("2002-10-16 00:00","1999-01-20 00:00","1997-11-20 00:00",)) if mibBuilder.loadTexts: snmpVacmMIB.setOrganization("SNMPv3 Working Group") if mibBuilder.loadTexts: snmpVacmMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In message body: subscribe snmpv3\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nemail: mundy@tislabs.com\nphone: +1 301-947-7107\n\nCo-Chair: David Harrington\n Enterasys Networks\nPostal: 35 Industrial Way\n P. O. Box 5004\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nPhone: +1 603-337-2614\n\nCo-editor: Bert Wijnen\n Lucent Technologies\npostal: Schagen 33\n 3461 GL Linschoten\n Netherlands\nemail: bwijnen@lucent.com\nphone: +31-348-480-685\n\nCo-editor: Randy Presuhn\n BMC Software, Inc.\n\npostal: 2141 North First Street\n San Jose, CA 95131\n USA\nemail: randy_presuhn@bmc.com\nphone: +1 408-546-1006\n\nCo-editor: Keith McCloghrie\n Cisco Systems, Inc.\npostal: 170 West Tasman Drive\n San Jose, CA 95134-1706\n USA\nemail: kzm@cisco.com\nphone: +1-408-526-5260") if mibBuilder.loadTexts: snmpVacmMIB.setDescription("The management information definitions for the\nView-based Access Control Model for SNMP.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3415;\nsee the RFC itself for full legal notices.") vacmMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1)) vacmContextTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 1)) if mibBuilder.loadTexts: vacmContextTable.setDescription("The table of locally available contexts.\n\nThis table provides information to SNMP Command\n\nGenerator applications so that they can properly\nconfigure the vacmAccessTable to control access to\nall contexts at the SNMP entity.\n\nThis table may change dynamically if the SNMP entity\nallows that contexts are added/deleted dynamically\n(for instance when its configuration changes). Such\nchanges would happen only if the management\ninstrumentation at that SNMP entity recognizes more\n(or fewer) contexts.\n\nThe presence of entries in this table and of entries\nin the vacmAccessTable are independent. That is, a\ncontext identified by an entry in this table is not\nnecessarily referenced by any entries in the\nvacmAccessTable; and the context(s) referenced by an\nentry in the vacmAccessTable does not necessarily\ncurrently exist and thus need not be identified by an\nentry in this table.\n\nThis table must be made accessible via the default\ncontext so that Command Responder applications have\na standard way of retrieving the information.\n\nThis table is read-only. It cannot be configured via\nSNMP.") vacmContextEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 1, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmContextName")) if mibBuilder.loadTexts: vacmContextEntry.setDescription("Information about a particular context.") vacmContextName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: vacmContextName.setDescription("A human readable name identifying a particular\ncontext at a particular SNMP entity.\n\nThe empty contextName (zero length) represents the\ndefault context.") vacmSecurityToGroupTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 2)) if mibBuilder.loadTexts: vacmSecurityToGroupTable.setDescription("This table maps a combination of securityModel and\nsecurityName into a groupName which is used to define\nan access control policy for a group of principals.") vacmSecurityToGroupEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 2, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityModel"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityName")) if mibBuilder.loadTexts: vacmSecurityToGroupEntry.setDescription("An entry in this table maps the combination of a\nsecurityModel and securityName into a groupName.") vacmSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 1), SnmpSecurityModel().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmSecurityModel.setDescription("The Security Model, by which the vacmSecurityName\nreferenced by this entry is provided.\n\nNote, this object may not take the 'any' (0) value.") vacmSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmSecurityName.setDescription("The securityName for the principal, represented in a\nSecurity Model independent format, which is mapped by\nthis entry to a groupName.") vacmGroupName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmGroupName.setDescription("The name of the group to which this entry (e.g., the\ncombination of securityModel and securityName)\nbelongs.\n\nThis groupName is used as index into the\nvacmAccessTable to select an access control policy.\nHowever, a value in this table does not imply that an\ninstance with the value exists in table vacmAccesTable.") vacmSecurityToGroupStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmSecurityToGroupStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") vacmSecurityToGroupStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmSecurityToGroupStatus.setDescription("The status of this conceptual row.\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\n\ncorresponding instance of the vacmSecurityToGroupStatus\ncolumn is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until a value has been set for vacmGroupName.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified.") vacmAccessTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 4)) if mibBuilder.loadTexts: vacmAccessTable.setDescription("The table of access rights for groups.\n\nEach entry is indexed by a groupName, a contextPrefix,\na securityModel and a securityLevel. To determine\nwhether access is allowed, one entry from this table\nneeds to be selected and the proper viewName from that\nentry must be used for access control checking.\n\nTo select the proper entry, follow these steps:\n\n1) the set of possible matches is formed by the\n intersection of the following sets of entries:\n\n the set of entries with identical vacmGroupName\n the union of these two sets:\n - the set with identical vacmAccessContextPrefix\n - the set of entries with vacmAccessContextMatch\n value of 'prefix' and matching\n vacmAccessContextPrefix\n intersected with the union of these two sets:\n - the set of entries with identical\n vacmSecurityModel\n - the set of entries with vacmSecurityModel\n value of 'any'\n intersected with the set of entries with\n vacmAccessSecurityLevel value less than or equal\n to the requested securityLevel\n\n2) if this set has only one member, we're done\n otherwise, it comes down to deciding how to weight\n the preferences between ContextPrefixes,\n SecurityModels, and SecurityLevels as follows:\n a) if the subset of entries with securityModel\n matching the securityModel in the message is\n not empty, then discard the rest.\n b) if the subset of entries with\n vacmAccessContextPrefix matching the contextName\n in the message is not empty,\n then discard the rest\n c) discard all entries with ContextPrefixes shorter\n than the longest one remaining in the set\n d) select the entry with the highest securityLevel\n\nPlease note that for securityLevel noAuthNoPriv, all\ngroups are really equivalent since the assumption that\nthe securityName has been authenticated does not hold.") vacmAccessEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 4, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextPrefix"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessSecurityModel"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmAccessSecurityLevel")) if mibBuilder.loadTexts: vacmAccessEntry.setDescription("An access right configured in the Local Configuration\nDatastore (LCD) authorizing access to an SNMP context.\n\nEntries in this table can use an instance value for\nobject vacmGroupName even if no entry in table\nvacmAccessSecurityToGroupTable has a corresponding\nvalue for object vacmGroupName.") vacmAccessContextPrefix = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmAccessContextPrefix.setDescription("In order to gain the access rights allowed by this\nconceptual row, a contextName must match exactly\n(if the value of vacmAccessContextMatch is 'exact')\nor partially (if the value of vacmAccessContextMatch\nis 'prefix') to the value of the instance of this\nobject.") vacmAccessSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 2), SnmpSecurityModel()).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmAccessSecurityModel.setDescription("In order to gain the access rights allowed by this\nconceptual row, this securityModel must be in use.") vacmAccessSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 3), SnmpSecurityLevel()).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmAccessSecurityLevel.setDescription("The minimum level of security required in order to\ngain the access rights allowed by this conceptual\nrow. A securityLevel of noAuthNoPriv is less than\nauthNoPriv which in turn is less than authPriv.\n\nIf multiple entries are equally indexed except for\nthis vacmAccessSecurityLevel index, then the entry\nwhich has the highest value for\nvacmAccessSecurityLevel is selected.") vacmAccessContextMatch = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 4), Integer().subtype(subtypeSpec=SingleValueConstraint(2,1,)).subtype(namedValues=NamedValues(("exact", 1), ("prefix", 2), )).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessContextMatch.setDescription("If the value of this object is exact(1), then all\nrows where the contextName exactly matches\nvacmAccessContextPrefix are selected.\n\nIf the value of this object is prefix(2), then all\nrows where the contextName whose starting octets\nexactly match vacmAccessContextPrefix are selected.\nThis allows for a simple form of wildcarding.") vacmAccessReadViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessReadViewName.setDescription("The value of an instance of this object identifies\nthe MIB view of the SNMP context to which this\nconceptual row authorizes read access.\n\nThe identified MIB view is that one for which the\nvacmViewTreeFamilyViewName has the same value as the\ninstance of this object; if the value is the empty\nstring or if there is no active MIB view having this\nvalue of vacmViewTreeFamilyViewName, then no access\nis granted.") vacmAccessWriteViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 6), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessWriteViewName.setDescription("The value of an instance of this object identifies\nthe MIB view of the SNMP context to which this\nconceptual row authorizes write access.\n\nThe identified MIB view is that one for which the\nvacmViewTreeFamilyViewName has the same value as the\ninstance of this object; if the value is the empty\nstring or if there is no active MIB view having this\nvalue of vacmViewTreeFamilyViewName, then no access\nis granted.") vacmAccessNotifyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessNotifyViewName.setDescription("The value of an instance of this object identifies\nthe MIB view of the SNMP context to which this\nconceptual row authorizes access for notifications.\n\nThe identified MIB view is that one for which the\nvacmViewTreeFamilyViewName has the same value as the\ninstance of this object; if the value is the empty\nstring or if there is no active MIB view having this\nvalue of vacmViewTreeFamilyViewName, then no access\nis granted.") vacmAccessStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessStorageType.setDescription("The storage type for this conceptual row.\n\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") vacmAccessStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 4, 1, 9), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmAccessStatus.setDescription("The status of this conceptual row.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified.") vacmMIBViews = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 1, 5)) vacmViewSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 16, 1, 5, 1), TestAndIncr()).setMaxAccess("readwrite") if mibBuilder.loadTexts: vacmViewSpinLock.setDescription("An advisory lock used to allow cooperating SNMP\nCommand Generator applications to coordinate their\nuse of the Set operation in creating or modifying\nviews.\n\nWhen creating a new view or altering an existing\nview, it is important to understand the potential\ninteractions with other uses of the view. The\nvacmViewSpinLock should be retrieved. The name of\nthe view to be created should be determined to be\nunique by the SNMP Command Generator application by\nconsulting the vacmViewTreeFamilyTable. Finally,\nthe named view may be created (Set), including the\nadvisory lock.\nIf another SNMP Command Generator application has\naltered the views in the meantime, then the spin\nlock's value will have changed, and so this creation\nwill fail because it will specify the wrong value for\nthe spin lock.\n\nSince this is an advisory lock, the use of this lock\nis not enforced.") vacmViewTreeFamilyTable = MibTable((1, 3, 6, 1, 6, 3, 16, 1, 5, 2)) if mibBuilder.loadTexts: vacmViewTreeFamilyTable.setDescription("Locally held information about families of subtrees\nwithin MIB views.\n\nEach MIB view is defined by two sets of view subtrees:\n - the included view subtrees, and\n - the excluded view subtrees.\nEvery such view subtree, both the included and the\n\nexcluded ones, is defined in this table.\n\nTo determine if a particular object instance is in\na particular MIB view, compare the object instance's\nOBJECT IDENTIFIER with each of the MIB view's active\nentries in this table. If none match, then the\nobject instance is not in the MIB view. If one or\nmore match, then the object instance is included in,\nor excluded from, the MIB view according to the\nvalue of vacmViewTreeFamilyType in the entry whose\nvalue of vacmViewTreeFamilySubtree has the most\nsub-identifiers. If multiple entries match and have\nthe same number of sub-identifiers (when wildcarding\nis specified with the value of vacmViewTreeFamilyMask),\nthen the lexicographically greatest instance of\nvacmViewTreeFamilyType determines the inclusion or\nexclusion.\n\nAn object instance's OBJECT IDENTIFIER X matches an\nactive entry in this table when the number of\nsub-identifiers in X is at least as many as in the\nvalue of vacmViewTreeFamilySubtree for the entry,\nand each sub-identifier in the value of\nvacmViewTreeFamilySubtree matches its corresponding\nsub-identifier in X. Two sub-identifiers match\neither if the corresponding bit of the value of\nvacmViewTreeFamilyMask for the entry is zero (the\n'wild card' value), or if they are equal.\n\nA 'family' of subtrees is the set of subtrees defined\nby a particular combination of values of\nvacmViewTreeFamilySubtree and vacmViewTreeFamilyMask.\n\nIn the case where no 'wild card' is defined in the\nvacmViewTreeFamilyMask, the family of subtrees reduces\nto a single subtree.\n\nWhen creating or changing MIB views, an SNMP Command\nGenerator application should utilize the\nvacmViewSpinLock to try to avoid collisions. See\nDESCRIPTION clause of vacmViewSpinLock.\n\nWhen creating MIB views, it is strongly advised that\nfirst the 'excluded' vacmViewTreeFamilyEntries are\ncreated and then the 'included' entries.\n\nWhen deleting MIB views, it is strongly advised that\nfirst the 'included' vacmViewTreeFamilyEntries are\n\ndeleted and then the 'excluded' entries.\n\nIf a create for an entry for instance-level access\ncontrol is received and the implementation does not\nsupport instance-level granularity, then an\ninconsistentName error must be returned.") vacmViewTreeFamilyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1)).setIndexNames((0, "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyViewName"), (0, "SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilySubtree")) if mibBuilder.loadTexts: vacmViewTreeFamilyEntry.setDescription("Information on a particular family of view subtrees\nincluded in or excluded from a particular SNMP\ncontext's MIB view.\n\nImplementations must not restrict the number of\nfamilies of view subtrees for a given MIB view,\nexcept as dictated by resource constraints on the\noverall number of entries in the\nvacmViewTreeFamilyTable.\n\nIf no conceptual rows exist in this table for a given\nMIB view (viewName), that view may be thought of as\nconsisting of the empty set of view subtrees.") vacmViewTreeFamilyViewName = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmViewTreeFamilyViewName.setDescription("The human readable name for a family of view subtrees.") vacmViewTreeFamilySubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 2), ObjectIdentifier()).setMaxAccess("noaccess") if mibBuilder.loadTexts: vacmViewTreeFamilySubtree.setDescription("The MIB subtree which when combined with the\ncorresponding instance of vacmViewTreeFamilyMask\ndefines a family of view subtrees.") vacmViewTreeFamilyMask = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmViewTreeFamilyMask.setDescription("The bit mask which, in combination with the\ncorresponding instance of vacmViewTreeFamilySubtree,\ndefines a family of view subtrees.\n\nEach bit of this bit mask corresponds to a\nsub-identifier of vacmViewTreeFamilySubtree, with the\nmost significant bit of the i-th octet of this octet\nstring value (extended if necessary, see below)\ncorresponding to the (8*i - 7)-th sub-identifier, and\nthe least significant bit of the i-th octet of this\noctet string corresponding to the (8*i)-th\nsub-identifier, where i is in the range 1 through 16.\n\nEach bit of this bit mask specifies whether or not\nthe corresponding sub-identifiers must match when\ndetermining if an OBJECT IDENTIFIER is in this\nfamily of view subtrees; a '1' indicates that an\nexact match must occur; a '0' indicates 'wild card',\ni.e., any sub-identifier value matches.\n\nThus, the OBJECT IDENTIFIER X of an object instance\nis contained in a family of view subtrees if, for\neach sub-identifier of the value of\nvacmViewTreeFamilySubtree, either:\n\n the i-th bit of vacmViewTreeFamilyMask is 0, or\n\n the i-th sub-identifier of X is equal to the i-th\n sub-identifier of the value of\n vacmViewTreeFamilySubtree.\n\nIf the value of this bit mask is M bits long and\n\nthere are more than M sub-identifiers in the\ncorresponding instance of vacmViewTreeFamilySubtree,\nthen the bit mask is extended with 1's to be the\nrequired length.\n\nNote that when the value of this object is the\nzero-length string, this extension rule results in\na mask of all-1's being used (i.e., no 'wild card'),\nand the family of view subtrees is the one view\nsubtree uniquely identified by the corresponding\ninstance of vacmViewTreeFamilySubtree.\n\nNote that masks of length greater than zero length\ndo not need to be supported. In this case this\nobject is made read-only.") vacmViewTreeFamilyType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 4), Integer().subtype(subtypeSpec=SingleValueConstraint(1,2,)).subtype(namedValues=NamedValues(("included", 1), ("excluded", 2), )).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmViewTreeFamilyType.setDescription("Indicates whether the corresponding instances of\nvacmViewTreeFamilySubtree and vacmViewTreeFamilyMask\ndefine a family of view subtrees which is included in\nor excluded from the MIB view.") vacmViewTreeFamilyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 5), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmViewTreeFamilyStorageType.setDescription("The storage type for this conceptual row.\n\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") vacmViewTreeFamilyStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 16, 1, 5, 2, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: vacmViewTreeFamilyStatus.setDescription("The status of this conceptual row.\n\nThe RowStatus TC [RFC2579] requires that this\nDESCRIPTION clause states under which circumstances\nother objects in this row can be modified:\n\nThe value of this object has no effect on whether\nother objects in this conceptual row can be modified.") vacmMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2)) vacmMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 1)) vacmMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 16, 2, 2)) # Augmentions # Groups vacmBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 16, 2, 2, 1)).setObjects(*(("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessContextMatch"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessReadViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmGroupName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmContextName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessWriteViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessNotifyViewName"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmAccessStatus"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmSecurityToGroupStorageType"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewTreeFamilyMask"), ("SNMP-VIEW-BASED-ACM-MIB", "vacmViewSpinLock"), ) ) if mibBuilder.loadTexts: vacmBasicGroup.setDescription("A collection of objects providing for remote\nconfiguration of an SNMP engine which implements\n\nthe SNMP View-based Access Control Model.") # Compliances vacmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 16, 2, 1, 1)).setObjects(*(("SNMP-VIEW-BASED-ACM-MIB", "vacmBasicGroup"), ) ) if mibBuilder.loadTexts: vacmMIBCompliance.setDescription("The compliance statement for SNMP engines which\nimplement the SNMP View-based Access Control Model\nconfiguration MIB.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", PYSNMP_MODULE_ID=snmpVacmMIB) # Objects mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", snmpVacmMIB=snmpVacmMIB, vacmMIBObjects=vacmMIBObjects, vacmContextTable=vacmContextTable, vacmContextEntry=vacmContextEntry, vacmContextName=vacmContextName, vacmSecurityToGroupTable=vacmSecurityToGroupTable, vacmSecurityToGroupEntry=vacmSecurityToGroupEntry, vacmSecurityModel=vacmSecurityModel, vacmSecurityName=vacmSecurityName, vacmGroupName=vacmGroupName, vacmSecurityToGroupStorageType=vacmSecurityToGroupStorageType, vacmSecurityToGroupStatus=vacmSecurityToGroupStatus, vacmAccessTable=vacmAccessTable, vacmAccessEntry=vacmAccessEntry, vacmAccessContextPrefix=vacmAccessContextPrefix, vacmAccessSecurityModel=vacmAccessSecurityModel, vacmAccessSecurityLevel=vacmAccessSecurityLevel, vacmAccessContextMatch=vacmAccessContextMatch, vacmAccessReadViewName=vacmAccessReadViewName, vacmAccessWriteViewName=vacmAccessWriteViewName, vacmAccessNotifyViewName=vacmAccessNotifyViewName, vacmAccessStorageType=vacmAccessStorageType, vacmAccessStatus=vacmAccessStatus, vacmMIBViews=vacmMIBViews, vacmViewSpinLock=vacmViewSpinLock, vacmViewTreeFamilyTable=vacmViewTreeFamilyTable, vacmViewTreeFamilyEntry=vacmViewTreeFamilyEntry, vacmViewTreeFamilyViewName=vacmViewTreeFamilyViewName, vacmViewTreeFamilySubtree=vacmViewTreeFamilySubtree, vacmViewTreeFamilyMask=vacmViewTreeFamilyMask, vacmViewTreeFamilyType=vacmViewTreeFamilyType, vacmViewTreeFamilyStorageType=vacmViewTreeFamilyStorageType, vacmViewTreeFamilyStatus=vacmViewTreeFamilyStatus, vacmMIBConformance=vacmMIBConformance, vacmMIBCompliances=vacmMIBCompliances, vacmMIBGroups=vacmMIBGroups) # Groups mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmBasicGroup=vacmBasicGroup) # Compliances mibBuilder.exportSymbols("SNMP-VIEW-BASED-ACM-MIB", vacmMIBCompliance=vacmMIBCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/SNMPv2-SMI.py0000644000076400001440000012547012220075303020271 0ustar ilyausers00000000000000import 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.error import PyAsn1Error ( Integer, ObjectIdentifier ) = mibBuilder.importSymbols( "ASN1", "Integer", "ObjectIdentifier" ) ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols( "ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint" ) # syntax of objects OctetString = rfc1902.OctetString Bits = rfc1902.Bits Integer32 = rfc1902.Integer32 IpAddress = rfc1902.IpAddress Counter32 = rfc1902.Counter32 Gauge32 = rfc1902.Gauge32 Unsigned32 = rfc1902.Unsigned32 TimeTicks = rfc1902.TimeTicks Opaque = rfc1902.Opaque Counter64 = rfc1902.Counter64 class ExtUTCTime(OctetString): subtypeSpec = OctetString.subtypeSpec+ConstraintsUnion(ValueSizeConstraint(11,11), ValueSizeConstraint(13,13)) # MIB tree foundation class class MibNode: label = '' def __init__(self, name): self.name = name def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.name) def getName(self): return self.name def getLabel(self): return self.label def setLabel(self, label): self.label = label return self def clone(self, name=None): myClone = self.__class__(self.name) if name is not None: myClone.name = name if self.label is not None: myClone.label = self.label return myClone # definitions for information modules class ModuleIdentity(MibNode): def getLastUpdated(self): return getattr(self, 'lastUpdated', '') def setLastUpdated(self, v): self.lastUpdated = v return self def getOrganization(self): return getattr(self, 'organization', '') def setOrganization(self, v): self.organization = v return self def getContactInfo(self): return getattr(self, 'contactInfo', '') def setContactInfo(self, v): self.contactInfo = v return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def getRevisions(self): return getattr(self, 'revisions', ()) def setRevisions(self, args): self.revisions = args return self def asn1Print(self): return '\ MODULE-IDENTITY\n\ LAST-UPDATED %s\n\ ORGANIZATION \"%s\"\n\ CONTACT-INFO \"%s\"\n\ DESCRIPTION \"%s\"\n\ %s\ ' % (self.getLastUpdated(), self.getOrganization(), self.getContactInfo(), self.getDescription(), ''.join([ "REVISION \"%s\"\n" % x for x in self.getRevisions() ])) class ObjectIdentity(MibNode): def getStatus(self): return getattr(self, 'status', 'current') def setStatus(self, v): self.status = v return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def getReference(self): return getattr(self, 'reference', '') def setReference(self, v): self.reference = v return self def asn1Print(self): return '\ OBJECT-IDENTITY\n\ STATUS %s\n\ DESCRIPTION \"%s\"\n\ REFERENCE \"%s\"\ ' % (self.getStatus(), self.getDescription(), self.getReference()) # definition for objects class NotificationType(MibNode): def getObjects(self): return getattr(self, 'objects', ()) def setObjects(self, *args): self.objects = args return self def getStatus(self): return getattr(self, 'status', 'current') def setStatus(self, v): self.status = v return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def getRevisions(self): return getattr(self, 'revisions', ()) def setRevisions(self, args): self.revisions = args return self def asn1Print(self): return '\ NOTIFICATION-TYPE\n\ OBJECTS { %s }\n\ STATUS %s\n\ DESCRIPTION \"%s\"\n\ %s\ ' % (', '.join([ x for x in self.getObjects() ]), self.getStatus(), self.getDescription(), ''.join([ "REVISION \"%s\"\n" % x for x in self.getRevisions() ])) class MibIdentifier(MibNode): def asn1Print(self): return 'OBJECT IDENTIFIER' class ObjectType(MibNode): maxAccess = None def __init__(self, name, syntax=None): MibNode.__init__(self, name) self.syntax = syntax # XXX def __eq__(self, other): return self.syntax == other def __ne__(self, other): return self.syntax != other def __lt__(self, other): return self.syntax < other def __le__(self, other): return self.syntax <= other def __gt__(self, other): return self.syntax > other def __ge__(self, other): return self.syntax >= other def __repr__(self): return '%s(%r, %r)' % ( self.__class__.__name__, self.name, self.syntax ) def getSyntax(self): return self.syntax def getUnits(self): return getattr(self, 'units', '') def setUnits(self, v): self.units = v return self def getMaxAccess(self): return getattr(self, 'maxAccess', 'not-accessible') def setMaxAccess(self, v): self.maxAccess = v return self def getStatus(self): return getattr(self, 'status', 'current') def setStatus(self, v): self.status = v return self def getDescription(self): return getattr(self, 'description', '') def setDescription(self, v): self.description = v return self def getReference(self): return getattr(self, 'reference', '') def setReference(self, v): self.reference = v return self def asn1Print(self): return '\ OBJECT-TYPE\n\ SYNTAX %s\n\ UNITS \"%s\"\n\ MAX-ACCESS %s\n\ STATUS %s\n\ DESCRIPTION \"%s\"\n\ REFERENCE \"%s\"\ ' % (self.getSyntax().__class__.__name__, self.getUnits(), self.getMaxAccess(), self.getStatus(), self.getDescription(), self.getReference()) class MibTree(ObjectType): branchVersionId = 0 # 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] 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 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 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 dublicate 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 # 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): 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 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 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 def writeUndo(self, name, val, idx, acInfo): # Revive previous value self.syntax = self.__oldSyntax self.__newSyntax = self.__oldSyntax = None # Table column instance specifics # Create operation def createTest(self, name, val, idx, acInfo): if name == self.name: 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 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 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): 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): 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): if not value: raise error.SmiError('Short OID for index %r' % (obj,)) value = tuple(value) # possible ObjectIdentifiers baseTag = obj.getTagSet().getBaseTag() if baseTag == self.__intBaseTag: return obj.clone(value[0]), value[1:] elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()): return obj.clone('.'.join([str(x) for x in value[:4]])), value[4:] elif baseTag == self.__strBaseTag: # rfc1902, 7.7 if impliedFlag: return obj.clone(value), () elif obj.isFixedLength(): l = obj.getFixedLength() return obj.clone(value[:l]), value[l:] else: return obj.clone(value[1:value[0]+1]), value[value[0]+1:] elif baseTag == self.__oidBaseTag: if impliedFlag: return obj.clone(value), () else: return obj.clone(value[1:value[0]+1]), value[value[0]+1:] # rfc2578, 7.1 elif baseTag == self.__bitsBaseTag: return obj.clone(value[1:value[0]+1]), value[value[0]+1:] else: raise error.SmiError('Unknown value type for index %r' % (obj,)) def getAsName(self, obj, impliedFlag=None): baseTag = obj.getTagSet().getBaseTag() if baseTag == self.__intBaseTag: return (int(obj),) elif self.__ipaddrTagSet.isSuperTagSetOf(obj.getTagSet()): return obj.asNumbers() elif baseTag == self.__strBaseTag: if impliedFlag or obj.isFixedLength(): initial = () else: initial = (len(obj),) return initial + obj.asNumbers() elif baseTag == self.__oidBaseTag: if impliedFlag: return tuple(obj) else: return (len(self.name),) + tuple(obj) # rfc2578, 7.1 elif baseTag == self.__bitsBaseTag: return ( len(obj), ) + obj.asNumbers() else: raise error.SmiError('Unknown value type for index %r' % (obj,)) # Fate sharing mechanics def announceManagementEvent(self, action, name, val, idx, acInfo): # Convert OID suffix into index vals instId = name[len(self.name)+1:] baseIndices = [] for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) syntax, instId = self.setFromName( mibObj.syntax, instId, impliedFlag ) if self.name == mibObj.name[:-1]: baseIndices.append((mibObj.name, syntax)) if instId: raise error.SmiError( 'Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId) ) if not baseIndices: return for modName, mibSym in self.augmentingRows.keys(): mibObj, = mibBuilder.importSymbols(modName, mibSym) debug.logger & debug.flagIns and debug.logger('announceManagementEvent %s to %s' % (action, mibObj)) mibObj.receiveManagementEvent( action, baseIndices, val, idx, 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) for name, syntax in baseIndices: if name == mibObj.name: newSuffix = newSuffix + self.getAsName(syntax, impliedFlag) if newSuffix: debug.logger & debug.flagIns and debug.logger('receiveManagementEvent %s for suffix %s' % (action, newSuffix)) self.__manageColumns(action, (), newSuffix, val, idx, 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 = 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 for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) syntax, instId = self.setFromName( mibObj.syntax, instId, impliedFlag ) indexVals[mibObj.name] = syntax for name, var in self._vars.items(): if name == excludeName: continue if name in indexVals: getattr(var, action)(name + nameSuffix, indexVals[name], idx, (None, None)) else: getattr(var, action)(name + nameSuffix, val, idx, 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. 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 ) 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 ) def writeTest(self, name, val, idx, acInfo): self.__delegate('Test', name, val, idx, acInfo) def writeCommit(self, name, val, idx, acInfo): self.__delegate('Commit', name, val, idx, acInfo) def writeCleanup(self, name, val, idx, acInfo): self.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) syntax, instId = self.setFromName(mibObj.syntax, instId, impliedFlag) indices.append(syntax) # to avoid cyclic refs if instId: raise error.SmiError( 'Excessive instance identifier sub-OIDs left at %s: %s' % (self, instId) ) indices = tuple(indices) self.__idToIdxCache[instId] = indices return indices def getInstIdFromIndices(self, *indices): """Return column instance identification from indices""" if indices in self.__idxToIdCache: return self.__idxToIdCache[indices] idx = 0; idxLen = len(indices); instId = () for impliedFlag, modName, symName in self.indexNames: mibObj, = mibBuilder.importSymbols(modName, symName) if idx < idxLen: instId = instId + self.getAsName( mibObj.syntax.clone(indices[idx]), impliedFlag ) else: break idx = idx + 1 self.__idxToIdCache[indices] = instId return instId # Table access by index def getInstNameByIndex(self, colId, *indices): """Build column instance name from components""" return self.name + (colId,) + self.getInstIdFromIndices(*indices) def getInstNamesByIndex(self, *indices): """Build column instance names from indices""" instNames = [] for columnName in self._vars.keys(): instNames.append( self.getInstNameByIndex(*(columnName[-1],) + indices) ) return tuple(instNames) class MibTable(MibTree): """MIB table. Manages a set of TableRow's""" def __init__(self, name): MibTree.__init__(self, name) zeroDotZero = ObjectIdentity((0,0)) #dot = MibTree() iso = MibTree((1,)) org = MibIdentifier(iso.name + (3,)) dod = MibIdentifier(org.name + (6,)) internet = MibIdentifier(dod.name + (1,)) directory = MibIdentifier(internet.name + (1,)) mgmt = MibIdentifier(internet.name + (2,)) mib_2 = MibIdentifier(mgmt.name + (1,)).setLabel('mib-2') transmission = MibIdentifier(mib_2.name + (10,)) experimental = MibIdentifier(internet.name + (3,)) private = MibIdentifier(internet.name + (4,)) enterprises = MibIdentifier(private.name + (1,)) security = MibIdentifier(internet.name + (5,)) snmpV2 = MibIdentifier(internet.name + (6,)) snmpDomains = MibIdentifier(snmpV2.name + (1,)) snmpProxys = MibIdentifier(snmpV2.name +(2,)) snmpModules = MibIdentifier(snmpV2.name +(3,)) mibBuilder.exportSymbols( 'SNMPv2-SMI', MibNode=MibNode, Integer32=Integer32, Bits=Bits, IpAddress=IpAddress, Counter32=Counter32, Gauge32=Gauge32, Unsigned32=Unsigned32, TimeTicks=TimeTicks, Opaque=Opaque, Counter64=Counter64, ExtUTCTime=ExtUTCTime, ModuleIdentity=ModuleIdentity, ObjectIdentity=ObjectIdentity, NotificationType=NotificationType, MibScalar=MibScalar, MibScalarInstance=MibScalarInstance, MibIdentifier=MibIdentifier, MibTree=MibTree, MibTableColumn=MibTableColumn, MibTableRow=MibTableRow, MibTable=MibTable, zeroDotZero=zeroDotZero, iso=iso, org=org, dod=dod, internet=internet, directory=directory, mgmt=mgmt, mib_2=mib_2, transmission=transmission, experimental=experimental, private=private, enterprises=enterprises, security=security, snmpV2=snmpV2, snmpDomains=snmpDomains, snmpProxys=snmpProxys, snmpModules=snmpModules ) # XXX # getAsName/setFromName goes out of MibRow? # revisit getNextNode() -- needs optimization pysnmp-4.2.5/pysnmp/smi/mibs/TRANSPORT-ADDRESS-MIB.py0000644000076400001440000003607112220306634021704 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python TRANSPORT-ADDRESS-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:58:37 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) from pyasn1.compat.octets import int2oct, oct2int from pysnmp import error import socket has_ipv6 = socket.has_ipv6 and hasattr(socket, 'AF_INET6') 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 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", 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 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]) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( Bits, Integer32, ModuleIdentity, MibIdentifier, ObjectIdentity, TimeTicks, mib_2, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "ObjectIdentity", "TimeTicks", "mib-2") ( TextualConvention, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention") # Types class TransportAddress(OctetString): subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) class TransportAddressDns(TextualConvention, OctetString): displayHint = "1a" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1,255) class TransportAddressIPv4(TextualConvention, OctetString): displayHint = "1d.1d.1d.1d:2d" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(6,6) fixedLength = 6 def prettyIn(self, value): if isinstance(value, tuple): # Wild hack -- need to implement TextualConvention.prettyIn value = 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 __getitem__(self, i): 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[i] class TransportAddressIPv4z(TextualConvention, OctetString): displayHint = "1d.1d.1d.1d%4d:2d" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(10,10) fixedLength = 10 class TransportAddressIPv6(TextualConvention, OctetString): displayHint = "0a[2x:2x:2x:2x:2x:2x:2x:2x]0a:2d" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(18,18) fixedLength = 18 def prettyIn(self, value): if 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 __getitem__(self, i): 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[i] class TransportAddressIPv6z(TextualConvention, OctetString): displayHint = "0a[2x:2x:2x:2x:2x:2x:2x:2x%4d]0a:2d" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(22,22) fixedLength = 22 class TransportAddressLocal(TextualConvention, OctetString): displayHint = "1a" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(1,255) class TransportAddressType(Integer): subtypeSpec = Integer.subtypeSpec+SingleValueConstraint(12,9,14,2,7,8,0,11,1,15,16,3,4,10,6,5,13,) namedValues = NamedValues(("unknown", 0), ("udpIpv4", 1), ("sctpIpv6", 10), ("sctpIpv4z", 11), ("sctpIpv6z", 12), ("local", 13), ("udpDns", 14), ("tcpDns", 15), ("sctpDns", 16), ("udpIpv6", 2), ("udpIpv4z", 3), ("udpIpv6z", 4), ("tcpIpv4", 5), ("tcpIpv6", 6), ("tcpIpv4z", 7), ("tcpIpv6z", 8), ("sctpIpv4", 9), ) class TransportDomain(ObjectIdentifier): pass # Objects transportAddressMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 100)).setRevisions(("2002-11-01 00:00",)) if mibBuilder.loadTexts: transportAddressMIB.setOrganization("IETF Operations and Management Area") if mibBuilder.loadTexts: transportAddressMIB.setContactInfo("Juergen Schoenwaelder (Editor)\nTU Braunschweig\nBueltenweg 74/75\n38106 Braunschweig, Germany\n\nPhone: +49 531 391-3289\nEMail: schoenw@ibr.cs.tu-bs.de\n\nSend comments to .") if mibBuilder.loadTexts: transportAddressMIB.setDescription("This MIB module provides commonly used transport\naddress definitions.\n\nCopyright (C) The Internet Society (2002). This version of\nthis MIB module is part of RFC 3419; see the RFC itself for\nfull legal notices.") transportDomains = MibIdentifier((1, 3, 6, 1, 2, 1, 100, 1)) transportDomainUdpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 1)) if mibBuilder.loadTexts: transportDomainUdpIpv4.setDescription("The UDP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4 for\nglobal IPv4 addresses.") transportDomainUdpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 2)) if mibBuilder.loadTexts: transportDomainUdpIpv6.setDescription("The UDP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6 for\nglobal IPv6 addresses.") transportDomainUdpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 3)) if mibBuilder.loadTexts: transportDomainUdpIpv4z.setDescription("The UDP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4z for\nscoped IPv4 addresses with a zone index.") transportDomainUdpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 4)) if mibBuilder.loadTexts: transportDomainUdpIpv6z.setDescription("The UDP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6z for\nscoped IPv6 addresses with a zone index.") transportDomainTcpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 5)) if mibBuilder.loadTexts: transportDomainTcpIpv4.setDescription("The TCP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4 for\nglobal IPv4 addresses.") transportDomainTcpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 6)) if mibBuilder.loadTexts: transportDomainTcpIpv6.setDescription("The TCP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6 for\nglobal IPv6 addresses.") transportDomainTcpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 7)) if mibBuilder.loadTexts: transportDomainTcpIpv4z.setDescription("The TCP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4z for\nscoped IPv4 addresses with a zone index.") transportDomainTcpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 8)) if mibBuilder.loadTexts: transportDomainTcpIpv6z.setDescription("The TCP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6z for\nscoped IPv6 addresses with a zone index.") transportDomainSctpIpv4 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 9)) if mibBuilder.loadTexts: transportDomainSctpIpv4.setDescription("The SCTP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4 for\nglobal IPv4 addresses. This transport domain usually\nrepresents the primary address on multihomed SCTP\nendpoints.") transportDomainSctpIpv6 = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 10)) if mibBuilder.loadTexts: transportDomainSctpIpv6.setDescription("The SCTP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6 for\nglobal IPv6 addresses. This transport domain usually\nrepresents the primary address on multihomed SCTP\nendpoints.") transportDomainSctpIpv4z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 11)) if mibBuilder.loadTexts: transportDomainSctpIpv4z.setDescription("The SCTP over IPv4 transport domain. The corresponding\ntransport address is of type TransportAddressIPv4z for\nscoped IPv4 addresses with a zone index. This transport\ndomain usually represents the primary address on\nmultihomed SCTP endpoints.") transportDomainSctpIpv6z = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 12)) if mibBuilder.loadTexts: transportDomainSctpIpv6z.setDescription("The SCTP over IPv6 transport domain. The corresponding\ntransport address is of type TransportAddressIPv6z for\nscoped IPv6 addresses with a zone index. This transport\ndomain usually represents the primary address on\nmultihomed SCTP endpoints.") transportDomainLocal = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 13)) if mibBuilder.loadTexts: transportDomainLocal.setDescription("The Posix Local IPC transport domain. The corresponding\ntransport address is of type TransportAddressLocal.\n\nThe Posix Local IPC transport domain incorporates the\nwell-known UNIX domain sockets.") transportDomainUdpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 14)) if mibBuilder.loadTexts: transportDomainUdpDns.setDescription("The UDP transport domain using fully qualified domain\nnames. The corresponding transport address is of type\nTransportAddressDns.") transportDomainTcpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 15)) if mibBuilder.loadTexts: transportDomainTcpDns.setDescription("The TCP transport domain using fully qualified domain\nnames. The corresponding transport address is of type\nTransportAddressDns.") transportDomainSctpDns = ObjectIdentity((1, 3, 6, 1, 2, 1, 100, 1, 16)) if mibBuilder.loadTexts: transportDomainSctpDns.setDescription("The SCTP transport domain using fully qualified domain\nnames. The corresponding transport address is of type\nTransportAddressDns.") # Augmentions # Exports # Module identity mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", PYSNMP_MODULE_ID=transportAddressMIB) # Types mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", TransportAddress=TransportAddress, TransportAddressDns=TransportAddressDns, TransportAddressIPv4=TransportAddressIPv4, TransportAddressIPv4z=TransportAddressIPv4z, TransportAddressIPv6=TransportAddressIPv6, TransportAddressIPv6z=TransportAddressIPv6z, TransportAddressLocal=TransportAddressLocal, TransportAddressType=TransportAddressType, TransportDomain=TransportDomain) # Objects mibBuilder.exportSymbols("TRANSPORT-ADDRESS-MIB", transportAddressMIB=transportAddressMIB, transportDomains=transportDomains, transportDomainUdpIpv4=transportDomainUdpIpv4, transportDomainUdpIpv6=transportDomainUdpIpv6, transportDomainUdpIpv4z=transportDomainUdpIpv4z, transportDomainUdpIpv6z=transportDomainUdpIpv6z, transportDomainTcpIpv4=transportDomainTcpIpv4, transportDomainTcpIpv6=transportDomainTcpIpv6, transportDomainTcpIpv4z=transportDomainTcpIpv4z, transportDomainTcpIpv6z=transportDomainTcpIpv6z, transportDomainSctpIpv4=transportDomainSctpIpv4, transportDomainSctpIpv6=transportDomainSctpIpv6, transportDomainSctpIpv4z=transportDomainSctpIpv4z, transportDomainSctpIpv6z=transportDomainSctpIpv6z, transportDomainLocal=transportDomainLocal, transportDomainUdpDns=transportDomainUdpDns, transportDomainTcpDns=transportDomainTcpDns, transportDomainSctpDns=transportDomainSctpDns) pysnmp-4.2.5/pysnmp/smi/mibs/ASN1-ENUMERATION.py0000644000076400001440000000023711667155417021120 0ustar ilyausers00000000000000# ASN.1 types enumeration tools from pyasn1.type import namedval mibBuilder.exportSymbols( 'ASN1-ENUMERATION', NamedValues=namedval.NamedValues ) pysnmp-4.2.5/pysnmp/smi/mibs/SNMPv2-MIB.py0000644000076400001440000007015411736571521020264 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMPv2-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:55:45 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( ModuleCompliance, NotificationGroup, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ( Bits, Counter32, Integer32, ModuleIdentity, MibIdentifier, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, TimeTicks, mib_2, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "ModuleIdentity", "MibIdentifier", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "TimeTicks", "mib-2", "snmpModules") ( DisplayString, TestAndIncr, TimeStamp, ) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TestAndIncr", "TimeStamp") # Objects system = MibIdentifier((1, 3, 6, 1, 2, 1, 1)) sysDescr = MibScalar((1, 3, 6, 1, 2, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDescr.setDescription("A textual description of the entity. This value should\ninclude the full name and version identification of\nthe system's hardware type, software operating-system,\nand networking software.") sysObjectID = MibScalar((1, 3, 6, 1, 2, 1, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysObjectID.setDescription("The vendor's authoritative identification of the\nnetwork management subsystem contained in the entity.\nThis value is allocated within the SMI enterprises\nsubtree (1.3.6.1.4.1) and provides an easy and\nunambiguous means for determining `what kind of box' is\nbeing managed. For example, if vendor `Flintstones,\nInc.' was assigned the subtree 1.3.6.1.4.1.424242,\nit could assign the identifier 1.3.6.1.4.1.424242.1.1\nto its `Fred Router'.") sysUpTime = MibScalar((1, 3, 6, 1, 2, 1, 1, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysUpTime.setDescription("The time (in hundredths of a second) since the\nnetwork management portion of the system was last\nre-initialized.") sysContact = MibScalar((1, 3, 6, 1, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysContact.setDescription("The textual identification of the contact person for\nthis managed node, together with information on how\nto contact this person. If no contact information is\nknown, the value is the zero-length string.") sysName = MibScalar((1, 3, 6, 1, 2, 1, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysName.setDescription("An administratively-assigned name for this managed\nnode. By convention, this is the node's fully-qualified\ndomain name. If the name is unknown, the value is\nthe zero-length string.") sysLocation = MibScalar((1, 3, 6, 1, 2, 1, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sysLocation.setDescription("The physical location of this node (e.g., 'telephone\ncloset, 3rd floor'). If the location is unknown, the\nvalue is the zero-length string.") sysServices = MibScalar((1, 3, 6, 1, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 127))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysServices.setDescription("A value which indicates the set of services that this\nentity may potentially offer. The value is a sum.\n\nThis sum initially takes the value zero. Then, for\neach layer, L, in the range 1 through 7, that this node\nperforms transactions for, 2 raised to (L - 1) is added\nto the sum. For example, a node which performs only\nrouting functions would have a value of 4 (2^(3-1)).\nIn contrast, a node which is a host offering application\nservices would have a value of 72 (2^(4-1) + 2^(7-1)).\nNote that in the context of the Internet suite of\nprotocols, values should be calculated accordingly:\n\n layer functionality\n 1 physical (e.g., repeaters)\n 2 datalink/subnetwork (e.g., bridges)\n 3 internet (e.g., supports the IP)\n 4 end-to-end (e.g., supports the TCP)\n 7 applications (e.g., supports the SMTP)\n\nFor systems including OSI protocols, layers 5 and 6\nmay also be counted.") sysORLastChange = MibScalar((1, 3, 6, 1, 2, 1, 1, 8), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORLastChange.setDescription("The value of sysUpTime at the time of the most recent\nchange in state or value of any instance of sysORID.") sysORTable = MibTable((1, 3, 6, 1, 2, 1, 1, 9)) if mibBuilder.loadTexts: sysORTable.setDescription("The (conceptual) table listing the capabilities of\nthe local SNMP application acting as a command\nresponder with respect to various MIB modules.\nSNMP entities having dynamically-configurable support\nof MIB modules will have a dynamically-varying number\nof conceptual rows.") sysOREntry = MibTableRow((1, 3, 6, 1, 2, 1, 1, 9, 1)).setIndexNames((0, "SNMPv2-MIB", "sysORIndex")) if mibBuilder.loadTexts: sysOREntry.setDescription("An entry (conceptual row) in the sysORTable.") sysORIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("noaccess") if mibBuilder.loadTexts: sysORIndex.setDescription("The auxiliary variable used for identifying instances\nof the columnar objects in the sysORTable.") sysORID = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 2), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORID.setDescription("An authoritative identification of a capabilities\nstatement with respect to various MIB modules supported\nby the local SNMP application acting as a command\nresponder.") sysORDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORDescr.setDescription("A textual description of the capabilities identified\nby the corresponding instance of sysORID.") sysORUpTime = MibTableColumn((1, 3, 6, 1, 2, 1, 1, 9, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysORUpTime.setDescription("The value of sysUpTime at the time this conceptual\nrow was last instantiated.") snmp = MibIdentifier((1, 3, 6, 1, 2, 1, 11)) snmpInPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInPkts.setDescription("The total number of messages delivered to the SNMP\nentity from the transport service.") snmpOutPkts = MibScalar((1, 3, 6, 1, 2, 1, 11, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutPkts.setDescription("The total number of SNMP Messages which were\npassed from the SNMP protocol entity to the\ntransport service.") snmpInBadVersions = MibScalar((1, 3, 6, 1, 2, 1, 11, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadVersions.setDescription("The total number of SNMP messages which were delivered\nto the SNMP entity and were for an unsupported SNMP\nversion.") snmpInBadCommunityNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadCommunityNames.setDescription("The total number of community-based SNMP messages (for\nexample, SNMPv1) delivered to the SNMP entity which\nused an SNMP community name not known to said entity.\nAlso, implementations which authenticate community-based\nSNMP messages using check(s) in addition to matching\nthe community name (for example, by also checking\nwhether the message originated from a transport address\nallowed to use a specified community name) MAY include\nin this value the number of messages which failed the\nadditional check(s). It is strongly RECOMMENDED that\n\nthe documentation for any security model which is used\nto authenticate community-based SNMP messages specify\nthe precise conditions that contribute to this value.") snmpInBadCommunityUses = MibScalar((1, 3, 6, 1, 2, 1, 11, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadCommunityUses.setDescription("The total number of community-based SNMP messages (for\nexample, SNMPv1) delivered to the SNMP entity which\nrepresented an SNMP operation that was not allowed for\nthe SNMP community named in the message. The precise\nconditions under which this counter is incremented\n(if at all) depend on how the SNMP entity implements\nits access control mechanism and how its applications\ninteract with that access control mechanism. It is\nstrongly RECOMMENDED that the documentation for any\naccess control mechanism which is used to control access\nto and visibility of MIB instrumentation specify the\nprecise conditions that contribute to this value.") snmpInASNParseErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInASNParseErrs.setDescription("The total number of ASN.1 or BER errors encountered by\nthe SNMP entity when decoding received SNMP messages.") snmpInTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 8), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTooBigs.setDescription("The total number of SNMP PDUs which were\ndelivered to the SNMP protocol entity and for\nwhich the value of the error-status field was\n`tooBig'.") snmpInNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInNoSuchNames.setDescription("The total number of SNMP PDUs which were\ndelivered to the SNMP protocol entity and for\nwhich the value of the error-status field was\n`noSuchName'.") snmpInBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInBadValues.setDescription("The total number of SNMP PDUs which were\ndelivered to the SNMP protocol entity and for\nwhich the value of the error-status field was\n`badValue'.") snmpInReadOnlys = MibScalar((1, 3, 6, 1, 2, 1, 11, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInReadOnlys.setDescription("The total number valid SNMP PDUs which were delivered\nto the SNMP protocol entity and for which the value\nof the error-status field was `readOnly'. It should\nbe noted that it is a protocol error to generate an\nSNMP PDU which contains the value `readOnly' in the\nerror-status field, as such this object is provided\nas a means of detecting incorrect implementations of\nthe SNMP.") snmpInGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 12), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGenErrs.setDescription("The total number of SNMP PDUs which were delivered\nto the SNMP protocol entity and for which the value\nof the error-status field was `genErr'.") snmpInTotalReqVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 13), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTotalReqVars.setDescription("The total number of MIB objects which have been\nretrieved successfully by the SNMP protocol entity\nas the result of receiving valid SNMP Get-Request\nand Get-Next PDUs.") snmpInTotalSetVars = MibScalar((1, 3, 6, 1, 2, 1, 11, 14), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTotalSetVars.setDescription("The total number of MIB objects which have been\naltered successfully by the SNMP protocol entity as\nthe result of receiving valid SNMP Set-Request PDUs.") snmpInGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 15), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGetRequests.setDescription("The total number of SNMP Get-Request PDUs which\nhave been accepted and processed by the SNMP\nprotocol entity.") snmpInGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGetNexts.setDescription("The total number of SNMP Get-Next PDUs which have been\naccepted and processed by the SNMP protocol entity.") snmpInSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInSetRequests.setDescription("The total number of SNMP Set-Request PDUs which\nhave been accepted and processed by the SNMP protocol\nentity.") snmpInGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInGetResponses.setDescription("The total number of SNMP Get-Response PDUs which\nhave been accepted and processed by the SNMP protocol\nentity.") snmpInTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpInTraps.setDescription("The total number of SNMP Trap PDUs which have been\naccepted and processed by the SNMP protocol entity.") snmpOutTooBigs = MibScalar((1, 3, 6, 1, 2, 1, 11, 20), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutTooBigs.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status field was `tooBig.'") snmpOutNoSuchNames = MibScalar((1, 3, 6, 1, 2, 1, 11, 21), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutNoSuchNames.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status was `noSuchName'.") snmpOutBadValues = MibScalar((1, 3, 6, 1, 2, 1, 11, 22), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutBadValues.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status field was `badValue'.") snmpOutGenErrs = MibScalar((1, 3, 6, 1, 2, 1, 11, 24), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGenErrs.setDescription("The total number of SNMP PDUs which were generated\nby the SNMP protocol entity and for which the value\nof the error-status field was `genErr'.") snmpOutGetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 25), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGetRequests.setDescription("The total number of SNMP Get-Request PDUs which\nhave been generated by the SNMP protocol entity.") snmpOutGetNexts = MibScalar((1, 3, 6, 1, 2, 1, 11, 26), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGetNexts.setDescription("The total number of SNMP Get-Next PDUs which have\nbeen generated by the SNMP protocol entity.") snmpOutSetRequests = MibScalar((1, 3, 6, 1, 2, 1, 11, 27), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutSetRequests.setDescription("The total number of SNMP Set-Request PDUs which\nhave been generated by the SNMP protocol entity.") snmpOutGetResponses = MibScalar((1, 3, 6, 1, 2, 1, 11, 28), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutGetResponses.setDescription("The total number of SNMP Get-Response PDUs which\nhave been generated by the SNMP protocol entity.") snmpOutTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 29), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpOutTraps.setDescription("The total number of SNMP Trap PDUs which have\nbeen generated by the SNMP protocol entity.") snmpEnableAuthenTraps = MibScalar((1, 3, 6, 1, 2, 1, 11, 30), Integer().subtype(subtypeSpec=SingleValueConstraint(2,1,)).subtype(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ))).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpEnableAuthenTraps.setDescription("Indicates whether the SNMP entity is permitted to\ngenerate authenticationFailure traps. The value of this\nobject overrides any configuration information; as such,\nit provides a means whereby all authenticationFailure\ntraps may be disabled.\n\nNote that it is strongly recommended that this object\nbe stored in non-volatile memory so that it remains\nconstant across re-initializations of the network\nmanagement system.") snmpSilentDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 31), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpSilentDrops.setDescription("The total number of Confirmed Class PDUs (such as\nGetRequest-PDUs, GetNextRequest-PDUs,\nGetBulkRequest-PDUs, SetRequest-PDUs, and\nInformRequest-PDUs) delivered to the SNMP entity which\nwere silently dropped because the size of a reply\ncontaining an alternate Response Class PDU (such as a\nResponse-PDU) with an empty variable-bindings field\nwas greater than either a local constraint or the\nmaximum message size associated with the originator of\nthe request.") snmpProxyDrops = MibScalar((1, 3, 6, 1, 2, 1, 11, 32), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpProxyDrops.setDescription("The total number of Confirmed Class PDUs\n(such as GetRequest-PDUs, GetNextRequest-PDUs,\nGetBulkRequest-PDUs, SetRequest-PDUs, and\nInformRequest-PDUs) delivered to the SNMP entity which\nwere silently dropped because the transmission of\nthe (possibly translated) message to a proxy target\nfailed in a manner (other than a time-out) such that\nno Response Class PDU (such as a Response-PDU) could\nbe returned.") snmpMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 1)).setRevisions(("2002-10-16 00:00","1995-11-09 00:00","1993-04-01 00:00",)) if mibBuilder.loadTexts: snmpMIB.setOrganization("IETF SNMPv3 Working Group") if mibBuilder.loadTexts: snmpMIB.setContactInfo("WG-EMail: snmpv3@lists.tislabs.com\nSubscribe: snmpv3-request@lists.tislabs.com\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\npostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nEMail: mundy@tislabs.com\nphone: +1 301 947-7107\n\nCo-Chair: David Harrington\n Enterasys Networks\npostal: 35 Industrial Way\n P. O. Box 5005\n Rochester, NH 03866-5005\n USA\nEMail: dbh@enterasys.com\nphone: +1 603 337-2614\n\nEditor: Randy Presuhn\n BMC Software, Inc.\npostal: 2141 North First Street\n San Jose, CA 95131\n USA\nEMail: randy_presuhn@bmc.com\nphone: +1 408 546-1006") if mibBuilder.loadTexts: snmpMIB.setDescription("The MIB module for SNMP entities.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3418;\nsee the RFC itself for full legal notices.") snmpMIBObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1)) snmpTrap = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 4)) snmpTrapOID = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 1), ObjectIdentifier()).setMaxAccess("notifyonly") if mibBuilder.loadTexts: snmpTrapOID.setDescription("The authoritative identification of the notification\ncurrently being sent. This variable occurs as\nthe second varbind in every SNMPv2-Trap-PDU and\nInformRequest-PDU.") snmpTrapEnterprise = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 4, 3), ObjectIdentifier()).setMaxAccess("notifyonly") if mibBuilder.loadTexts: snmpTrapEnterprise.setDescription("The authoritative identification of the enterprise\nassociated with the trap currently being sent. When an\nSNMP proxy agent is mapping an RFC1157 Trap-PDU\ninto a SNMPv2-Trap-PDU, this variable occurs as the\nlast varbind.") snmpTraps = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5)) snmpSet = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 6)) snmpSetSerialNo = MibScalar((1, 3, 6, 1, 6, 3, 1, 1, 6, 1), TestAndIncr()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpSetSerialNo.setDescription("An advisory lock used to allow several cooperating\ncommand generator applications to coordinate their\nuse of the SNMP set operation.\n\nThis object is used for coarse-grain coordination.\nTo achieve fine-grain coordination, one or more similar\nobjects might be defined within each MIB group, as\nappropriate.") snmpMIBConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2)) snmpMIBCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 1)) snmpMIBGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 1, 2, 2)) # Augmentions # Notifications coldStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 1)).setObjects(*() ) if mibBuilder.loadTexts: coldStart.setDescription("A coldStart trap signifies that the SNMP entity,\nsupporting a notification originator application, is\nreinitializing itself and that its configuration may\nhave been altered.") warmStart = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 2)).setObjects(*() ) if mibBuilder.loadTexts: warmStart.setDescription("A warmStart trap signifies that the SNMP entity,\nsupporting a notification originator application,\nis reinitializing itself such that its configuration\nis unaltered.") authenticationFailure = NotificationType((1, 3, 6, 1, 6, 3, 1, 1, 5, 5)).setObjects(*() ) if mibBuilder.loadTexts: authenticationFailure.setDescription("An authenticationFailure trap signifies that the SNMP\nentity has received a protocol message that is not\nproperly authenticated. While all implementations\nof SNMP entities MAY be capable of generating this\ntrap, the snmpEnableAuthenTraps object indicates\nwhether this trap will be generated.") # Groups snmpSetGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 5)).setObjects(*(("SNMPv2-MIB", "snmpSetSerialNo"), ) ) if mibBuilder.loadTexts: snmpSetGroup.setDescription("A collection of objects which allow several cooperating\ncommand generator applications to coordinate their\nuse of the set operation.") systemGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 6)).setObjects(*(("SNMPv2-MIB", "sysName"), ("SNMPv2-MIB", "sysObjectID"), ("SNMPv2-MIB", "sysORID"), ("SNMPv2-MIB", "sysUpTime"), ("SNMPv2-MIB", "sysORDescr"), ("SNMPv2-MIB", "sysContact"), ("SNMPv2-MIB", "sysORLastChange"), ("SNMPv2-MIB", "sysLocation"), ("SNMPv2-MIB", "sysServices"), ("SNMPv2-MIB", "sysDescr"), ("SNMPv2-MIB", "sysORUpTime"), ) ) if mibBuilder.loadTexts: systemGroup.setDescription("The system group defines objects which are common to all\nmanaged systems.") snmpBasicNotificationsGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 7)).setObjects(*(("SNMPv2-MIB", "authenticationFailure"), ("SNMPv2-MIB", "coldStart"), ) ) if mibBuilder.loadTexts: snmpBasicNotificationsGroup.setDescription("The basic notifications implemented by an SNMP entity\nsupporting command responder applications.") snmpGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 8)).setObjects(*(("SNMPv2-MIB", "snmpEnableAuthenTraps"), ("SNMPv2-MIB", "snmpSilentDrops"), ("SNMPv2-MIB", "snmpInASNParseErrs"), ("SNMPv2-MIB", "snmpInPkts"), ("SNMPv2-MIB", "snmpInBadVersions"), ("SNMPv2-MIB", "snmpProxyDrops"), ) ) if mibBuilder.loadTexts: snmpGroup.setDescription("A collection of objects providing basic instrumentation\nand control of an SNMP entity.") snmpCommunityGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 9)).setObjects(*(("SNMPv2-MIB", "snmpInBadCommunityNames"), ("SNMPv2-MIB", "snmpInBadCommunityUses"), ) ) if mibBuilder.loadTexts: snmpCommunityGroup.setDescription("A collection of objects providing basic instrumentation\nof a SNMP entity which supports community-based\nauthentication.") snmpObsoleteGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 10)).setObjects(*(("SNMPv2-MIB", "snmpOutNoSuchNames"), ("SNMPv2-MIB", "snmpInReadOnlys"), ("SNMPv2-MIB", "snmpInTotalReqVars"), ("SNMPv2-MIB", "snmpInSetRequests"), ("SNMPv2-MIB", "snmpOutGenErrs"), ("SNMPv2-MIB", "snmpOutGetRequests"), ("SNMPv2-MIB", "snmpOutPkts"), ("SNMPv2-MIB", "snmpOutBadValues"), ("SNMPv2-MIB", "snmpOutTraps"), ("SNMPv2-MIB", "snmpInNoSuchNames"), ("SNMPv2-MIB", "snmpInGetNexts"), ("SNMPv2-MIB", "snmpInGetRequests"), ("SNMPv2-MIB", "snmpOutGetResponses"), ("SNMPv2-MIB", "snmpInGenErrs"), ("SNMPv2-MIB", "snmpInTraps"), ("SNMPv2-MIB", "snmpInTotalSetVars"), ("SNMPv2-MIB", "snmpInGetResponses"), ("SNMPv2-MIB", "snmpOutSetRequests"), ("SNMPv2-MIB", "snmpInBadValues"), ("SNMPv2-MIB", "snmpInTooBigs"), ("SNMPv2-MIB", "snmpOutGetNexts"), ("SNMPv2-MIB", "snmpOutTooBigs"), ) ) if mibBuilder.loadTexts: snmpObsoleteGroup.setDescription("A collection of objects from RFC 1213 made obsolete\nby this MIB module.") snmpWarmStartNotificationGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 11)).setObjects(*(("SNMPv2-MIB", "warmStart"), ) ) if mibBuilder.loadTexts: snmpWarmStartNotificationGroup.setDescription("An additional notification for an SNMP entity supporting\ncommand responder applications, if it is able to reinitialize\nitself such that its configuration is unaltered.") snmpNotificationGroup = NotificationGroup((1, 3, 6, 1, 6, 3, 1, 2, 2, 12)).setObjects(*(("SNMPv2-MIB", "snmpTrapOID"), ("SNMPv2-MIB", "snmpTrapEnterprise"), ) ) if mibBuilder.loadTexts: snmpNotificationGroup.setDescription("These objects are required for entities\nwhich support notification originator applications.") # Compliances snmpBasicCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 1, 2, 1, 2)).setObjects(*(("SNMPv2-MIB", "snmpGroup"), ("SNMPv2-MIB", "systemGroup"), ("SNMPv2-MIB", "snmpBasicNotificationsGroup"), ("SNMPv2-MIB", "snmpSetGroup"), ("SNMPv2-MIB", "snmpCommunityGroup"), ) ) if mibBuilder.loadTexts: snmpBasicCompliance.setDescription("The compliance statement for SNMPv2 entities which\nimplement the SNMPv2 MIB.\n\nThis compliance statement is replaced by\nsnmpBasicComplianceRev2.") snmpBasicComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 6, 3, 1, 2, 1, 3)).setObjects(*(("SNMPv2-MIB", "snmpGroup"), ("SNMPv2-MIB", "snmpWarmStartNotificationGroup"), ("SNMPv2-MIB", "snmpBasicNotificationsGroup"), ("SNMPv2-MIB", "snmpCommunityGroup"), ("SNMPv2-MIB", "systemGroup"), ("SNMPv2-MIB", "snmpSetGroup"), ) ) if mibBuilder.loadTexts: snmpBasicComplianceRev2.setDescription("The compliance statement for SNMP entities which\nimplement this MIB module.") # Exports # Module identity mibBuilder.exportSymbols("SNMPv2-MIB", PYSNMP_MODULE_ID=snmpMIB) # Objects mibBuilder.exportSymbols("SNMPv2-MIB", system=system, sysDescr=sysDescr, sysObjectID=sysObjectID, sysUpTime=sysUpTime, sysContact=sysContact, sysName=sysName, sysLocation=sysLocation, sysServices=sysServices, sysORLastChange=sysORLastChange, sysORTable=sysORTable, sysOREntry=sysOREntry, sysORIndex=sysORIndex, sysORID=sysORID, sysORDescr=sysORDescr, sysORUpTime=sysORUpTime, snmp=snmp, snmpInPkts=snmpInPkts, snmpOutPkts=snmpOutPkts, snmpInBadVersions=snmpInBadVersions, snmpInBadCommunityNames=snmpInBadCommunityNames, snmpInBadCommunityUses=snmpInBadCommunityUses, snmpInASNParseErrs=snmpInASNParseErrs, snmpInTooBigs=snmpInTooBigs, snmpInNoSuchNames=snmpInNoSuchNames, snmpInBadValues=snmpInBadValues, snmpInReadOnlys=snmpInReadOnlys, snmpInGenErrs=snmpInGenErrs, snmpInTotalReqVars=snmpInTotalReqVars, snmpInTotalSetVars=snmpInTotalSetVars, snmpInGetRequests=snmpInGetRequests, snmpInGetNexts=snmpInGetNexts, snmpInSetRequests=snmpInSetRequests, snmpInGetResponses=snmpInGetResponses, snmpInTraps=snmpInTraps, snmpOutTooBigs=snmpOutTooBigs, snmpOutNoSuchNames=snmpOutNoSuchNames, snmpOutBadValues=snmpOutBadValues, snmpOutGenErrs=snmpOutGenErrs, snmpOutGetRequests=snmpOutGetRequests, snmpOutGetNexts=snmpOutGetNexts, snmpOutSetRequests=snmpOutSetRequests, snmpOutGetResponses=snmpOutGetResponses, snmpOutTraps=snmpOutTraps, snmpEnableAuthenTraps=snmpEnableAuthenTraps, snmpSilentDrops=snmpSilentDrops, snmpProxyDrops=snmpProxyDrops, snmpMIB=snmpMIB, snmpMIBObjects=snmpMIBObjects, snmpTrap=snmpTrap, snmpTrapOID=snmpTrapOID, snmpTrapEnterprise=snmpTrapEnterprise, snmpTraps=snmpTraps, snmpSet=snmpSet, snmpSetSerialNo=snmpSetSerialNo, snmpMIBConformance=snmpMIBConformance, snmpMIBCompliances=snmpMIBCompliances, snmpMIBGroups=snmpMIBGroups) # Notifications mibBuilder.exportSymbols("SNMPv2-MIB", coldStart=coldStart, warmStart=warmStart, authenticationFailure=authenticationFailure) # Groups mibBuilder.exportSymbols("SNMPv2-MIB", snmpSetGroup=snmpSetGroup, systemGroup=systemGroup, snmpBasicNotificationsGroup=snmpBasicNotificationsGroup, snmpGroup=snmpGroup, snmpCommunityGroup=snmpCommunityGroup, snmpObsoleteGroup=snmpObsoleteGroup, snmpWarmStartNotificationGroup=snmpWarmStartNotificationGroup, snmpNotificationGroup=snmpNotificationGroup) # Compliances mibBuilder.exportSymbols("SNMPv2-MIB", snmpBasicCompliance=snmpBasicCompliance, snmpBasicComplianceRev2=snmpBasicComplianceRev2) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-TARGET-MIB.py0000644000076400001440000004544612206334611020774 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-TARGET-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 16:05:39 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) from pysnmp.smi import error # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( SnmpAdminString, SnmpMessageProcessingModel, SnmpSecurityLevel, SnmpSecurityModel, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString", "SnmpMessageProcessingModel", "SnmpSecurityLevel", "SnmpSecurityModel") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Counter32, Integer32, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Counter32", "Integer32", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( RowStatus, StorageType, TAddress, TDomain, TextualConvention, TestAndIncr, TimeInterval, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType", "TAddress", "TDomain", "TextualConvention", "TestAndIncr", "TimeInterval") # Types class SnmpTagList(TextualConvention, OctetString): displayHint = "255t" subtypeSpec = OctetString.subtypeSpec+ValueSizeConstraint(0,255) 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): 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) # Objects snmpTargetMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 12)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) if mibBuilder.loadTexts: snmpTargetMIB.setOrganization("IETF SNMPv3 Working Group") if mibBuilder.loadTexts: snmpTargetMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In message body: subscribe snmpv3\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\nPostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nEMail: mundy@tislabs.com\nPhone: +1 301-947-7107\n\nCo-Chair: David Harrington\n Enterasys Networks\nPostal: 35 Industrial Way\n P. O. Box 5004\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nPhone: +1 603-337-2614\n\nCo-editor: David B. Levi\n Nortel Networks\nPostal: 3505 Kesterwood Drive\n Knoxville, Tennessee 37918\nEMail: dlevi@nortelnetworks.com\nPhone: +1 865 686 0432\n\nCo-editor: Paul Meyer\n Secure Computing Corporation\nPostal: 2675 Long Lake Road\n\n Roseville, Minnesota 55113\nEMail: paul_meyer@securecomputing.com\nPhone: +1 651 628 1592\n\nCo-editor: Bob Stewart\n Retired") if mibBuilder.loadTexts: snmpTargetMIB.setDescription("This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters used\nby an SNMP entity for the generation of SNMP messages.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.") snmpTargetObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 1)) snmpTargetSpinLock = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 1), TestAndIncr()).setMaxAccess("readwrite") if mibBuilder.loadTexts: snmpTargetSpinLock.setDescription("This object is used to facilitate modification of table\nentries in the SNMP-TARGET-MIB module by multiple\nmanagers. In particular, it is useful when modifying\nthe value of the snmpTargetAddrTagList object.\n\nThe procedure for modifying the snmpTargetAddrTagList\nobject is as follows:\n\n 1. Retrieve the value of snmpTargetSpinLock and\n of snmpTargetAddrTagList.\n\n 2. Generate a new value for snmpTargetAddrTagList.\n\n 3. Set the value of snmpTargetSpinLock to the\n retrieved value, and the value of\n snmpTargetAddrTagList to the new value. If\n the set fails for the snmpTargetSpinLock\n object, go back to step 1.") snmpTargetAddrTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 2)) if mibBuilder.loadTexts: snmpTargetAddrTable.setDescription("A table of transport addresses to be used in the generation\nof SNMP messages.") snmpTargetAddrEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 2, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetAddrName")) if mibBuilder.loadTexts: snmpTargetAddrEntry.setDescription("A transport address to be used in the generation\nof SNMP operations.\n\nEntries in the snmpTargetAddrTable are created and\ndeleted using the snmpTargetAddrRowStatus object.") snmpTargetAddrName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: snmpTargetAddrName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpTargetAddrEntry.") snmpTargetAddrTDomain = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 2), TDomain()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTDomain.setDescription("This object indicates the transport type of the address\ncontained in the snmpTargetAddrTAddress object.") snmpTargetAddrTAddress = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 3), TAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTAddress.setDescription("This object contains a transport address. The format of\nthis address depends on the value of the\nsnmpTargetAddrTDomain object.") snmpTargetAddrTimeout = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 4), TimeInterval().clone('1500')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTimeout.setDescription("This object should reflect the expected maximum round\ntrip time for communicating with the transport address\ndefined by this row. When a message is sent to this\naddress, and a response (if one is expected) is not\nreceived within this time period, an implementation\nmay assume that the response will not be delivered.\n\nNote that the time interval that an application waits\nfor a response may actually be derived from the value\nof this object. The method for deriving the actual time\ninterval is implementation dependent. One such method\nis to derive the expected round trip time based on a\nparticular retransmission algorithm and on the number\nof timeouts which have occurred. The type of message may\nalso be considered when deriving expected round trip\ntimes for retransmissions. For example, if a message is\nbeing sent with a securityLevel that indicates both\n\nauthentication and privacy, the derived value may be\nincreased to compensate for extra processing time spent\nduring authentication and encryption processing.") snmpTargetAddrRetryCount = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(3)).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrRetryCount.setDescription("This object specifies a default number of retries to be\nattempted when a response is not received for a generated\nmessage. An application may provide its own retry count,\nin which case the value of this object is ignored.") snmpTargetAddrTagList = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 6), SnmpTagList().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrTagList.setDescription("This object contains a list of tag values which are\nused to select target addresses for a particular\noperation.") snmpTargetAddrParams = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrParams.setDescription("The value of this object identifies an entry in the\nsnmpTargetParamsTable. The identified entry\ncontains SNMP parameters to be used when generating\nmessages to be sent to this transport address.") snmpTargetAddrStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 8), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") snmpTargetAddrRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetAddrRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the snmpTargetAddrRowStatus\ncolumn is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until the corresponding instances of\nsnmpTargetAddrTDomain, snmpTargetAddrTAddress, and\nsnmpTargetAddrParams have all been set.\n\nThe following objects may not be modified while the\nvalue of this object is active(1):\n - snmpTargetAddrTDomain\n - snmpTargetAddrTAddress\nAn attempt to set these objects while the value of\nsnmpTargetAddrRowStatus is active(1) will result in\nan inconsistentValue error.") snmpTargetParamsTable = MibTable((1, 3, 6, 1, 6, 3, 12, 1, 3)) if mibBuilder.loadTexts: snmpTargetParamsTable.setDescription("A table of SNMP target information to be used\nin the generation of SNMP messages.") snmpTargetParamsEntry = MibTableRow((1, 3, 6, 1, 6, 3, 12, 1, 3, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetParamsName")) if mibBuilder.loadTexts: snmpTargetParamsEntry.setDescription("A set of SNMP target information.\n\nEntries in the snmpTargetParamsTable are created and\ndeleted using the snmpTargetParamsRowStatus object.") snmpTargetParamsName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: snmpTargetParamsName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpTargetParamsEntry.") snmpTargetParamsMPModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 2), SnmpMessageProcessingModel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsMPModel.setDescription("The Message Processing Model to be used when generating\nSNMP messages using this entry.") snmpTargetParamsSecurityModel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 3), SnmpSecurityModel().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsSecurityModel.setDescription("The Security Model to be used when generating SNMP\nmessages using this entry. An implementation may\nchoose to return an inconsistentValue error if an\nattempt is made to set this variable to a value\nfor a security model which the implementation does\nnot support.") snmpTargetParamsSecurityName = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 4), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsSecurityName.setDescription("The securityName which identifies the Principal on\nwhose behalf SNMP messages will be generated using\nthis entry.") snmpTargetParamsSecurityLevel = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 5), SnmpSecurityLevel()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsSecurityLevel.setDescription("The Level of Security to be used when generating\nSNMP messages using this entry.") snmpTargetParamsStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 6), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") snmpTargetParamsRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpTargetParamsRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the snmpTargetParamsRowStatus\ncolumn is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until the corresponding\nsnmpTargetParamsMPModel,\nsnmpTargetParamsSecurityModel,\nsnmpTargetParamsSecurityName,\nand snmpTargetParamsSecurityLevel have all been set.\n\nThe following objects may not be modified while the\nvalue of this object is active(1):\n - snmpTargetParamsMPModel\n - snmpTargetParamsSecurityModel\n - snmpTargetParamsSecurityName\n - snmpTargetParamsSecurityLevel\nAn attempt to set these objects while the value of\nsnmpTargetParamsRowStatus is active(1) will result in\nan inconsistentValue error.") snmpUnavailableContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpUnavailableContexts.setDescription("The total number of packets received by the SNMP\nengine which were dropped because the context\ncontained in the message was unavailable.") snmpUnknownContexts = MibScalar((1, 3, 6, 1, 6, 3, 12, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: snmpUnknownContexts.setDescription("The total number of packets received by the SNMP\nengine which were dropped because the context\ncontained in the message was unknown.") snmpTargetConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3)) snmpTargetCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 1)) snmpTargetGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 12, 3, 2)) # Augmentions # Groups snmpTargetBasicGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 1)).setObjects(*(("SNMP-TARGET-MIB", "snmpTargetAddrTDomain"), ("SNMP-TARGET-MIB", "snmpTargetParamsMPModel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityName"), ("SNMP-TARGET-MIB", "snmpTargetAddrTAddress"), ("SNMP-TARGET-MIB", "snmpTargetSpinLock"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityLevel"), ("SNMP-TARGET-MIB", "snmpTargetParamsSecurityModel"), ("SNMP-TARGET-MIB", "snmpTargetAddrRowStatus"), ("SNMP-TARGET-MIB", "snmpTargetAddrStorageType"), ("SNMP-TARGET-MIB", "snmpTargetAddrParams"), ("SNMP-TARGET-MIB", "snmpTargetParamsStorageType"), ("SNMP-TARGET-MIB", "snmpTargetAddrTagList"), ("SNMP-TARGET-MIB", "snmpTargetParamsRowStatus"), ) ) if mibBuilder.loadTexts: snmpTargetBasicGroup.setDescription("A collection of objects providing basic remote\nconfiguration of management targets.") snmpTargetResponseGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 2)).setObjects(*(("SNMP-TARGET-MIB", "snmpTargetAddrRetryCount"), ("SNMP-TARGET-MIB", "snmpTargetAddrTimeout"), ) ) if mibBuilder.loadTexts: snmpTargetResponseGroup.setDescription("A collection of objects providing remote configuration\nof management targets for applications which generate\nSNMP messages for which a response message would be\nexpected.") snmpTargetCommandResponderGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 12, 3, 2, 3)).setObjects(*(("SNMP-TARGET-MIB", "snmpUnavailableContexts"), ("SNMP-TARGET-MIB", "snmpUnknownContexts"), ) ) if mibBuilder.loadTexts: snmpTargetCommandResponderGroup.setDescription("A collection of objects required for command responder\napplications, used for counting error conditions.") # Compliances snmpTargetCommandResponderCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 12, 3, 1, 1)).setObjects(*(("SNMP-TARGET-MIB", "snmpTargetCommandResponderGroup"), ) ) if mibBuilder.loadTexts: snmpTargetCommandResponderCompliance.setDescription("The compliance statement for SNMP entities which include\na command responder application.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-TARGET-MIB", PYSNMP_MODULE_ID=snmpTargetMIB) # Types mibBuilder.exportSymbols("SNMP-TARGET-MIB", SnmpTagList=SnmpTagList, SnmpTagValue=SnmpTagValue) # Objects mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetMIB=snmpTargetMIB, snmpTargetObjects=snmpTargetObjects, snmpTargetSpinLock=snmpTargetSpinLock, snmpTargetAddrTable=snmpTargetAddrTable, snmpTargetAddrEntry=snmpTargetAddrEntry, snmpTargetAddrName=snmpTargetAddrName, snmpTargetAddrTDomain=snmpTargetAddrTDomain, snmpTargetAddrTAddress=snmpTargetAddrTAddress, snmpTargetAddrTimeout=snmpTargetAddrTimeout, snmpTargetAddrRetryCount=snmpTargetAddrRetryCount, snmpTargetAddrTagList=snmpTargetAddrTagList, snmpTargetAddrParams=snmpTargetAddrParams, snmpTargetAddrStorageType=snmpTargetAddrStorageType, snmpTargetAddrRowStatus=snmpTargetAddrRowStatus, snmpTargetParamsTable=snmpTargetParamsTable, snmpTargetParamsEntry=snmpTargetParamsEntry, snmpTargetParamsName=snmpTargetParamsName, snmpTargetParamsMPModel=snmpTargetParamsMPModel, snmpTargetParamsSecurityModel=snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName=snmpTargetParamsSecurityName, snmpTargetParamsSecurityLevel=snmpTargetParamsSecurityLevel, snmpTargetParamsStorageType=snmpTargetParamsStorageType, snmpTargetParamsRowStatus=snmpTargetParamsRowStatus, snmpUnavailableContexts=snmpUnavailableContexts, snmpUnknownContexts=snmpUnknownContexts, snmpTargetConformance=snmpTargetConformance, snmpTargetCompliances=snmpTargetCompliances, snmpTargetGroups=snmpTargetGroups) # Groups mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetBasicGroup=snmpTargetBasicGroup, snmpTargetResponseGroup=snmpTargetResponseGroup, snmpTargetCommandResponderGroup=snmpTargetCommandResponderGroup) # Compliances mibBuilder.exportSymbols("SNMP-TARGET-MIB", snmpTargetCommandResponderCompliance=snmpTargetCommandResponderCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/SNMP-NOTIFICATION-MIB.py0000644000076400001440000004366511737076367021720 0ustar ilyausers00000000000000# PySNMP SMI module. Autogenerated from smidump -f python SNMP-NOTIFICATION-MIB # by libsmi2pysnmp-0.1.3 at Tue Apr 3 15:14:42 2012, # Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0) # Imports ( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") ( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") ( SnmpAdminString, ) = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ( SnmpTagValue, snmpTargetBasicGroup, snmpTargetBasicGroup, snmpTargetBasicGroup, snmpTargetParamsMPModel, snmpTargetParamsName, snmpTargetParamsRowStatus, snmpTargetParamsSecurityLevel, snmpTargetParamsSecurityModel, snmpTargetParamsSecurityName, snmpTargetParamsStorageType, snmpTargetResponseGroup, ) = mibBuilder.importSymbols("SNMP-TARGET-MIB", "SnmpTagValue", "snmpTargetBasicGroup", "snmpTargetBasicGroup", "snmpTargetBasicGroup", "snmpTargetParamsMPModel", "snmpTargetParamsName", "snmpTargetParamsRowStatus", "snmpTargetParamsSecurityLevel", "snmpTargetParamsSecurityModel", "snmpTargetParamsSecurityName", "snmpTargetParamsStorageType", "snmpTargetResponseGroup") ( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup") ( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, snmpModules, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "snmpModules") ( RowStatus, StorageType, ) = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "StorageType") # Objects snmpNotificationMIB = ModuleIdentity((1, 3, 6, 1, 6, 3, 13)).setRevisions(("2002-10-14 00:00","1998-08-04 00:00","1997-07-14 00:00",)) if mibBuilder.loadTexts: snmpNotificationMIB.setOrganization("IETF SNMPv3 Working Group") if mibBuilder.loadTexts: snmpNotificationMIB.setContactInfo("WG-email: snmpv3@lists.tislabs.com\nSubscribe: majordomo@lists.tislabs.com\n In message body: subscribe snmpv3\n\nCo-Chair: Russ Mundy\n Network Associates Laboratories\nPostal: 15204 Omega Drive, Suite 300\n Rockville, MD 20850-4601\n USA\nEMail: mundy@tislabs.com\nPhone: +1 301-947-7107\n\nCo-Chair: David Harrington\n Enterasys Networks\nPostal: 35 Industrial Way\n P. O. Box 5004\n Rochester, New Hampshire 03866-5005\n USA\nEMail: dbh@enterasys.com\nPhone: +1 603-337-2614\n\nCo-editor: David B. Levi\n Nortel Networks\nPostal: 3505 Kesterwood Drive\n Knoxville, Tennessee 37918\nEMail: dlevi@nortelnetworks.com\nPhone: +1 865 686 0432\n\nCo-editor: Paul Meyer\n Secure Computing Corporation\nPostal: 2675 Long Lake Road\n Roseville, Minnesota 55113\nEMail: paul_meyer@securecomputing.com\nPhone: +1 651 628 1592\n\nCo-editor: Bob Stewart\n Retired") if mibBuilder.loadTexts: snmpNotificationMIB.setDescription("This MIB module defines MIB objects which provide\nmechanisms to remotely configure the parameters\nused by an SNMP entity for the generation of\nnotifications.\n\nCopyright (C) The Internet Society (2002). This\nversion of this MIB module is part of RFC 3413;\nsee the RFC itself for full legal notices.") snmpNotifyObjects = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 1)) snmpNotifyTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 1)) if mibBuilder.loadTexts: snmpNotifyTable.setDescription("This table is used to select management targets which should\nreceive notifications, as well as the type of notification\nwhich should be sent to each selected management target.") snmpNotifyEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 1, 1)).setIndexNames((1, "SNMP-NOTIFICATION-MIB", "snmpNotifyName")) if mibBuilder.loadTexts: snmpNotifyEntry.setDescription("An entry in this table selects a set of management targets\nwhich should receive notifications, as well as the type of\n\nnotification which should be sent to each selected\nmanagement target.\n\nEntries in the snmpNotifyTable are created and\ndeleted using the snmpNotifyRowStatus object.") snmpNotifyName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("noaccess") if mibBuilder.loadTexts: snmpNotifyName.setDescription("The locally arbitrary, but unique identifier associated\nwith this snmpNotifyEntry.") snmpNotifyTag = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 2), SnmpTagValue().clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyTag.setDescription("This object contains a single tag value which is used\nto select entries in the snmpTargetAddrTable. Any entry\nin the snmpTargetAddrTable which contains a tag value\nwhich is equal to the value of an instance of this\nobject is selected. If this object contains a value\nof zero length, no entries are selected.") snmpNotifyType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 3), Integer().subtype(subtypeSpec=SingleValueConstraint(2,1,)).subtype(namedValues=NamedValues(("trap", 1), ("inform", 2), )).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyType.setDescription("This object determines the type of notification to\n\nbe generated for entries in the snmpTargetAddrTable\nselected by the corresponding instance of\nsnmpNotifyTag. This value is only used when\ngenerating notifications, and is ignored when\nusing the snmpTargetAddrTable for other purposes.\n\nIf the value of this object is trap(1), then any\nmessages generated for selected rows will contain\nUnconfirmed-Class PDUs.\n\nIf the value of this object is inform(2), then any\nmessages generated for selected rows will contain\nConfirmed-Class PDUs.\n\nNote that if an SNMP entity only supports\ngeneration of Unconfirmed-Class PDUs (and not\nConfirmed-Class PDUs), then this object may be\nread-only.") snmpNotifyStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") snmpNotifyRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 1, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).") snmpNotifyFilterProfileTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 2)) if mibBuilder.loadTexts: snmpNotifyFilterProfileTable.setDescription("This table is used to associate a notification filter\nprofile with a particular set of target parameters.") snmpNotifyFilterProfileEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 2, 1)).setIndexNames((1, "SNMP-TARGET-MIB", "snmpTargetParamsName")) if mibBuilder.loadTexts: snmpNotifyFilterProfileEntry.setDescription("An entry in this table indicates the name of the filter\nprofile to be used when generating notifications using\nthe corresponding entry in the snmpTargetParamsTable.\n\nEntries in the snmpNotifyFilterProfileTable are created\nand deleted using the snmpNotifyFilterProfileRowStatus\nobject.") snmpNotifyFilterProfileName = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterProfileName.setDescription("The name of the filter profile to be used when generating\nnotifications using the corresponding entry in the\nsnmpTargetAddrTable.") snmpNotifyFilterProfileStorType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 2), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterProfileStorType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\nallow write-access to any columnar objects in the row.") snmpNotifyFilterProfileRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterProfileRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).\n\nUntil instances of all corresponding columns are\nappropriately configured, the value of the\ncorresponding instance of the\nsnmpNotifyFilterProfileRowStatus column is 'notReady'.\n\nIn particular, a newly created row cannot be made\nactive until the corresponding instance of\nsnmpNotifyFilterProfileName has been set.") snmpNotifyFilterTable = MibTable((1, 3, 6, 1, 6, 3, 13, 1, 3)) if mibBuilder.loadTexts: snmpNotifyFilterTable.setDescription("The table of filter profiles. Filter profiles are used\nto determine whether particular management targets should\nreceive particular notifications.\n\nWhen a notification is generated, it must be compared\nwith the filters associated with each management target\nwhich is configured to receive notifications, in order to\ndetermine whether it may be sent to each such management\ntarget.\n\nA more complete discussion of notification filtering\ncan be found in section 6. of [SNMP-APPL].") snmpNotifyFilterEntry = MibTableRow((1, 3, 6, 1, 6, 3, 13, 1, 3, 1)).setIndexNames((0, "SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), (1, "SNMP-NOTIFICATION-MIB", "snmpNotifyFilterSubtree")) if mibBuilder.loadTexts: snmpNotifyFilterEntry.setDescription("An element of a filter profile.\n\nEntries in the snmpNotifyFilterTable are created and\ndeleted using the snmpNotifyFilterRowStatus object.") snmpNotifyFilterSubtree = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 1), ObjectIdentifier()).setMaxAccess("noaccess") if mibBuilder.loadTexts: snmpNotifyFilterSubtree.setDescription("The MIB subtree which, when combined with the corresponding\ninstance of snmpNotifyFilterMask, defines a family of\nsubtrees which are included in or excluded from the\nfilter profile.") snmpNotifyFilterMask = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16)).clone('')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterMask.setDescription("The bit mask which, in combination with the corresponding\ninstance of snmpNotifyFilterSubtree, defines a family of\nsubtrees which are included in or excluded from the\nfilter profile.\n\nEach bit of this bit mask corresponds to a\nsub-identifier of snmpNotifyFilterSubtree, with the\nmost significant bit of the i-th octet of this octet\nstring value (extended if necessary, see below)\ncorresponding to the (8*i - 7)-th sub-identifier, and\nthe least significant bit of the i-th octet of this\noctet string corresponding to the (8*i)-th\nsub-identifier, where i is in the range 1 through 16.\n\nEach bit of this bit mask specifies whether or not\nthe corresponding sub-identifiers must match when\ndetermining if an OBJECT IDENTIFIER matches this\nfamily of filter subtrees; a '1' indicates that an\nexact match must occur; a '0' indicates 'wild card',\ni.e., any sub-identifier value matches.\n\nThus, the OBJECT IDENTIFIER X of an object instance\nis contained in a family of filter subtrees if, for\neach sub-identifier of the value of\nsnmpNotifyFilterSubtree, either:\n\n the i-th bit of snmpNotifyFilterMask is 0, or\n\n the i-th sub-identifier of X is equal to the i-th\n sub-identifier of the value of\n snmpNotifyFilterSubtree.\n\nIf the value of this bit mask is M bits long and\nthere are more than M sub-identifiers in the\ncorresponding instance of snmpNotifyFilterSubtree,\nthen the bit mask is extended with 1's to be the\nrequired length.\n\nNote that when the value of this object is the\nzero-length string, this extension rule results in\na mask of all-1's being used (i.e., no 'wild card'),\nand the family of filter subtrees is the one\nsubtree uniquely identified by the corresponding\ninstance of snmpNotifyFilterSubtree.") snmpNotifyFilterType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 3), Integer().subtype(subtypeSpec=SingleValueConstraint(1,2,)).subtype(namedValues=NamedValues(("included", 1), ("excluded", 2), )).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterType.setDescription("This object indicates whether the family of filter subtrees\ndefined by this entry are included in or excluded from a\nfilter. A more detailed discussion of the use of this\nobject can be found in section 6. of [SNMP-APPL].") snmpNotifyFilterStorageType = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 4), StorageType().clone('nonVolatile')).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterStorageType.setDescription("The storage type for this conceptual row.\nConceptual rows having the value 'permanent' need not\n\nallow write-access to any columnar objects in the row.") snmpNotifyFilterRowStatus = MibTableColumn((1, 3, 6, 1, 6, 3, 13, 1, 3, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: snmpNotifyFilterRowStatus.setDescription("The status of this conceptual row.\n\nTo create a row in this table, a manager must\nset this object to either createAndGo(4) or\ncreateAndWait(5).") snmpNotifyConformance = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3)) snmpNotifyCompliances = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 1)) snmpNotifyGroups = MibIdentifier((1, 3, 6, 1, 6, 3, 13, 3, 2)) # Augmentions # Groups snmpNotifyGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 1)).setObjects(*(("SNMP-NOTIFICATION-MIB", "snmpNotifyTag"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyRowStatus"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyType"), ) ) if mibBuilder.loadTexts: snmpNotifyGroup.setDescription("A collection of objects for selecting which management\ntargets are used for generating notifications, and the\ntype of notification to be generated for each selected\nmanagement target.") snmpNotifyFilterGroup = ObjectGroup((1, 3, 6, 1, 6, 3, 13, 3, 2, 2)).setObjects(*(("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterRowStatus"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileStorType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileName"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterStorageType"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterMask"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterProfileRowStatus"), ) ) if mibBuilder.loadTexts: snmpNotifyFilterGroup.setDescription("A collection of objects providing remote configuration\nof notification filters.") # Compliances snmpNotifyBasicCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 1)).setObjects(*(("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), ) ) if mibBuilder.loadTexts: snmpNotifyBasicCompliance.setDescription("The compliance statement for minimal SNMP entities which\nimplement only SNMP Unconfirmed-Class notifications and\nread-create operations on only the snmpTargetAddrTable.") snmpNotifyBasicFiltersCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 2)).setObjects(*(("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterGroup"), ("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), ) ) if mibBuilder.loadTexts: snmpNotifyBasicFiltersCompliance.setDescription("The compliance statement for SNMP entities which implement\nSNMP Unconfirmed-Class notifications with filtering, and\nread-create operations on all related tables.") snmpNotifyFullCompliance = ModuleCompliance((1, 3, 6, 1, 6, 3, 13, 3, 1, 3)).setObjects(*(("SNMP-TARGET-MIB", "snmpTargetResponseGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyFilterGroup"), ("SNMP-TARGET-MIB", "snmpTargetBasicGroup"), ("SNMP-NOTIFICATION-MIB", "snmpNotifyGroup"), ) ) if mibBuilder.loadTexts: snmpNotifyFullCompliance.setDescription("The compliance statement for SNMP entities which either\nimplement only SNMP Confirmed-Class notifications, or both\nSNMP Unconfirmed-Class and Confirmed-Class notifications,\nplus filtering and read-create operations on all related\ntables.") # Exports # Module identity mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", PYSNMP_MODULE_ID=snmpNotificationMIB) # Objects mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotificationMIB=snmpNotificationMIB, snmpNotifyObjects=snmpNotifyObjects, snmpNotifyTable=snmpNotifyTable, snmpNotifyEntry=snmpNotifyEntry, snmpNotifyName=snmpNotifyName, snmpNotifyTag=snmpNotifyTag, snmpNotifyType=snmpNotifyType, snmpNotifyStorageType=snmpNotifyStorageType, snmpNotifyRowStatus=snmpNotifyRowStatus, snmpNotifyFilterProfileTable=snmpNotifyFilterProfileTable, snmpNotifyFilterProfileEntry=snmpNotifyFilterProfileEntry, snmpNotifyFilterProfileName=snmpNotifyFilterProfileName, snmpNotifyFilterProfileStorType=snmpNotifyFilterProfileStorType, snmpNotifyFilterProfileRowStatus=snmpNotifyFilterProfileRowStatus, snmpNotifyFilterTable=snmpNotifyFilterTable, snmpNotifyFilterEntry=snmpNotifyFilterEntry, snmpNotifyFilterSubtree=snmpNotifyFilterSubtree, snmpNotifyFilterMask=snmpNotifyFilterMask, snmpNotifyFilterType=snmpNotifyFilterType, snmpNotifyFilterStorageType=snmpNotifyFilterStorageType, snmpNotifyFilterRowStatus=snmpNotifyFilterRowStatus, snmpNotifyConformance=snmpNotifyConformance, snmpNotifyCompliances=snmpNotifyCompliances, snmpNotifyGroups=snmpNotifyGroups) # Groups mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotifyGroup=snmpNotifyGroup, snmpNotifyFilterGroup=snmpNotifyFilterGroup) # Compliances mibBuilder.exportSymbols("SNMP-NOTIFICATION-MIB", snmpNotifyBasicCompliance=snmpNotifyBasicCompliance, snmpNotifyBasicFiltersCompliance=snmpNotifyBasicFiltersCompliance, snmpNotifyFullCompliance=snmpNotifyFullCompliance) pysnmp-4.2.5/pysnmp/smi/mibs/ASN1-REFINEMENT.py0000644000076400001440000000063111667155417020764 0ustar ilyausers00000000000000# ASN.1 types refinement tools from pyasn1.type import constraint mibBuilder.exportSymbols( 'ASN1-REFINEMENT', ConstraintsUnion=constraint.ConstraintsUnion, ConstraintsIntersection=constraint.ConstraintsIntersection, SingleValueConstraint=constraint.SingleValueConstraint, ValueRangeConstraint=constraint.ValueRangeConstraint, ValueSizeConstraint=constraint.ValueSizeConstraint ) pysnmp-4.2.5/pysnmp/smi/exval.py0000644000076400001440000000023611470071636017006 0ustar ilyausers00000000000000from pysnmp.proto import rfc1905 noSuchObject = rfc1905.noSuchObject noSuchInstance = rfc1905.noSuchInstance endOfMibView = endOfMib = rfc1905.endOfMibView pysnmp-4.2.5/pysnmp/smi/indices.py0000644000076400001440000000546211655706726017325 0ustar ilyausers00000000000000"""Ordered dictionaries classes used for indices""" from bisect import bisect class OrderedDict(dict): def __init__(self, **kwargs): self.__keys = [] self.__dirty = 1 super(OrderedDict, self).__init__() if kwargs: self.update(kwargs) def __setitem__(self, key, value): if key not in self: self.__keys.append(key) super(OrderedDict, self).__setitem__(key, value) self.__dirty = 1 def __repr__(self): if self.__dirty: self.__order() return super(OrderedDict, self).__repr__() def __str__(self): if self.__dirty: self.__order() return super(OrderedDict, self).__str__() def __delitem__(self, key): if super(OrderedDict, self).__contains__(key): self.__keys.remove(key) super(OrderedDict, self).__delitem__(key) self.__dirty = 1 __delattr__ = __delitem__ def clear(self): super(OrderedDict, self).clear() self.__keys = [] self.__dirty = 1 def keys(self): if self.__dirty: self.__order() return list(self.__keys) def values(self): if self.__dirty: self.__order() return [ self[k] for k in self.__keys ] def items(self): if self.__dirty: self.__order() return [ (k, self[k]) for k in self.__keys ] def update(self, d): [ self.__setitem__(k, v) for k,v in d.items() ] def sortingFun(self, keys): keys.sort() def __order(self): self.sortingFun(self.__keys) d = {} for k in self.__keys: d[len(k)] = 1 l = list(d.keys()) l.sort(reverse=True) self.__keysLens = tuple(l) self.__dirty = 0 def nextKey(self, key): keys = list(self.keys()) if key in self: nextIdx = keys.index(key) + 1 else: nextIdx = bisect(keys, key) if nextIdx < len(keys): return keys[nextIdx] else: raise KeyError(key) def getKeysLens(self): if self.__dirty: self.__order() return self.__keysLens class OidOrderedDict(OrderedDict): def __init__(self, **kwargs): self.__keysCache = {} OrderedDict.__init__(self, **kwargs) def __setitem__(self, key, value): if key not in self.__keysCache: if isinstance(key, tuple): self.__keysCache[key] = key else: self.__keysCache[key] = [ int(x) for x in key.split('.') if x ] OrderedDict.__setitem__(self, key, value) def __delitem__(self, key): if key in self.__keysCache: del self.__keysCache[key] OrderedDict.__delitem__(self, key) __delattr__ = __delitem__ def sortingFun(self, keys): keys.sort(key=lambda k, d=self.__keysCache: d[k]) pysnmp-4.2.5/pysnmp/smi/builder.py0000644000076400001440000003162312153626041017314 0ustar ilyausers00000000000000# MIB modules loader import os, sys, imp, struct, marshal, time, traceback from pysnmp.smi import error from pysnmp import debug if sys.version_info[0] <= 2: import types classTypes = (types.ClassType, type) else: classTypes = (type,) class __AbstractMibSource: def __init__(self, srcName): self._srcName = srcName self.__magic = imp.get_magic() self.__sfx = {} self.__inited = None for sfx, mode, typ in imp.get_suffixes(): if typ not in self.__sfx: self.__sfx[typ] = [] self.__sfx[typ].append((sfx, len(sfx), mode)) debug.logger & debug.flagBld and debug.logger('trying %s' % self) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self._srcName) def _uniqNames(self, files): u = {} for f in files: if f[:9] == '__init__.': continue for typ in (imp.PY_SOURCE, imp.PY_COMPILED): for sfx, sfxLen, mode in self.__sfx[typ]: if f[-sfxLen:] == sfx: u[f[:-sfxLen]] = None return tuple(u.keys()) # MibSource API follows def fullPath(self, f='', sfx=''): return self._srcName + (f and (os.sep + f + sfx) or '') def init(self): if self.__inited is None: self.__inited = self._init() if self.__inited is self: self.__inited = True if self.__inited is True: return self else: return self.__inited def listdir(self): return self._listdir() def read(self, f): for pycSfx, pycSfxLen, pycMode in self.__sfx[imp.PY_COMPILED]: try: pycData = self._getData(f + pycSfx, pycMode) except IOError: pycTime = -1 else: if self.__magic == pycData[:4]: pycData = pycData[4:] pycTime = struct.unpack('= pyTime: return marshal.loads(pycData), pycSfx if pyTime != -1: return self._getData(f+pySfx, pyMode), pySfx raise IOError('No suitable module found') # Interfaces for subclasses def _init(self): raise NotImplementedError() def _listdir(self): raise NotImplementedError() def _getTimestamp(self, f): raise NotImplementedError() def _getData(self, f, mode=None): 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 else: # Dir relative to PYTHONPATH return DirMibSource(os.path.split(p.__file__)[0]).init() except ImportError: # Dir relative to CWD return DirMibSource(self._srcName).init() def _parseDosTime(self, dosdate, dostime): t = ( ((dosdate >> 9) & 0x7f) + 1980, # year ((dosdate >> 5) & 0x0f), # month dosdate & 0x1f, # mday (dostime >> 11) & 0x1f, # hour (dostime >> 5) & 0x3f, # min (dostime & 0x1f) * 2, # sec -1, # wday -1, # yday -1 ) # dst return time.mktime(t) def _listdir(self): l = [] for f in self.__loader._files.keys(): d, f = os.path.split(f) if d == self._srcName: l.append(f) return tuple(self._uniqNames(l)) def _getTimestamp(self, f): p = os.path.join(self._srcName, f) if p in self.__loader._files: return self._parseDosTime( self.__loader._files[p][6], self.__loader._files[p][5] ) else: raise IOError('No file in ZIP: %s' % p) def _getData(self, f, mode=None): return self.__loader.get_data(os.path.join(self._srcName, f)) class DirMibSource(__AbstractMibSource): def _init(self): self._srcName = os.path.normpath(self._srcName) return self def _listdir(self): try: return self._uniqNames(os.listdir(self._srcName)) except OSError: return () def _getTimestamp(self, f): return os.stat(os.path.join(self._srcName, f))[8] def _getData(self, f, mode): try: if f in os.listdir(self._srcName): # make FS case-sensitive return open(os.path.join(self._srcName, f), mode).read() except OSError: pass raise IOError # pretend there's no such file class MibBuilder: loadTexts = 0 defaultCoreMibs = os.pathsep.join( ('pysnmp.smi.mibs.instances', 'pysnmp.smi.mibs') ) defaultMiscMibs = 'pysnmp_mibs' moduleID = 'PYSNMP_MODULE_ID' def __init__(self): self.lastBuildId = self._autoName = 0 sources = [] for m in os.environ.get('PYSNMP_MIB_PKGS', self.defaultCoreMibs).split(os.pathsep): sources.append(ZipMibSource(m)) # Compatibility variable if 'PYSNMP_MIB_DIR' in os.environ: os.environ['PYSNMP_MIB_DIRS'] = os.environ['PYSNMP_MIB_DIR'] if 'PYSNMP_MIB_DIRS' in os.environ: for m in os.environ['PYSNMP_MIB_DIRS'].split(os.pathsep): sources.append(DirMibSource(m)) if self.defaultMiscMibs: for m in self.defaultMiscMibs.split(os.pathsep): sources.append(ZipMibSource(m)) self.mibSymbols = {} self.__modSeen = {} self.__modPathsSeen = {} self.setMibSources(*sources) # MIB modules management def setMibSources(self, *mibSources): self.__mibSources = [ s.init() for s in mibSources ] debug.logger & debug.flagBld and debug.logger('setMibPath: new MIB sources %s' % (self.__mibSources,)) def getMibSources(self): return tuple(self.__mibSources) # Legacy/compatibility methods (won't work for .eggs) def setMibPath(self, *mibPaths): self.setMibSources(*[ DirMibSource(x) for x in mibPaths ]) def getMibPath(self): paths = () for mibSource in self.getMibSources(): if isinstance(mibSource, DirMibSource): paths += ( mibSource.fullPath(), ) else: raise error.SmiError( 'MIB source is not a plain directory: %s' % (mibSource,) ) return paths def loadModules(self, *modNames, **userCtx): # Build a list of available modules if not modNames: modNames = {} for mibSource in self.__mibSources: for modName in mibSource.listdir(): modNames[modName] = None modNames = list(modNames.keys()) if not modNames: raise error.SmiError( 'No MIB module to load at %s' % (self,) ) for modName in modNames: for mibSource in self.__mibSources: debug.logger & debug.flagBld and debug.logger('loadModules: trying %s at %s' % (modName, mibSource)) try: modData, sfx = mibSource.read(modName) except IOError: debug.logger & debug.flagBld and debug.logger('loadModules: read %s from %s failed: %s' % (modName, mibSource, sys.exc_info()[1])) continue modPath = mibSource.fullPath(modName, sfx) if modPath in self.__modPathsSeen: debug.logger & debug.flagBld and debug.logger('loadModules: seen %s' % modPath) break else: self.__modPathsSeen[modPath] = 1 debug.logger & debug.flagBld and debug.logger('loadModules: evaluating %s' % modPath) g = { 'mibBuilder': self, 'userCtx': userCtx } try: exec(modData, g) except Exception: del self.__modPathsSeen[modPath] raise error.SmiError( 'MIB module \"%s\" load error: %s' % (modPath, traceback.format_exception(*sys.exc_info())) ) self.__modSeen[modName] = modPath debug.logger & debug.flagBld and debug.logger('loadModules: loaded %s' % modPath) break if modName not in self.__modSeen: raise error.SmiError( 'MIB file \"%s\" not found in search path' % (modName and modName + ".py[co]") ) return self def unloadModules(self, *modNames): if not modNames: modNames = list(self.mibSymbols.keys()) for modName in modNames: if modName not in self.mibSymbols: raise error.SmiError( 'No module %s at %s' % (modName, self) ) self.unexportSymbols(modName) del self.__modPathsSeen[self.__modSeen[modName]] del self.__modSeen[modName] debug.logger & debug.flagBld and debug.logger('unloadModules: ' % (modName)) return self def importSymbols(self, modName, *symNames, **userCtx): if not modName: raise error.SmiError( 'importSymbols: empty MIB module name' ) r = () for symName in symNames: if modName not in self.mibSymbols: self.loadModules(modName, **userCtx) if modName not in self.mibSymbols: raise error.SmiError( 'No module %s loaded at %s' % (modName, self) ) if symName not in self.mibSymbols[modName]: raise error.SmiError( 'No symbol %s::%s at %s' % (modName, symName, self) ) r = r + (self.mibSymbols[modName][symName],) return r def exportSymbols(self, modName, *anonymousSyms, **namedSyms): if modName not in self.mibSymbols: self.mibSymbols[modName] = {} mibSymbols = self.mibSymbols[modName] for symObj in anonymousSyms: debug.logger & debug.flagBld and debug.logger('exportSymbols: anonymous symbol %s::__pysnmp_%ld' % (modName, self._autoName)) mibSymbols['__pysnmp_%ld' % self._autoName] = symObj self._autoName = self._autoName + 1 for symName, symObj in namedSyms.items(): if symName in mibSymbols: raise error.SmiError( 'Symbol %s already exported at %s' % (symName, modName) ) if symName != self.moduleID and \ not isinstance(symObj, classTypes): label = symObj.getLabel() if label: symName = label else: symObj.setLabel(symName) mibSymbols[symName] = symObj debug.logger & debug.flagBld and debug.logger('exportSymbols: symbol %s::%s' % (modName, symName)) self.lastBuildId = self.lastBuildId + 1 def unexportSymbols(self, modName, *symNames): if modName not in self.mibSymbols: raise error.SmiError( 'No module %s at %s' % (modName, self) ) mibSymbols = self.mibSymbols[modName] if not symNames: symNames = list(mibSymbols.keys()) for symName in symNames: if symName not in mibSymbols: raise error.SmiError( 'No symbol %s::%s at %s' % (modName, symName, self) ) del mibSymbols[symName] debug.logger & debug.flagBld and debug.logger('unexportSymbols: symbol %s::%s' % (modName, symName)) if not self.mibSymbols[modName]: del self.mibSymbols[modName] self.lastBuildId = self.lastBuildId + 1 pysnmp-4.2.5/pysnmp/cache.py0000644000076400001440000000217211655706725016154 0ustar ilyausers00000000000000# Limited-size dictionary class to use for caches class Cache: def __init__(self, maxSize=256): self.__maxSize = maxSize self.__size = 0 self.__chopSize = maxSize//10 self.__chopSize = self.__chopSize and self.__chopSize or 1 self.__cache = {} self.__usage = {} def __contains__(self, k): return k in self.__cache def __getitem__(self, k): self.__usage[k] = self.__usage[k] + 1 return self.__cache[k] def __len__(self): return self.__size def __setitem__(self, k, v): if self.__size >= self.__maxSize: keys = list(self.__usage.keys()) keys.sort(key=lambda x,d=self.__usage: d[x]) for _k in keys[:self.__chopSize]: del self.__cache[_k] del self.__usage[_k] self.__size = self.__size - self.__chopSize if k not in self.__cache: self.__size = self.__size + 1 self.__usage[k] = 0 self.__cache[k] = v def __delitem__(self, k): del self.__cache[k] del self.__usage[k] self.__size = self.__size - 1 pysnmp-4.2.5/pysnmp/carrier/0000755000076400001440000000000012222743671016154 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/carrier/__init__.py0000644000076400001440000000007311775060051020261 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/carrier/asynsock/0000755000076400001440000000000012222743671020006 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/carrier/asynsock/__init__.py0000644000076400001440000000007311775060054022116 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/carrier/asynsock/dgram/0000755000076400001440000000000012222743671021100 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/carrier/asynsock/dgram/udp6.py0000644000076400001440000000143112222117726022323 0ustar ilyausers00000000000000# Implements asyncore-based UDP6 transport domain try: from socket import AF_INET6 except: AF_INET6 = None from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport domainName = snmpUDP6Domain = (1, 3, 6, 1, 2, 1, 100, 1, 2) class Udp6SocketTransport(DgramSocketTransport): sockFamily = AF_INET6 def normalizeAddress(self, transportAddress): if '%' in transportAddress[0]: # strip zone ID return (transportAddress[0].split('%')[0], transportAddress[1], 0, # flowinfo 0) # scopeid else: return (transportAddress[0], transportAddress[1], 0, # flowinfo 0) # scopeid Udp6Transport = Udp6SocketTransport pysnmp-4.2.5/pysnmp/carrier/asynsock/dgram/unix.py0000644000076400001440000000245011775601046022437 0ustar ilyausers00000000000000# Implements asyncore-based UNIX transport domain import os import random try: from socket import AF_UNIX except ImportError: AF_UNIX = None from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) random.seed() class UnixSocketTransport(DgramSocketTransport): sockFamily = AF_UNIX 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: pass UnixTransport = UnixSocketTransport # Compatibility stub UnixDgramSocketTransport = UnixSocketTransport pysnmp-4.2.5/pysnmp/carrier/asynsock/dgram/__init__.py0000644000076400001440000000007311775060060023205 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/carrier/asynsock/dgram/udp.py0000644000076400001440000000046111772174365022252 0ustar ilyausers00000000000000# Implements asyncore-based UDP transport domain from socket import AF_INET from pysnmp.carrier.asynsock.dgram.base import DgramSocketTransport domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) class UdpSocketTransport(DgramSocketTransport): sockFamily = AF_INET UdpTransport = UdpSocketTransport pysnmp-4.2.5/pysnmp/carrier/asynsock/dgram/base.py0000644000076400001440000001001112222117726022351 0ustar ilyausers00000000000000# Implements asyncore-based generic DGRAM transport import socket, errno, sys from pysnmp.carrier.asynsock.base import AbstractSocketTransport from pysnmp.carrier import error from pysnmp import debug sockErrors = { # Ignore these socket errors errno.ESHUTDOWN: 1, errno.ENOTCONN: 1, errno.ECONNRESET: 0, errno.ECONNREFUSED: 0, errno.EAGAIN: 0, errno.EWOULDBLOCK: 0 } if hasattr(errno, 'EBADFD'): # bad FD may happen upon FD closure on n-1 select() event sockErrors[errno.EBADFD] = 1 class DgramSocketTransport(AbstractSocketTransport): sockType = socket.SOCK_DGRAM retryCount = 3; retryInterval = 1 def __init__(self, sock=None, sockMap=None): self.__outQueue = [] AbstractSocketTransport.__init__(self, sock, sockMap) def openClientMode(self, iface=None): if iface is not None: try: self.socket.bind(iface) except socket.error: raise error.CarrierError('bind() 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 sendMessage(self, outgoingMessage, transportAddress): self.__outQueue.append( (outgoingMessage, transportAddress) ) debug.logger & debug.flagIO and debug.logger('sendMessage: outgoingMessage queued (%d octets) %s' % (len(outgoingMessage), debug.hexdump(outgoingMessage))) def normalizeAddress(self, transportAddress): return transportAddress def __getsockname(self): # one evil OS does not seem to support getsockname() for DGRAM sockets try: return self.socket.getsockname() except: 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' % (self.__getsockname(), 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.socket.sendto(outgoingMessage, transportAddress) except socket.error: if sys.exc_info()[1].args[0] in sockErrors: debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (sys.exc_info()[1],)) else: raise 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.socket.recvfrom(65535) transportAddress = self.normalizeAddress(transportAddress) debug.logger & debug.flagIO and debug.logger('handle_read: transportAddress %r -> %r incomingMessage (%d octets) %s' % (transportAddress, self.__getsockname(), 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.2.5/pysnmp/carrier/asynsock/base.py0000644000076400001440000000671312212144142021264 0ustar ilyausers00000000000000# Defines standard API to asyncore-based transport import socket, sys import asyncore from pysnmp.carrier import error from pysnmp.carrier.base import AbstractTransport from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp import debug class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): protoTransportDispatcher = AsynsockDispatcher sockFamily = sockType = None retryCount = 0; retryInterval = 0 bufferSize = 131070 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 %d: %s' % (self.__class__.__name__, b, sys.exc_info()[1])) # The socket map is managed by the AsynsockDispatcher on # which this transport is registered. Here we just prepare # socket and postpone transport registration at dispatcher # till AsynsockDispatcher invokes registerSocket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) self.set_socket(sock) # 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) # Public API def openClientMode(self, iface=None): raise error.CarrierError('Method not implemented') def openServerMode(self, iface=None): raise error.CarrierError('Method not implemented') def sendMessage(self, outgoingMessage, transportAddress): raise error.CarrierError('Method not implemented') def 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.2.5/pysnmp/carrier/asynsock/dispatch.py0000644000076400001440000000310512164576216022162 0ustar ilyausers00000000000000# Implements I/O over asynchronous sockets 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 AsynsockDispatcher(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 and timeout or self.timeout, 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.2.5/pysnmp/carrier/error.py0000644000076400001440000000010610253524662017653 0ustar ilyausers00000000000000from pysnmp import error class CarrierError(error.PySnmpError): pass pysnmp-4.2.5/pysnmp/carrier/base.py0000644000076400001440000001547112220133030017424 0ustar ilyausers00000000000000# Abstract I/O dispatcher. Defines standard dispatcher API from pysnmp.carrier import error class TimerCallable: def __init__(self, cbFun, callInterval): self.__cbFun = cbFun self.__callInterval = callInterval self.__nextCall = 0 def __call__(self, timeNow): if self.__nextCall <= timeNow: self.__cbFun(timeNow) self.__nextCall = timeNow + self.__callInterval def __eq__(self, cbFun): return self.__cbFun == cbFun def __ne__(self, cbFun): return self.__cbFun != cbFun def __lt__(self, cbFun): return self.__cbFun < cbFun def __le__(self, cbFun): return self.__cbFun <= cbFun def __gt__(self, cbFun): return self.__cbFun > cbFun def __ge__(self, cbFun): return self.__cbFun >= cbFun class AbstractTransportDispatcher: def __init__(self): self.__transports = {} self.__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') 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): if jobId in self.__jobs: self.__jobs[jobId] = self.__jobs[jobId] + 1 else: self.__jobs[jobId] = 1 def jobFinished(self, jobId): self.__jobs[jobId] = self.__jobs[jobId] - 1 if self.__jobs[jobId] == 0: del self.__jobs[jobId] def jobsArePending(self): if self.__jobs: return 1 else: return 0 def runDispatcher(self, timeout=0.0): raise error.CarrierError('Method not implemented') def closeDispatcher(self): for tDomain in list(self.__transports): self.__transports[tDomain].closeTransport() self.unregisterTransport(tDomain) self.__transports.clear() self.unregisterRecvCbFun() self.unregisterTimerCbFun() class AbstractTransport: protoTransportDispatcher = None _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() pysnmp-4.2.5/pysnmp/carrier/twisted/0000755000076400001440000000000012222743671017637 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/carrier/twisted/__init__.py0000644000076400001440000000007311775060065021751 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/carrier/twisted/dgram/0000755000076400001440000000000012222743671020731 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/carrier/twisted/dgram/unix.py0000644000076400001440000000177312164555477022310 0ustar ilyausers00000000000000# Implements twisted-based UNIX domain socket transport import sys from twisted.internet import reactor from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport from pysnmp.carrier import error domainName = snmpLocalDomain = (1, 3, 6, 1, 2, 1, 100, 1, 13) class UnixTwistedTransport(DgramTwistedTransport): # AbstractTwistedTransport API def openClientMode(self, iface=''): try: self._lport = reactor.connectUNIXDatagram(iface, self) except Exception: raise error.CarrierError(sys.exc_info()[1]) return self def openServerMode(self, iface=None): try: self._lport = reactor.listenUNIXDatagram(iface, self) except Exception: raise error.CarrierError(sys.exc_info()[1]) return self def closeTransport(self): d = self._lport.stopListening() d and d.addCallback(lambda x: None) DgramTwistedTransport.closeTransport(self) UnixTransport = UnixTwistedTransport pysnmp-4.2.5/pysnmp/carrier/twisted/dgram/__init__.py0000644000076400001440000000007311775060070023037 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/carrier/twisted/dgram/udp.py0000644000076400001440000000174612164555477022115 0ustar ilyausers00000000000000# Implements twisted-based UDP transport import sys from twisted.internet import reactor from pysnmp.carrier.twisted.dgram.base import DgramTwistedTransport from pysnmp.carrier import error domainName = snmpUDPDomain = (1, 3, 6, 1, 6, 1, 1) class UdpTwistedTransport(DgramTwistedTransport): # AbstractTwistedTransport API def openClientMode(self, iface=('', 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=('', 161)): try: self._lport = reactor.listenUDP(iface[1], self, iface[0]) except Exception: raise error.CarrierError(sys.exc_info()[1]) return self def closeTransport(self): d = self._lport.stopListening() d and d.addCallback(lambda x: None) DgramTwistedTransport.closeTransport(self) UdpTransport = UdpTwistedTransport pysnmp-4.2.5/pysnmp/carrier/twisted/dgram/base.py0000644000076400001440000000412712164555477022233 0ustar ilyausers00000000000000# Implements twisted-based generic DGRAM transport import sys from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from pysnmp.carrier.twisted.base import AbstractTwistedTransport from pysnmp.carrier import error from pysnmp import debug class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport): """Base Twisted datagram Transport, to be used with TwistedDispatcher""" # Twisted Datagram API def datagramReceived(self, datagram, 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.2.5/pysnmp/carrier/twisted/base.py0000644000076400001440000000125512164555477021140 0ustar ilyausers00000000000000# # Copyright (C) 2008 Truelite Srl # Author: Filippo Giunchedi # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation # # Description: twisted DatagramProtocol UDP transport # from pysnmp.carrier.twisted.dispatch import TwistedDispatcher from pysnmp.carrier.base import AbstractTransport class AbstractTwistedTransport(AbstractTransport): protoTransportDispatcher = TwistedDispatcher """Base Twisted Transport, to be used with TwistedDispatcher""" def __init__(self): self._writeQ = [] pysnmp-4.2.5/pysnmp/carrier/twisted/dispatch.py0000644000076400001440000000416412164555477022027 0ustar ilyausers00000000000000# # Copyright (C) 2008 Truelite Srl # Author: Filippo Giunchedi # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2 # as published by the Free Software Foundation # # Description: Transport dispatcher based on twisted.internet.reactor # import sys, time, 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 = self.__transportCount + 1 def unregisterTransport(self, tDomain): t = AbstractTransportDispatcher.getTransport(self, tDomain) if t is not None: AbstractTransportDispatcher.unregisterTransport(self, tDomain) self.__transportCount = self.__transportCount - 1 # The last transport has been removed, stop the timeout if self.__transportCount == 0 and self.loopingcall.running: self.loopingcall.stop() pysnmp-4.2.5/pysnmp/nextid.py0000644000076400001440000000200711655706725016401 0ustar ilyausers00000000000000# Return a next value in a reasonably MT-safe manner import random random.seed() class Integer: def __init__(self, maximum, increment=256): self.__maximum = maximum if increment >= maximum: increment = maximum self.__increment = increment self.__threshold = increment//2 e = random.randrange(self.__maximum - self.__increment) self.__bank = list(range(e, e+self.__increment)) def __repr__(self): return '%s(%d, %d)' % ( self.__class__.__name__, self.__maximum, self.__increment ) def __call__(self): v = self.__bank.pop(0) if v % self.__threshold: return v else: # this is MT-safe unless too many (~ increment/2) threads # bump into this code simultaneously e = self.__bank[-1]+1 if e > self.__maximum: e = 0 self.__bank.extend(range(e, e+self.__threshold)) return v pysnmp-4.2.5/pysnmp/entity/0000755000076400001440000000000012222743671016041 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/entity/rfc3413/0000755000076400001440000000000012222743671017126 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/entity/rfc3413/__init__.py0000644000076400001440000000007311775060074021240 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/entity/rfc3413/oneliner/0000755000076400001440000000000012222743671020741 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/entity/rfc3413/oneliner/__init__.py0000644000076400001440000000007311775060100023041 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/entity/rfc3413/oneliner/target.py0000644000076400001440000000524212162560513022577 0ustar ilyausers00000000000000import socket, sys from pysnmp.carrier.asynsock.dgram import udp, udp6, unix from pysnmp import error from pyasn1.compat.octets import null class _AbstractTransportTarget: transportDomain = None protoTransport = NotImplementedError def __init__(self, transportAddr, timeout=1, retries=5, tagList=null): self.transportAddr = self._resolveAddr(transportAddr) self.timeout = timeout self.retries = retries self.tagList = tagList 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 openClientMode(self): self.transport = self.protoTransport().openClientMode() 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() class UdpTransportTarget(_AbstractTransportTarget): 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): 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.2.5/pysnmp/entity/rfc3413/oneliner/ntforg.py0000644000076400001440000002071312156567433022623 0ustar ilyausers00000000000000from pyasn1.compat.octets import null from pysnmp import nextid, error from pysnmp.entity import config from pysnmp.entity.rfc3413 import ntforg, context from pysnmp.entity.rfc3413.oneliner.mibvar import MibVariable from pysnmp.entity.rfc3413.oneliner.auth import CommunityData, UsmUserData from pysnmp.entity.rfc3413.oneliner.target import UdpTransportTarget, \ Udp6TransportTarget, UnixTransportTarget from pysnmp.entity.rfc3413.oneliner import cmdgen # Auth protocol usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol usmHMACSHAAuthProtocol = config.usmHMACSHAAuthProtocol usmNoAuthProtocol = config.usmNoAuthProtocol # Privacy protocol usmDESPrivProtocol = config.usmDESPrivProtocol usm3DESEDEPrivProtocol = config.usm3DESEDEPrivProtocol usmAesCfb128Protocol = config.usmAesCfb128Protocol usmAesCfb192Protocol = config.usmAesCfb192Protocol usmAesCfb256Protocol = config.usmAesCfb256Protocol usmNoPrivProtocol = config.usmNoPrivProtocol nextID = nextid.Integer(0xffffffff) class AsynNotificationOriginator(cmdgen.AsynCommandGenerator): def __init__(self, snmpEngine=None, snmpContext=None): cmdgen.AsynCommandGenerator.__init__(self, snmpEngine) self.snmpContext = snmpContext self.__knownNotifyNames = {} self.__knownAuths = {} def __del__(self): self.uncfgNtfOrg() def cfgNtfOrg(self, authData, transportTarget, notifyType): addrName, paramsName = self.cfgCmdGen(authData, transportTarget) tagList = transportTarget.tagList.split() if not tagList: tagList = [''] for tag in tagList: notifyNameKey = paramsName, tag, notifyType if notifyNameKey in self.__knownNotifyNames: notifyName, paramsName, useCount = self.__knownNotifyNames[notifyNameKey] self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, useCount + 1 else: notifyName = 'n%s' % nextID() config.addNotificationTarget( self.snmpEngine, notifyName, paramsName, tag, notifyType ) self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, 1 authDataKey = authData.securityName, authData.securityModel if authDataKey in self.__knownAuths: authDataX, subTree, useCount = self.__knownAuths[authDataKey] self.__knownAuths[authDataKey] = authDataX, subTree, useCount + 1 else: subTree = (1,3,6) config.addTrapUser( self.snmpEngine, authData.securityModel, authData.securityName, authData.securityLevel, subTree ) self.__knownAuths[authDataKey] = authData, subTree, 1 if self.snmpContext is None: self.snmpContext = context.SnmpContext(self.snmpEngine) config.addContext( self.snmpEngine, '' # this is leaky ) return notifyName def uncfgNtfOrg(self, authData=None): if authData: authDataKey = authData.securityName, authData.securityModel if authDataKey in self.__knownAuths: authDataKeys = ( authDataKey, ) else: raise error.PySnmpError('Unknown authData %s' % (authData,)) else: authDataKeys = self.__knownAuths.keys() addrNames, paramsNames = self.uncfgCmdGen(authData) notifyAndParamsNames = [ (self.__knownNotifyNames[x], x) for x in self.__knownNotifyNames.keys() if x[0] in paramsNames ] for (notifyName, paramsName, useCount), notifyNameKey in notifyAndParamsNames: useCount -= 1 if useCount: self.__knownNotifyNames[notifyNameKey] = notifyName, paramsName, useCount else: config.delNotificationTarget( self.snmpEngine, notifyName, paramsName ) del self.__knownNotifyNames[notifyNameKey] for authDataKey in authDataKeys: authDataX, subTree, useCount = self.__knownAuths[authDataKey] useCount -= 1 if useCount: self.__knownAuths[authDataKey] = authDataX, subTree, useCount else: config.delTrapUser( self.snmpEngine, authDataX.securityModel, authDataX.securityName, authDataX.securityLevel, subTree ) del self.__knownAuths[authDataKey] def sendNotification(self, authData, transportTarget, notifyType, notificationType, varBinds=(), cbInfo=(None, None), lookupNames=False, lookupValues=False, contextName=null): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupNames, lookupValues, cbFun, cbCtx = cbCtx if cbFun is None: # user callback not supplied return try: # we need to pass response PDU information to user for INFORMs return cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, self.unmakeVarBinds(varBinds, lookupNames, lookupValues), 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 (cbFun, cbCtx) = cbInfo # Create matching transport tags if not given by user 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] notifyName = self.cfgNtfOrg(authData, transportTarget, notifyType) if isinstance(notificationType, MibVariable): notificationType = notificationType.resolveWithMib(self.mibViewController, oidOnly=True) elif isinstance(notificationType[0], tuple): # legacy notificationType = MibVariable(notificationType[0][0], notificationType[0][1], *notificationType[1:]).resolveWithMib(self.mibViewController) return ntforg.NotificationOriginator(self.snmpContext).sendNotification(self.snmpEngine, notifyName, notificationType, self.makeVarBinds(varBinds), __cbFun, (lookupNames, lookupValues, cbFun, cbCtx), contextName) asyncSendNotification = sendNotification # substitute sendNotification return object for backward compatibility class ErrorIndicationReturn: def __init__(self, *vars): self.__vars = vars def __getitem__(self, i): return self.__vars[i] def __nonzero__(self): return self.__vars[0] and 1 or 0 def __bool__(self): return bool(self.__vars[0]) def __str__(self): return str(self.__vars[0]) class NotificationOriginator: def __init__(self, snmpEngine=None, snmpContext=None, asynNtfOrg=None): if asynNtfOrg is None: self.__asynNtfOrg = AsynNotificationOriginator( snmpEngine, snmpContext ) else: self.__asynNtfOrg = asynNtfOrg def sendNotification(self, authData, transportTarget, notifyType, notificationType, *varBinds, **kwargs): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, appReturn): appReturn[0] = ErrorIndicationReturn( errorIndication, errorStatus, errorIndex, varBinds ) appReturn = { 0: ErrorIndicationReturn(None, 0, 0, ()) } self.__asynNtfOrg.sendNotification( authData, transportTarget, notifyType, notificationType, varBinds, (__cbFun, appReturn), kwargs.get('lookupNames', False), kwargs.get('lookupValues', False), kwargs.get('contextName', null) ) self.__asynNtfOrg.snmpEngine.transportDispatcher.runDispatcher() return appReturn[0] pysnmp-4.2.5/pysnmp/entity/rfc3413/oneliner/auth.py0000644000076400001440000001353612153626041022256 0ustar ilyausers00000000000000from pysnmp.entity import config from pysnmp import error from pyasn1.compat.octets import null class CommunityData: 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 ) class UsmUserData: authKey = privKey = None authProtocol = config.usmNoAuthProtocol privProtocol = config.usmNoPrivProtocol securityLevel = 'noAuthNoPriv' securityModel = 3 mpModel = 3 contextName = null # the contextEngineId/contextName values stored here should # be used for USM configuration only, not for PDU contents def __init__(self, userName, authKey=None, privKey=None, authProtocol=None, privProtocol=None, securityEngineId=None, # deprecated parameters begin contextName=None, contextEngineId=None, # deprecated parameters end securityName=None): 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 # the contextEngineId parameter is actually a securityEngineId if securityEngineId is None: securityEngineId = contextEngineId self.contextEngineId = self.securityEngineId = securityEngineId # the contextName parameter should never be used here if contextName is not None: self.contextName = contextName 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)'%( self.__class__.__name__, self.userName, self.authProtocol, self.privProtocol, self.securityEngineId is None and '' or self.securityEngineId, self.securityName ) def clone(self, userName=None, authKey=None, privKey=None, authProtocol=None, privProtocol=None, securityEngineId=None, securityName=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=securityName is None and self.securityName or securityName ) pysnmp-4.2.5/pysnmp/entity/rfc3413/oneliner/cmdgen.py0000644000076400001440000006336112162560513022554 0ustar ilyausers00000000000000from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdgen from pysnmp.entity.rfc3413.oneliner.mibvar import MibVariable from pysnmp.entity.rfc3413.oneliner.auth import CommunityData, UsmUserData from pysnmp.entity.rfc3413.oneliner.target import UdpTransportTarget, \ Udp6TransportTarget, UnixTransportTarget from pysnmp.proto import rfc1905, errind from pysnmp.smi import view from pysnmp import nextid, error from pyasn1.type import univ, base from pyasn1.compat.octets import null # Auth protocol usmHMACMD5AuthProtocol = config.usmHMACMD5AuthProtocol usmHMACSHAAuthProtocol = config.usmHMACSHAAuthProtocol usmNoAuthProtocol = config.usmNoAuthProtocol # Privacy protocol usmDESPrivProtocol = config.usmDESPrivProtocol usm3DESEDEPrivProtocol = config.usm3DESEDEPrivProtocol usmAesCfb128Protocol = config.usmAesCfb128Protocol usmAesCfb192Protocol = config.usmAesCfb192Protocol usmAesCfb256Protocol = config.usmAesCfb256Protocol usmNoPrivProtocol = config.usmNoPrivProtocol nextID = nextid.Integer(0xffffffff) class AsynCommandGenerator: _null = univ.Null('') def __init__(self, snmpEngine=None): self.__knownAuths = {} self.__knownParams = {} self.__knownTransports = {} self.__knownTransportAddrs = {} if snmpEngine is None: self.snmpEngine = engine.SnmpEngine() else: self.snmpEngine = snmpEngine self.mibViewController = view.MibViewController( self.snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder ) def __del__(self): self.uncfgCmdGen() def cfgCmdGen(self, authData, transportTarget): if isinstance(authData, CommunityData): if authData.communityIndex not in self.__knownAuths: config.addV1System( self.snmpEngine, authData.communityIndex, authData.communityName, authData.contextEngineId, authData.contextName, authData.tag, authData.securityName ) self.__knownAuths[authData.communityIndex] = authData elif isinstance(authData, UsmUserData): authDataKey = authData.userName, authData.securityEngineId if authDataKey not in self.__knownAuths: config.addV3User( self.snmpEngine, authData.userName, authData.authProtocol, authData.authKey, authData.privProtocol, authData.privKey, authData.securityEngineId, securityName=authData.securityName ) self.__knownAuths[authDataKey] = authData else: raise error.PySnmpError('Unsupported authentication object') paramsKey = authData.securityName, \ authData.securityLevel, \ authData.mpModel if paramsKey in self.__knownParams: paramsName, useCount = self.__knownParams[paramsKey] self.__knownParams[paramsKey] = paramsName, useCount + 1 else: paramsName = 'p%s' % nextID() config.addTargetParams( self.snmpEngine, paramsName, authData.securityName, authData.securityLevel, authData.mpModel ) self.__knownParams[paramsKey] = paramsName, 1 if transportTarget.transportDomain in self.__knownTransports: transportTarget.verifyDispatcherCompatibility(self.snmpEngine) transport, useCount = self.__knownTransports[transportTarget.transportDomain] self.__knownTransports[transportTarget.transportDomain] = transport, useCount + 1 else: transport = transportTarget.openClientMode() config.addTransport( self.snmpEngine, transportTarget.transportDomain, transport ) self.__knownTransports[transportTarget.transportDomain] = transport, 1 transportKey = ( paramsName, transportTarget.transportDomain, transportTarget.transportAddr, transportTarget.tagList ) if transportKey in self.__knownTransportAddrs: addrName, useCount = self.__knownTransportAddrs[transportKey] self.__knownTransportAddrs[transportKey] = addrName, useCount + 1 else: addrName = 'a%s' % nextID() config.addTargetAddr( self.snmpEngine, addrName, transportTarget.transportDomain, transportTarget.transportAddr, paramsName, transportTarget.timeout * 100, transportTarget.retries, transportTarget.tagList ) self.__knownTransportAddrs[transportKey] = addrName, 1 return addrName, paramsName def uncfgCmdGen(self, authData=None): 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 self.__knownAuths: authDataKeys = ( authDataKey, ) else: raise error.PySnmpError('Unknown authData %s' % (authData,)) else: authDataKeys = list(self.__knownAuths.keys()) addrNames, paramsNames = set(), set() for authDataKey in authDataKeys: authDataX = self.__knownAuths[authDataKey] del self.__knownAuths[authDataKey] if isinstance(authDataX, CommunityData): config.delV1System( self.snmpEngine, authDataX.communityIndex ) elif isinstance(authDataX, UsmUserData): config.delV3User( self.snmpEngine, authDataX.userName, authDataX.securityEngineId ) else: raise error.PySnmpError('Unsupported authentication object') paramsKey = authDataX.securityName, \ authDataX.securityLevel, \ authDataX.mpModel if paramsKey in self.__knownParams: paramsName, useCount = self.__knownParams[paramsKey] useCount -= 1 if useCount: self.__knownParams[paramsKey] = paramsName, useCount else: del self.__knownParams[paramsKey] config.delTargetParams( self.snmpEngine, paramsName ) paramsNames.add(paramsName) else: raise error.PySnmpError('Unknown target %s' % (paramsKey,)) addrKeys = [ x for x in self.__knownTransportAddrs if x[0] == paramsName ] for addrKey in addrKeys: addrName, useCount = self.__knownTransportAddrs[addrKey] useCount -= 1 if useCount: self.__knownTransportAddrs[addrKey] = addrName, useCount else: config.delTargetAddr(self.snmpEngine, addrName) addrNames.add(addrKey) if addrKey[1] in self.__knownTransports: transport, useCount = self.__knownTransports[addrKey[1]] if useCount > 1: useCount -= 1 self.__knownTransports[addrKey[1]] = transport, useCount else: config.delTransport(self.snmpEngine, addrKey[1]) transport.closeTransport() del self.__knownTransports[addrKey[1]] return addrNames, paramsNames # compatibility stub def makeReadVarBinds(self, varNames): return self.makeVarBinds( [ (x, self._null) for x in varNames ], oidOnly=True ) def makeVarBinds(self, varBinds, oidOnly=False): __varBinds = [] for varName, varVal in varBinds: if isinstance(varName, MibVariable): if oidOnly or isinstance(varVal, base.AbstractSimpleAsn1Item): varName.resolveWithMib(self.mibViewController, oidOnly=True) else: varName.resolveWithMib(self.mibViewController) varVal = varName.getMibNode().getSyntax().clone(varVal) elif isinstance(varName[0], tuple): # legacy varName = MibVariable(varName[0][0], varName[0][1], *varName[1:]).resolveWithMib(self.mibViewController) if not oidOnly and \ not isinstance(varVal, base.AbstractSimpleAsn1Item): varVal = varName.getMibNode().getSyntax().clone(varVal) else: if oidOnly or isinstance(varVal, base.AbstractSimpleAsn1Item): varName = MibVariable(varName).resolveWithMib(self.mibViewController, oidOnly=True) else: varName = MibVariable(varName).resolveWithMib(self.mibViewController) varVal = varName.getMibNode().getSyntax().clone(varVal) __varBinds.append((varName, varVal)) return __varBinds def unmakeVarBinds(self, varBinds, lookupNames, lookupValues): if lookupNames or lookupValues: _varBinds = [] for name, value in varBinds: varName = MibVariable(name).resolveWithMib(self.mibViewController) if lookupNames: name = varName if lookupValues: if value.tagSet not in (rfc1905.NoSuchObject.tagSet, rfc1905.NoSuchInstance.tagSet, rfc1905.EndOfMibView.tagSet): if varName.isFullyResolved(): value = varName.getMibNode().getSyntax().clone(value) _varBinds.append((name, value)) return _varBinds else: return varBinds # Async SNMP apps def getCmd(self, authData, transportTarget, varNames, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupNames, lookupValues, cbFun, cbCtx = cbCtx return cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, self.unmakeVarBinds(varBinds, lookupNames, lookupValues), cbCtx ) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName (cbFun, cbCtx) = cbInfo addrName, paramsName = self.cfgCmdGen( authData, transportTarget ) return cmdgen.GetCommandGenerator().sendReq( self.snmpEngine, addrName, self.makeReadVarBinds(varNames), __cbFun, (lookupNames, lookupValues, cbFun, cbCtx), contextEngineId, contextName ) asyncGetCmd = getCmd def setCmd(self, authData, transportTarget, varBinds, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): lookupNames, lookupValues, cbFun, cbCtx = cbCtx return cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, self.unmakeVarBinds(varBinds, lookupNames, lookupValues), cbCtx ) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName (cbFun, cbCtx) = cbInfo addrName, paramsName = self.cfgCmdGen( authData, transportTarget ) return cmdgen.SetCommandGenerator().sendReq( self.snmpEngine, addrName, self.makeVarBinds(varBinds), __cbFun, (lookupNames, lookupValues, cbFun, cbCtx), contextEngineId, contextName ) asyncSetCmd = setCmd def nextCmd(self, authData, transportTarget, varNames, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupNames, lookupValues, cbFun, cbCtx = cbCtx return cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, [ self.unmakeVarBinds(varBindTableRow, lookupNames, lookupValues) for varBindTableRow in varBindTable ], cbCtx ) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName (cbFun, cbCtx) = cbInfo addrName, paramsName = self.cfgCmdGen( authData, transportTarget ) return cmdgen.NextCommandGenerator().sendReq( self.snmpEngine, addrName, self.makeReadVarBinds(varNames), __cbFun, (lookupNames, lookupValues, cbFun, cbCtx), contextEngineId, contextName ) asyncNextCmd = nextCmd def bulkCmd(self, authData, transportTarget, nonRepeaters, maxRepetitions, varNames, cbInfo, lookupNames=False, lookupValues=False, contextEngineId=None, contextName=null): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): lookupNames, lookupValues, cbFun, cbCtx = cbCtx return cbFun( sendRequestHandle, errorIndication, errorStatus, errorIndex, [ self.unmakeVarBinds(varBindTableRow, lookupNames, lookupValues) for varBindTableRow in varBindTable ], cbCtx ) # for backward compatibility if contextName is null and authData.contextName: contextName = authData.contextName (cbFun, cbCtx) = cbInfo addrName, paramsName = self.cfgCmdGen( authData, transportTarget ) varBinds = self.makeReadVarBinds(varNames) return cmdgen.BulkCommandGenerator().sendReq( self.snmpEngine, addrName, nonRepeaters, maxRepetitions, varBinds, __cbFun, (lookupNames, lookupValues, cbFun, cbCtx), contextEngineId, contextName ) asyncBulkCmd = bulkCmd class CommandGenerator: def __init__(self, snmpEngine=None, asynCmdGen=None): if asynCmdGen is None: self.__asynCmdGen = AsynCommandGenerator(snmpEngine) else: self.__asynCmdGen = asynCmdGen # compatibility attributes self.snmpEngine = self.__asynCmdGen.snmpEngine self.mibViewController = self.__asynCmdGen.mibViewController def getCmd(self, authData, transportTarget, *varNames, **kwargs): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, appReturn): appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex appReturn['varBinds'] = varBinds appReturn = {} self.__asynCmdGen.getCmd( authData, transportTarget, varNames, (__cbFun, appReturn), kwargs.get('lookupNames', False), kwargs.get('lookupValues', False), kwargs.get('contextEngineId'), kwargs.get('contextName', null) ) self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() return ( appReturn['errorIndication'], appReturn['errorStatus'], appReturn['errorIndex'], appReturn['varBinds'] ) def setCmd(self, authData, transportTarget, *varBinds, **kwargs): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, appReturn): appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex appReturn['varBinds'] = varBinds appReturn = {} self.__asynCmdGen.setCmd( authData, transportTarget, varBinds, (__cbFun, appReturn), kwargs.get('lookupNames', False), kwargs.get('lookupValues', False), kwargs.get('contextEngineId'), kwargs.get('contextName', null) ) self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() return ( appReturn['errorIndication'], appReturn['errorStatus'], appReturn['errorIndex'], appReturn['varBinds'] ) def nextCmd(self, authData, transportTarget, *varNames, **kwargs): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): (self, varBindHead, varBindTotalTable, appReturn) = cbCtx if (ignoreNonIncreasingOid or \ hasattr(self, 'ignoreNonIncreasingOid') and \ self.ignoreNonIncreasingOid ) and \ errorIndication and \ isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorStatus or errorIndication: appReturn['errorIndication'] = errorIndication if errorStatus == 2: # Hide SNMPv1 noSuchName error which leaks in here # from SNMPv1 Agent through internal pysnmp proxy. appReturn['errorStatus'] = errorStatus.clone(0) appReturn['errorIndex'] = errorIndex.clone(0) else: appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex appReturn['varBindTable'] = varBindTotalTable return else: if maxRows and len(varBindTotalTable) >= maxRows or \ hasattr(self, 'maxRows') and self.maxRows and \ len(varBindTotalTable) >= self.maxRows: appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex if hasattr(self, 'maxRows'): appReturn['varBindTable'] = varBindTotalTable[:self.maxRows] else: appReturn['varBindTable'] = varBindTotalTable[:maxRows] return varBindTableRow = varBindTable and varBindTable[-1] or varBindTable for idx in range(len(varBindTableRow)): name, val = varBindTableRow[idx] # XXX extra rows if not isinstance(val, univ.Null): if lexicographicMode or \ hasattr(self, 'lexicographicMode') and \ self.lexicographicMode: # obsolete if varBindHead[idx] <= name: break else: if varBindHead[idx].isPrefixOf(name): break else: appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex appReturn['varBindTable'] = varBindTotalTable return varBindTotalTable.extend(varBindTable) return 1 # continue table retrieval lookupNames = kwargs.get('lookupNames', False) lookupValues = kwargs.get('lookupValues', False) contextEngineId = kwargs.get('contextEngineId') contextName = kwargs.get('contextName', null) lexicographicMode = kwargs.get('lexicographicMode', False) maxRows = kwargs.get('maxRows', 0) ignoreNonIncreasingOid = kwargs.get('ignoreNonIncreasingOid', False) varBindHead = [ univ.ObjectIdentifier(x[0]) for x in self.__asynCmdGen.makeReadVarBinds(varNames) ] appReturn = {} self.__asynCmdGen.nextCmd( authData, transportTarget, varNames, (__cbFun, (self, varBindHead, [], appReturn)), lookupNames, lookupValues, contextEngineId, contextName ) self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() return ( appReturn['errorIndication'], appReturn['errorStatus'], appReturn['errorIndex'], appReturn['varBindTable'] ) def bulkCmd(self, authData, transportTarget, nonRepeaters, maxRepetitions, *varNames, **kwargs): def __cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): (self, varBindHead, varBindTotalTable, appReturn) = cbCtx if (ignoreNonIncreasingOid or \ hasattr(self, 'ignoreNonIncreasingOid') and \ self.ignoreNonIncreasingOid ) and \ errorIndication and \ isinstance(errorIndication, errind.OidNotIncreasing): errorIndication = None if errorStatus or errorIndication: appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex appReturn['varBindTable'] = varBindTable return else: while varBindTable: if len(varBindTable[-1]) != len(varBindHead): # Fix possibly non-rectangular table del varBindTable[-1] else: break varBindTotalTable.extend(varBindTable) # XXX out of table # rows possible if maxRows and len(varBindTotalTable) >= maxRows or \ hasattr(self, 'maxRows') and self.maxRows and \ len(varBindTotalTable) >= self.maxRows: # obsolete appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex if hasattr(self, 'maxRows'): appReturn['varBindTable'] = varBindTotalTable[:self.maxRows] else: appReturn['varBindTable'] = varBindTotalTable[:maxRows] return varBindTableRow = varBindTable and varBindTable[-1] or varBindTable for idx in range(len(varBindTableRow)): name, val = varBindTableRow[idx] if not isinstance(val, univ.Null): if lexicographicMode or \ hasattr(self, 'lexicographicMode') and \ self.lexicographicMode: # obsolete if varBindHead[idx] <= name: break else: if varBindHead[idx].isPrefixOf(name): break else: appReturn['errorIndication'] = errorIndication appReturn['errorStatus'] = errorStatus appReturn['errorIndex'] = errorIndex appReturn['varBindTable'] = varBindTotalTable return return 1 # continue table retrieval lookupNames = kwargs.get('lookupNames', False) lookupValues = kwargs.get('lookupValues', False) contextEngineId = kwargs.get('contextEngineId') contextName = kwargs.get('contextName', null) lexicographicMode = kwargs.get('lexicographicMode', False) maxRows = kwargs.get('maxRows', 0) ignoreNonIncreasingOid = kwargs.get('ignoreNonIncreasingOid', False) varBindHead = [ univ.ObjectIdentifier(x[0]) for x in self.__asynCmdGen.makeReadVarBinds(varNames) ] appReturn = {} self.__asynCmdGen.bulkCmd( authData, transportTarget, nonRepeaters, maxRepetitions, varNames, (__cbFun, (self, varBindHead, [], appReturn)), lookupNames, lookupValues, contextEngineId, contextName ) self.__asynCmdGen.snmpEngine.transportDispatcher.runDispatcher() return ( appReturn['errorIndication'], appReturn['errorStatus'], appReturn['errorIndex'], appReturn['varBindTable'] ) pysnmp-4.2.5/pysnmp/entity/rfc3413/oneliner/mibvar.py0000644000076400001440000002527212153626041022575 0ustar ilyausers00000000000000from pysnmp.proto import rfc1902 from pysnmp.smi.builder import ZipMibSource from pysnmp.error import PySnmpError from pyasn1.error import PyAsn1Error # # An OID-like object that embeds MIB resolution. # # Valid initializers include: # MibVariable('1.3.6.1.2.1.1.1.0'), # MibVariable('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0') # MibVariable('SNMPv2-MIB', 'system'), # MibVariable('SNMPv2-MIB', 'sysDescr', 0), # MibVariable('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123), # class MibVariable: stDirty, stOidOnly, stClean, stUnresolved = 1, 2, 4, 8 def __init__(self, *args): self.__args = args self.__mibSourcesToAdd = self.__modNamesToLoad = None self.__state = self.stDirty # # public API # def getMibSymbol(self): if self.__state & self.stClean: return self.__modName, self.__symName, self.__indices else: raise PySnmpError('%s object not fully initialized' % self.__class__.__name__) def getOid(self): if self.__state & (self.stOidOnly | self.stClean): return self.__oid else: raise PySnmpError('%s object not fully initialized' % self.__class__.__name__) def getLabel(self): if self.__state & self.stClean: return self.__label else: raise PySnmpError('%s object not fully initialized' % self.__class__.__name__) def getMibNode(self): # XXX if self.__state & self.stClean: return self.__mibNode else: raise PySnmpError('%s object not fully initialized' % self.__class__.__name__) def isFullyResolved(self): return not (self.__state & self.stUnresolved) # # A gateway to MIBs manipulation routines # def addMibSource(self, *mibSources): self.__mibSourcesToAdd = mibSources return self # provides deferred MIBs load def loadMibs(self, *modNames): self.__modNamesToLoad = modNames return self # this would eventually be called by an entity which posses a # reference to MibViewController def resolveWithMib(self, mibViewController, oidOnly=False): if self.__mibSourcesToAdd is not None: mibSources = tuple( [ ZipMibSource(x) for x in self.__mibSourcesToAdd ] ) + mibViewController.mibBuilder.getMibSources() mibViewController.mibBuilder.setMibSources(*mibSources) self.__mibSourcesToAdd = None if self.__modNamesToLoad is not None: mibViewController.mibBuilder.loadModules(*self.__modNamesToLoad) self.__modNamesToLoad = None if self.__state & (self.stOidOnly | self.stClean): return self MibScalar, MibTableColumn, = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTableColumn') if len(self.__args) == 1: # OID or label try: self.__oid = rfc1902.ObjectName(self.__args[0]) except PyAsn1Error: try: label = tuple(self.__args[0].split('.')) except ValueError: raise PySnmpError('Bad OID format %s' % (self.__args[0],)) prefix, label, suffix = mibViewController.getNodeNameByOid( label ) if suffix: try: suffix = tuple([ int(x) for x in suffix ]) except ValueError: raise PySnmpError('Unknown object name component %s' % (suffix,)) self.__oid = rfc1902.ObjectName(prefix + suffix) self.__state |= self.stOidOnly if oidOnly: return self else: self.__state |= self.stOidOnly if oidOnly: return self prefix, label, suffix = mibViewController.getNodeNameByOid( self.__oid ) modName, symName, _ = mibViewController.getNodeLocation(prefix) self.__modName = modName self.__symName = symName self.__label = label mibNode, = mibViewController.mibBuilder.importSymbols( modName, symName ) self.__mibNode = mibNode if isinstance(mibNode, MibTableColumn): # table column rowModName, rowSymName, _ = mibViewController.getNodeLocation( mibNode.name[:-1] ) rowNode, = mibViewController.mibBuilder.importSymbols( rowModName, rowSymName ) self.__indices = rowNode.getIndicesFromInstId(suffix) elif isinstance(mibNode, MibScalar): # scalar self.__indices = ( rfc1902.ObjectName(suffix), ) else: self.__indices = ( rfc1902.ObjectName(suffix), ) self.__state |= self.stUnresolved self.__state |= self.stClean return self elif len(self.__args) > 1: # MIB, symbol[, index, index ...] self.__modName = self.__args[0] if self.__args[1]: self.__symName = self.__args[1] else: mibViewController.mibBuilder.loadModules(self.__modName) oid, _, _ = mibViewController.getFirstNodeName(self.__modName) _, self.__symName, _ = mibViewController.getNodeLocation(oid) mibNode, = mibViewController.mibBuilder.importSymbols( self.__modName, self.__symName ) self.__mibNode = mibNode self.__indices = () self.__oid = rfc1902.ObjectName(mibNode.getName()) prefix, label, suffix = mibViewController.getNodeNameByOid( self.__oid ) self.__label = label if isinstance(mibNode, MibTableColumn): # table rowModName, rowSymName, _ = mibViewController.getNodeLocation( mibNode.name[:-1] ) rowNode, = mibViewController.mibBuilder.importSymbols( rowModName, rowSymName ) if self.__args[2:]: instIds = rowNode.getInstIdFromIndices(*self.__args[2:]) self.__oid += instIds self.__indices = rowNode.getIndicesFromInstId(instIds) elif self.__args[2:]: # any other kind of MIB node with indices instId = rfc1902.ObjectName( '.'.join([ str(x) for x in self.__args[2:] ]) ) self.__oid += instId self.__indices = ( instId, ) self.__state |= (self.stClean | self.stOidOnly) return self else: raise PySnmpError('Non-OID, label or MIB symbol') def prettyPrint(self): if self.__state & self.stClean: return '%s::%s.%s' % ( self.__modName, self.__symName, '.'.join(['"%s"' % x.prettyPrint() for x in self.__indices ]) ) else: raise PySnmpError('%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.stOidOnly: return str(self.__oid) else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __eq__(self, other): if self.__state & self.stOidOnly: return self.__oid == other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __ne__(self, other): if self.__state & self.stOidOnly: return self.__oid != other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __lt__(self, other): if self.__state & self.stOidOnly: return self.__oid < other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __le__(self, other): if self.__state & self.stOidOnly: return self.__oid <= other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __gt__(self, other): if self.__state & self.stOidOnly: return self.__oid > other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __ge__(self, other): if self.__state & self.stOidOnly: return self.__oid > other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __nonzero__(self): if self.__state & self.stOidOnly: return self.__oid != 0 else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __bool__(self): if self.__state & self.stOidOnly: return bool(self.__oid) else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __getitem__(self, i): if self.__state & self.stOidOnly: return self.__oid[i] else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __len__(self): if self.__state & self.stOidOnly: return len(self.__oid) else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __add__(self, other): if self.__state & self.stOidOnly: return self.__oid + other else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __radd__(self, other): if self.__state & self.stOidOnly: return other + self.__oid else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __hash__(self): if self.__state & self.stOidOnly: return hash(self.__oid) else: raise PySnmpError('%s object not properly initialized' % self.__class__.__name__) def __getattr__(self, attr): if self.__state & self.stOidOnly: if attr in ( 'asTuple', 'clone', 'subtype', 'isPrefixOf', 'isSameTypeWith', 'isSuperTypeOf'): return getattr(self.__oid, attr) raise AttributeError else: raise PySnmpError('%s object not properly initialized for %s access' % (self.__class__.__name__, attr)) pysnmp-4.2.5/pysnmp/entity/rfc3413/config.py0000644000076400001440000002347412153626041020751 0ustar ilyausers00000000000000# Shortcuts to MIB instrumentation items used internally in SNMP applications 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' ) if 'getTargetAddr' not in snmpEngine.cache: snmpEngine.cache['getTargetAddr'] = { 'id': -1 } cache = snmpEngine.cache['getTargetAddr'] 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' ) 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 except NoSuchInstanceError: raise SmiError('Target %s not configured to LCD' % snmpTargetAddrName) if snmpTargetAddrTDomain[:len(config.snmpUDPDomain)] == config.snmpUDPDomain: SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') snmpTargetAddrTAddress = tuple( SnmpUDPAddress(snmpTargetAddrTAddress) ) elif snmpTargetAddrTDomain[:len(config.snmpUDP6Domain)] == config.snmpUDP6Domain: TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') snmpTargetAddrTAddress = tuple( TransportAddressIPv6(snmpTargetAddrTAddress) ) elif snmpTargetAddrTDomain[:len(config.snmpLocalDomain)] == config.snmpLocalDomain: snmpTargetAddrTAddress = str(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' ) if 'getTargetParams' not in snmpEngine.cache: snmpEngine.cache['getTargetParams'] = { 'id': -1 } cache = snmpEngine.cache['getTargetParams'] 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' ) if 'getNotificationInfo' not in snmpEngine.cache: snmpEngine.cache['getNotificationInfo'] = { 'id': -1 } cache = snmpEngine.cache['getNotificationInfo'] 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' ) if 'getTargetNames' not in snmpEngine.cache: snmpEngine.cache['getTargetNames'] = { 'id': -1 } cache = snmpEngine.cache['getTargetNames'] 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' ) targetNames = [] mibNode = snmpTargetAddrTagList while 1: 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.2.5/pysnmp/entity/rfc3413/context.py0000644000076400001440000000450512162613323021161 0ustar ilyausers00000000000000# SNMP entity context from pyasn1.type import univ from pyasn1.compat.octets import null from pysnmp import error from pysnmp import debug class SnmpContext: def __init__(self, snmpEngine, contextEngineId=None): 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.2.5/pysnmp/entity/rfc3413/ntforg.py0000644000076400001440000004027312153626041020777 0ustar ilyausers00000000000000import sys from pyasn1.compat.octets import null from pysnmp.entity.rfc3413 import config from pysnmp.proto.proxy import rfc2576 from pysnmp.proto.api import v2c from pysnmp.proto import error from pysnmp import nextid from pysnmp import debug getNextHandle = nextid.Integer(0x7fffffff) class NotificationOriginator: acmID = 3 # default MIB access control method to use def __init__(self, snmpContext): self.__pendingReqs = {} self.__pendingNotifications = {} self.snmpContext = snmpContext def processResponsePdu( self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, sendPduHandle, cbInfo ): (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, metaSendPduHandle ) = self.__pendingReqs[sendPduHandle] del self.__pendingReqs[sendPduHandle] self.__pendingNotifications[metaSendPduHandle] -= 1 snmpEngine.transportDispatcher.jobFinished(id(self)) if statusInformation: debug.logger & debug.flagApp and debug.logger('processResponsePdu: metaSendPduHandle %s, sendPduHandle %s statusInformation %s' % (metaSendPduHandle, sendPduHandle, statusInformation)) if origRetries == origRetryCount: debug.logger & debug.flagApp and debug.logger('processResponsePdu: metaSendPduHandle %s, sendPduHandle %s retry count %d exceeded' % (metaSendPduHandle, sendPduHandle, origRetries)) if not self.__pendingNotifications[metaSendPduHandle]: del self.__pendingNotifications[metaSendPduHandle] self._handleResponse( metaSendPduHandle, statusInformation['errorIndication'], 0, 0, (), cbFun, 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, 1, # expectResponse timeoutInTicks, self.processResponsePdu, (cbFun, cbCtx) ) except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('processResponsePdu: metaSendPduHandle %s: sendPdu() failed with %r ' % (metaSendPduHandle, statusInformation)) if not self.__pendingNotifications[metaSendPduHandle]: del self.__pendingNotifications[metaSendPduHandle] self._handleResponse( metaSendPduHandle, statusInformation['errorIndication'], 0, 0, (), cbFun, cbCtx ) return self.__pendingNotifications[metaSendPduHandle] += 1 snmpEngine.transportDispatcher.jobStarted(id(self)) debug.logger & debug.flagApp and debug.logger('processResponsePdu: metaSendPduHandle %s, sendPduHandle %s, timeout %d, retry %d of %d' % (metaSendPduHandle, sendPduHandle, origTimeout, origRetries, origRetryCount)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPdu, origTimeout, origRetryCount, origRetries + 1, metaSendPduHandle ) return # 3.3.6c if not self.__pendingNotifications[metaSendPduHandle]: del self.__pendingNotifications[metaSendPduHandle] # User-side API assumes SMIv2 if messageProcessingModel == 0: PDU = rfc2576.v1ToV2(PDU, origPdu) self._handleResponse(metaSendPduHandle, None, v2c.apiPDU.getErrorStatus(PDU), v2c.apiPDU.getErrorIndex(PDU,muteErrors=True), v2c.apiPDU.getVarBinds(PDU), cbFun, cbCtx) def _handleResponse(self, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbFun, 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 ): debug.logger & debug.flagApp and debug.logger('sendNotification: notificationTarget %s, notificationName %s, additionalVarBinds %s, contextName "%s", instanceIndex %s' % (notificationTarget, notificationName, additionalVarBinds, contextName, instanceIndex)) if contextName: __SnmpAdminString, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') contextName = __SnmpAdminString(contextName) # 3.3 ( notifyTag, notifyType ) = config.getNotificationInfo( snmpEngine, notificationTarget ) metaSendPduHandle = getNextHandle() debug.logger & debug.flagApp and debug.logger('sendNotification: metaSendPduHandle %s, notifyTag %s, notifyType %s' % (metaSendPduHandle, notifyTag, notifyType)) contextMibInstrumCtl = self.snmpContext.getMibInstrum(contextName) additionalVarBinds = [ (v2c.ObjectIdentifier(x),y) for x,y in additionalVarBinds ] for targetAddrName in config.getTargetNames(snmpEngine, notifyTag): ( transportDomain, transportAddress, timeout, retryCount, params ) = config.getTargetAddr(snmpEngine, targetAddrName) ( messageProcessingModel, securityModel, securityName, securityLevel ) = config.getTargetParams(snmpEngine, params) debug.logger & debug.flagApp and debug.logger('sendNotification: metaSendPduHandle %s, notifyTag %s yields: transportDomain %s, transportAddress %r, securityModel %s, securityName %s, securityLevel %s' % (metaSendPduHandle, notifyTag, transportDomain, transportAddress, securityModel, securityName, securityLevel)) # 3.3.1 XXX # XXX filtering's yet to be implemented # filterProfileName = config.getNotifyFilterProfile(params) # ( filterSubtree, # filterMask, # filterType ) = config.getNotifyFilter(filterProfileName) varBinds = [] # 3.3.2 & 3.3.3 sysUpTime, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'sysUpTime') for varName, varVal in additionalVarBinds: if varName == sysUpTime.name: varBinds.append((varName, varVal)) break if not varBinds: varBinds.append((sysUpTime.name, sysUpTime.syntax.clone())) # for actual value snmpTrapOid, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpTrapOID') if len(notificationName) == 2: # ('MIB', 'symbol') notificationTypeObject, = contextMibInstrumCtl.mibBuilder.importSymbols(*notificationName) varBinds.append((snmpTrapOid.name, v2c.ObjectIdentifier(notificationTypeObject.name))) debug.logger & debug.flagApp and debug.logger('sendNotification: notification type object is %s' % notificationTypeObject) for notificationObject in notificationTypeObject.getObjects(): mibNode, = contextMibInstrumCtl.mibBuilder.importSymbols(*notificationObject) if instanceIndex: mibNode = mibNode.getNode(mibNode.name + instanceIndex) else: mibNode = mibNode.getNextNode(mibNode.name) varBinds.append((mibNode.name, mibNode.syntax)) debug.logger & debug.flagApp and debug.logger('sendNotification: processed notification object %s, instance index %s, var-bind %s' % (notificationObject, instanceIndex is None and "" or instanceIndex, mibNode)) elif notificationName: # numeric OID varBinds.append( (snmpTrapOid.name, snmpTrapOid.syntax.clone(notificationName)) ) else: varBinds.append((snmpTrapOid.name, snmpTrapOid.syntax)) for varName, varVal in additionalVarBinds: if varName in (sysUpTime.name, snmpTrapOid.name): continue try: snmpEngine.accessControlModel[self.acmID].isAccessAllowed( snmpEngine, securityModel, securityName, securityLevel, 'notify', contextName, varName ) except error.StatusInformation: debug.logger & debug.flagApp and debug.logger('sendNotification: OID %s not allowed for %s, droppping notification' % (varName, securityName)) return else: varBinds.append((varName, varVal)) # 3.3.4 if notifyType == 1: pdu = v2c.SNMPv2TrapPDU() elif notifyType == 2: pdu = v2c.InformRequestPDU() else: raise RuntimeError() v2c.apiPDU.setDefaults(pdu) v2c.apiPDU.setVarBinds(pdu, varBinds) # User-side API assumes SMIv2 if messageProcessingModel == 0: reqPDU = rfc2576.v2ToV1(pdu) pduVersion = 0 else: reqPDU = pdu pduVersion = 1 # 3.3.5 if notifyType == 1: try: snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, self.snmpContext.contextEngineId, contextName, pduVersion, reqPDU, None ) except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: metaSendPduHandle %s: sendPdu() failed with %r' % (metaSendPduHandle, statusInformation)) if not self.__pendingNotifications[metaSendPduHandle]: del self.__pendingNotifications[metaSendPduHandle] self._handleResponse( metaSendPduHandle, statusInformation['errorIndication'], 0, 0, (), cbFun, cbCtx ) return metaSendPduHandle else: # Convert timeout in seconds into timeout in timer ticks timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() # 3.3.6a try: sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, self.snmpContext.contextEngineId, contextName, pduVersion, reqPDU, 1, # expectResponse timeoutInTicks, self.processResponsePdu, (cbFun, cbCtx) ) except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: metaSendPduHandle %s: sendPdu() failed with %r' % (metaSendPduHandle, statusInformation)) if not self.__pendingNotifications[metaSendPduHandle]: del self.__pendingNotifications[metaSendPduHandle] self._handleResponse( metaSendPduHandle, statusInformation['errorIndication'], 0, 0, (), cbFun, cbCtx ) return metaSendPduHandle debug.logger & debug.flagApp and debug.logger('sendNotification: metaSendPduHandle %s, sendPduHandle %s, timeout %d' % (metaSendPduHandle, sendPduHandle, timeout)) # 3.3.6b self.__pendingReqs[sendPduHandle] = ( transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, self.snmpContext.contextEngineId, contextName, pdu, timeout, retryCount, 1, metaSendPduHandle ) if metaSendPduHandle not in self.__pendingNotifications: self.__pendingNotifications[metaSendPduHandle] = 0 self.__pendingNotifications[metaSendPduHandle] += 1 snmpEngine.transportDispatcher.jobStarted(id(self)) debug.logger & debug.flagApp and debug.logger('sendNotification: metaSendPduHandle %s, notification(s) sent' % metaSendPduHandle) return metaSendPduHandle # XXX # move/group/implement config setting/retrieval at a stand-alone module pysnmp-4.2.5/pysnmp/entity/rfc3413/cmdrsp.py0000644000076400001440000003227712220074471020774 0ustar ilyausers00000000000000import 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: 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 sendRsp(self, snmpEngine, stateReference, errorStatus, errorIndex, varBinds): ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, origPdu, maxSizeResponseScopedPDU, statusInformation ) = self.__pendingReqs[stateReference] debug.logger & debug.flagApp and debug.logger('sendRsp: stateReference %s, errorStatus %s, errorIndex %s, varBinds %s' % (stateReference, errorStatus, errorIndex, varBinds)) v2c.apiPDU.setErrorStatus(PDU, errorStatus) v2c.apiPDU.setErrorIndex(PDU, errorIndex) v2c.apiPDU.setVarBinds(PDU, varBinds) # Agent-side API complies with SMIv2 if messageProcessingModel == 0: PDU = rfc2576.v2ToV1(PDU, origPdu) # 3.2.6 try: snmpEngine.msgAndPduDsp.returnResponsePdu( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference, statusInformation ) except error.StatusInformation: debug.logger & debug.flagApp and debug.logger('sendRsp: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 _getRequestType = rfc1905.GetRequestPDU.tagSet _getNextRequestType = rfc1905.GetNextRequestPDU.tagSet _setRequestType = rfc1905.SetRequestPDU.tagSet _counter64Type = rfc1902.Counter64.tagSet def releaseStateInformation(self, stateReference): if stateReference in self.__pendingReqs: del self.__pendingReqs[stateReference] def processPdu( self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, maxSizeResponseScopedPDU, stateReference ): # Agent-side API complies with SMIv2 if messageProcessingModel == 0: origPdu = PDU PDU = rfc2576.v1ToV2(PDU) else: origPdu = None # 3.2.1 if PDU.tagSet not in rfc3411.readClassPDUs and \ PDU.tagSet not in rfc3411.writeClassPDUs: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) # 3.2.2 --> no-op # 3.2.4 rspPDU = v2c.apiPDU.getResponse(PDU) statusInformation = {} self.__pendingReqs[stateReference] = ( messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, rspPDU, origPdu, maxSizeResponseScopedPDU, statusInformation ) acCtx = ( snmpEngine, securityModel, securityName, securityLevel, contextName, PDU.getTagSet() ) # 3.2.5 varBinds = v2c.apiPDU.getVarBinds(PDU) errorStatus, errorIndex = 'noError', 0 debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) try: self.handleMgmtOperation( snmpEngine, stateReference, contextName, PDU, (self.__verifyAccess, acCtx) ) # SNMPv2 SMI exceptions except pysnmp.smi.error.GenError: errorIndication = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, errorIndication %s' % (stateReference, errorIndication)) if 'oid' in errorIndication: # Request REPORT generation statusInformation['oid'] = errorIndication['oid'] statusInformation['val'] = errorIndication['val'] # PDU-level SMI errors except pysnmp.smi.error.NoAccessError: errorStatus, errorIndex = 'noAccess', sys.exc_info()[1]['idx']+1 except pysnmp.smi.error.WrongTypeError: errorStatus, errorIndex = 'wrongType', sys.exc_info()[1]['idx']+1 except pysnmp.smi.error.WrongValueError: errorStatus, errorIndex = 'wrongValue', sys.exc_info()[1]['idx']+1 except pysnmp.smi.error.NoCreationError: errorStatus, errorIndex = 'noCreation', sys.exc_info()[1]['idx']+1 except pysnmp.smi.error.InconsistentValueError: errorStatus, errorIndex = 'inconsistentValue', sys.exc_info()[1]['idx']+1 except pysnmp.smi.error.ResourceUnavailableError: errorStatus, errorIndex = 'resourceUnavailable', sys.exc_info()[1]['idx']+1 except pysnmp.smi.error.CommitFailedError: errorStatus, errorIndex = '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 or 0 except pysnmp.error.PySnmpError: self.releaseStateInformation(stateReference) return else: # successful request processor must release state info return self.sendRsp( snmpEngine, stateReference, errorStatus, errorIndex, varBinds ) self.releaseStateInformation(stateReference) def __verifyAccess(self, name, syntax, idx, viewType, acCtx): (snmpEngine, securityModel, securityName, securityLevel, contextName, pduType) = acCtx try: snmpEngine.accessControlModel[self.acmID].isAccessAllowed( snmpEngine, securityModel, securityName, securityLevel, viewType, contextName, name ) # Map ACM errors onto SMI ones except error.StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) errorIndication = statusInformation['errorIndication'] # 3.2.5... if errorIndication == errind.noSuchView or \ errorIndication == errind.noAccessEntry or \ errorIndication == errind.noGroupName: raise pysnmp.smi.error.AuthorizationError( name=name, idx=idx ) elif errorIndication == errind.otherError: raise pysnmp.smi.error.GenError(name=name, idx=idx) elif errorIndication == errind.noSuchContext: snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-TARGET-MIB', 'snmpUnknownContexts') snmpUnknownContexts.syntax = snmpUnknownContexts.syntax + 1 # Request REPORT generation raise pysnmp.smi.error.GenError( name=name, idx=idx, oid=snmpUnknownContexts.name, val=snmpUnknownContexts.syntax ) elif errorIndication == errind.notInView: return 1 else: raise error.ProtocolError( 'Unknown ACM error %s' % errorIndication ) else: # rfc2576: 4.1.2.1 if securityModel == 1 and \ syntax is not None and \ self._counter64Type == syntax.getTagSet() and \ self._getNextRequestType == pduType: # This will cause MibTree to skip this OID-value raise pysnmp.smi.error.NoAccessError(name=name, idx=idx) class GetCommandResponder(CommandResponderBase): pduTypes = ( rfc1905.GetRequestPDU.tagSet, ) # rfc1905: 4.2.1 def handleMgmtOperation( self, snmpEngine, stateReference, contextName, PDU, acInfo ): (acFun, acCtx) = acInfo # rfc1905: 4.2.1.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readVars self.sendRsp( snmpEngine, stateReference, 0, 0, mgmtFun( v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) ) ) self.releaseStateInformation(stateReference) class NextCommandResponder(CommandResponderBase): pduTypes = ( rfc1905.GetNextRequestPDU.tagSet, ) # rfc1905: 4.2.2 def handleMgmtOperation( self, snmpEngine, stateReference, contextName, PDU, acInfo ): (acFun, acCtx) = acInfo # rfc1905: 4.2.2.1 mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars varBinds = v2c.apiPDU.getVarBinds(PDU) while 1: rspVarBinds = mgmtFun(varBinds, (acFun, acCtx)) try: self.sendRsp(snmpEngine, stateReference, 0, 0, rspVarBinds) except error.StatusInformation: idx = sys.exc_info()[1]['idx'] varBinds[idx] = (rspVarBinds[idx][0], varBinds[idx][1]) else: break self.releaseStateInformation(stateReference) class BulkCommandResponder(CommandResponderBase): pduTypes = ( rfc1905.GetBulkRequestPDU.tagSet, ) maxVarBinds = 64 # rfc1905: 4.2.3 def handleMgmtOperation( self, snmpEngine, stateReference, contextName, PDU, acInfo ): (acFun, acCtx) = acInfo nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU) if nonRepeaters < 0: nonRepeaters = 0 maxRepetitions = v2c.apiBulkPDU.getMaxRepetitions(PDU) if maxRepetitions < 0: maxRepetitions = 0 reqVarBinds = v2c.apiPDU.getVarBinds(PDU) N = min(int(nonRepeaters), len(reqVarBinds)) M = int(maxRepetitions) R = max(len(reqVarBinds)-N, 0) if R: M = min(M, self.maxVarBinds/R) debug.logger & debug.flagApp and debug.logger('handleMgmtOperation: N %d, M %d, R %d' % (N, M, R)) mgmtFun = self.snmpContext.getMibInstrum(contextName).readNextVars if N: rspVarBinds = mgmtFun(reqVarBinds[:N], (acFun, acCtx)) else: rspVarBinds = [] varBinds = reqVarBinds[-R:] while M and R: rspVarBinds.extend( mgmtFun(varBinds, (acFun, acCtx)) ) varBinds = rspVarBinds[-R:] M = M - 1 if len(rspVarBinds): self.sendRsp( snmpEngine, stateReference, 0, 0, rspVarBinds ) self.releaseStateInformation(stateReference) else: raise pysnmp.smi.error.SmiError() class SetCommandResponder(CommandResponderBase): pduTypes = ( rfc1905.SetRequestPDU.tagSet, ) # rfc1905: 4.2.5 def handleMgmtOperation( self, snmpEngine, stateReference, contextName, PDU, acInfo ): (acFun, acCtx) = acInfo mgmtFun = self.snmpContext.getMibInstrum(contextName).writeVars # rfc1905: 4.2.5.1-13 try: self.sendRsp( snmpEngine, stateReference, 0, 0, mgmtFun( v2c.apiPDU.getVarBinds(PDU), (acFun, acCtx) ) ) self.releaseStateInformation(stateReference) except ( pysnmp.smi.error.NoSuchObjectError, pysnmp.smi.error.NoSuchInstanceError ): e = pysnmp.smi.error.NotWritableError() e.update(sys.exc_info()[1]) raise e pysnmp-4.2.5/pysnmp/entity/rfc3413/ntfrcv.py0000644000076400001440000001024212153626041020773 0ustar ilyausers00000000000000import 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: pduTypes = ( v1.TrapPDU.tagSet, v2c.SNMPv2TrapPDU.tagSet, v2c.InformRequestPDU.tagSet ) def __init__(self, snmpEngine, cbFun, cbCtx=None): snmpEngine.msgAndPduDsp.registerContextEngineId( null, self.pduTypes, self.processPdu # '' is a wildcard ) self.__cbFunVer = 0 self.__cbFun = cbFun self.__cbCtx = cbCtx def close(self, snmpEngine): snmpEngine.msgAndPduDsp.unregisterContextEngineId( null, self.pduTypes ) 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) else: origPdu = None errorStatus = 'noError'; errorIndex = 0 varBinds = v2c.apiPDU.getVarBinds(PDU) debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds)) # 3.4 if PDU.tagSet in rfc3411.confirmedClassPDUs: # 3.4.1 --> no-op rspPDU = v2c.apiPDU.getResponse(PDU) # 3.4.2 v2c.apiPDU.setErrorStatus(rspPDU, errorStatus) v2c.apiPDU.setErrorIndex(rspPDU, errorIndex) v2c.apiPDU.setVarBinds(rspPDU, varBinds) debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, confirm PDU %s' % (stateReference, rspPDU.prettyPrint())) # Agent-side API complies with SMIv2 if messageProcessingModel == 0: rspPDU = rfc2576.v2ToV1(rspPDU, origPdu) statusInformation = {} # 3.4.3 try: snmpEngine.msgAndPduDsp.returnResponsePdu( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU, stateReference, statusInformation ) except error.StatusInformation: debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax = snmpSilentDrops.syntax + 1 elif PDU.tagSet in rfc3411.unconfirmedClassPDUs: pass else: raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet) debug.logger & debug.flagApp and debug.logger('processPdu: stateReference %s, user cbFun %s, cbCtx %s, varBinds %s' % (stateReference, self.__cbFun, self.__cbCtx, varBinds)) if self.__cbFunVer: self.__cbFun( snmpEngine, stateReference, contextEngineId, contextName, varBinds, self.__cbCtx ) else: # Compatibility stub (handle legacy cbFun interface) try: self.__cbFun( snmpEngine, contextEngineId, contextName, varBinds, self.__cbCtx ) except TypeError: self.__cbFunVer = 1 self.__cbFun( snmpEngine, stateReference, contextEngineId, contextName, varBinds, self.__cbCtx ) pysnmp-4.2.5/pysnmp/entity/rfc3413/cmdgen.py0000644000076400001440000005050212153626041020731 0ustar ilyausers00000000000000import 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(origVarBinds, varBinds): errorIndication = None idx = nonNulls = len(varBinds) rspVarBinds = [] while idx: idx = idx - 1 if varBinds[idx][1].tagSet in (rfc1905.NoSuchObject.tagSet, rfc1905.NoSuchInstance.tagSet, rfc1905.EndOfMibView.tagSet): nonNulls = nonNulls - 1 elif origVarBinds[idx][0].asTuple() >= varBinds[idx][0].asTuple(): errorIndication = errind.oidNotIncreasing rspVarBinds.insert(0, (varBinds[idx][0], __null)) if not nonNulls: rspVarBinds = [] return errorIndication, rspVarBinds class CommandGeneratorBase: _null = univ.Null('') def __init__(self): self.__pendingReqs = {} self.__SnmpEngineID, self.__SnmpAdminString = None, None def processResponsePdu( self, snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, PDU, statusInformation, sendPduHandle, cbInfo ): (cbFun, cbCtx) = cbInfo # 3.1.1 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, origSendRequestHandle ) = self.__pendingReqs[sendPduHandle] del self.__pendingReqs[sendPduHandle] snmpEngine.transportDispatcher.jobFinished(id(self)) # 3.1.3 if statusInformation: debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, statusInformation %s' % (sendPduHandle, statusInformation)) errorIndication = statusInformation['errorIndication'] # SNMP engine discovery will take extra retries, allow that if errorIndication in (errind.notInTimeWindow, errind.unknownEngineID) and \ origRetries == origRetryCount + 2 or \ errorIndication not in (errind.notInTimeWindow, errind.unknownEngineID) and \ origRetries == origRetryCount: debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, retry count %d exceeded' % (sendPduHandle, origRetries)) cbFun(origSendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return try: self._sendPdu( snmpEngine, origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPdu, origTimeout, origRetryCount, origRetries + 1, origSendRequestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % (sendPduHandle, statusInformation)) cbFun(origSendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return if origMessageProcessingModel != messageProcessingModel or \ origSecurityModel != securityModel or \ origSecurityName != origSecurityName or \ origContextEngineId and origContextEngineId != contextEngineId or \ origContextName and origContextName != contextName or \ origPduVersion != pduVersion: debug.logger & debug.flagApp and debug.logger('processResponsePdu: sendPduHandle %s, request/response data mismatch' % sendPduHandle) cbFun(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx) return # 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(origSendRequestHandle, 'badResponse', 0, 0, (), cbCtx) return self._handleResponse( snmpEngine, origTransportDomain, origTransportAddress, origMessageProcessingModel, origSecurityModel, origSecurityName, origSecurityLevel, origContextEngineId, origContextName, origPdu, origTimeout, origRetryCount, PDU, origSendRequestHandle, (cbFun, cbCtx), ) def sendReq( self, snmpEngine, addrName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName='' ): raise error.PySnmpError('Method not implemented') def _sendPdu( self, snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, reqPDU, timeout, retryCount, retries, sendRequestHandle, cbInfo ): (processResponsePdu, cbCtx) = cbInfo # Convert timeout in seconds into timeout in timer ticks timeoutInTicks = float(timeout)/100/snmpEngine.transportDispatcher.getTimerResolution() if not self.__SnmpEngineID or not self.__SnmpAdminString: self.__SnmpEngineID, self.__SnmpAdminString = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpEngineID', 'SnmpAdminString') # Cast possible strings into bytes if contextEngineId: contextEngineId = self.__SnmpEngineID(contextEngineId) contextName = self.__SnmpAdminString(contextName) origPDU = reqPDU # User-side API assumes SMIv2 if messageProcessingModel == 0: reqPDU = rfc2576.v2ToV1(reqPDU) pduVersion = 0 else: pduVersion = 1 # 3.1 sendPduHandle = snmpEngine.msgAndPduDsp.sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, reqPDU, 1, # expectResponse timeoutInTicks, processResponsePdu, cbCtx ) snmpEngine.transportDispatcher.jobStarted(id(self)) self.__pendingReqs[sendPduHandle] = ( transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, origPDU, timeout, retryCount, retries, sendRequestHandle ) debug.logger & debug.flagApp and debug.logger('_sendPdu: sendPduHandle %s, timeout %d*10 ms/%d ticks, retry %d of %d' % (sendPduHandle, timeout, timeoutInTicks, retries, retryCount)) def _handleResponse( self, snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, PDU, timeout, retryCount, rspPDU, sendRequestHandle, cbInfo ): (cbFun, cbCtx) = cbInfo cbFun(sendRequestHandle, None, v2c.apiPDU.getErrorStatus(rspPDU), v2c.apiPDU.getErrorIndex(rspPDU, muteErrors=True), v2c.apiPDU.getVarBinds(rspPDU), cbCtx) class GetCommandGenerator(CommandGeneratorBase): def sendReq( self, snmpEngine, addrName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName='' ): ( transportDomain, transportAddress, timeout, retryCount, messageProcessingModel, securityModel, securityName, securityLevel ) = config.getTargetInfo(snmpEngine, addrName) reqPDU = v2c.GetRequestPDU() v2c.apiPDU.setDefaults(reqPDU) v2c.apiPDU.setVarBinds(reqPDU, varBinds) requestHandle = getNextHandle() try: self._sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, reqPDU, timeout, retryCount, 0, # retries requestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: sendPduHandle %s: _sendPdu() failed with %r' % (requestHandle, statusInformation)) cbFun(requestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return requestHandle class SetCommandGenerator(CommandGeneratorBase): def sendReq( self, snmpEngine, addrName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName='' ): ( transportDomain, transportAddress, timeout, retryCount, messageProcessingModel, securityModel, securityName, securityLevel ) = config.getTargetInfo(snmpEngine, addrName) reqPDU = v2c.SetRequestPDU() v2c.apiPDU.setDefaults(reqPDU) v2c.apiPDU.setVarBinds(reqPDU, varBinds) requestHandle = getNextHandle() try: self._sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, reqPDU, timeout, retryCount, 0, # retries requestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: sendPduHandle %s: _sendPdu() failed with %r' % (requestHandle, statusInformation)) cbFun(requestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return requestHandle class NextCommandGeneratorSingleRun(CommandGeneratorBase): def sendReq( self, snmpEngine, addrName, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName='' ): ( transportDomain, transportAddress, timeout, retryCount, messageProcessingModel, securityModel, securityName, securityLevel ) = config.getTargetInfo(snmpEngine, addrName) reqPDU = v2c.GetNextRequestPDU() v2c.apiPDU.setDefaults(reqPDU) v2c.apiPDU.setVarBinds(reqPDU, varBinds) requestHandle = getNextHandle() try: self._sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, reqPDU, timeout, retryCount, 0, # retries requestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: sendPduHandle %s: _sendPdu() failed with %r' % (requestHandle, statusInformation)) cbFun(requestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return requestHandle class NextCommandGenerator(NextCommandGeneratorSingleRun): def _handleResponse( self, snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, PDU, timeout, retryCount, rspPDU, sendRequestHandle, cbInfo ): (cbFun, cbCtx) = cbInfo varBindTable = v2c.apiPDU.getVarBindTable(PDU, rspPDU) if v2c.apiPDU.getErrorStatus(rspPDU): errorIndication, varBinds = None, () elif not varBindTable: errorIndication, varBinds = errind.emptyResponse, () else: errorIndication, varBinds = getNextVarBinds( v2c.apiPDU.getVarBinds(PDU), varBindTable[-1] ) if not cbFun(sendRequestHandle, errorIndication, v2c.apiPDU.getErrorStatus(rspPDU), v2c.apiPDU.getErrorIndex(rspPDU, muteErrors=True), varBindTable, cbCtx): debug.logger & debug.flagApp and debug.logger('_handleResponse: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) return # app says enough if not varBinds: return # no more objects available v2c.apiPDU.setRequestID(PDU, v2c.getNextRequestID()) v2c.apiPDU.setVarBinds(PDU, varBinds) sendRequestHandle = getNextHandle() try: self._sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, PDU, timeout, retryCount, 0, # retries sendRequestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: sendPduHandle %s: _sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) cbFun(sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) class BulkCommandGeneratorSingleRun(CommandGeneratorBase): def sendReq( self, snmpEngine, addrName, nonRepeaters, maxRepetitions, varBinds, cbFun, cbCtx=None, contextEngineId=None, contextName='' ): ( transportDomain, transportAddress, timeout, retryCount, messageProcessingModel, securityModel, securityName, securityLevel ) = config.getTargetInfo(snmpEngine, addrName) reqPDU = v2c.GetBulkRequestPDU() v2c.apiBulkPDU.setDefaults(reqPDU) v2c.apiBulkPDU.setNonRepeaters(reqPDU, nonRepeaters) v2c.apiBulkPDU.setMaxRepetitions(reqPDU, maxRepetitions) v2c.apiBulkPDU.setVarBinds(reqPDU, varBinds) requestHandle = getNextHandle() try: self._sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, reqPDU, timeout, retryCount, 0, # retries requestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: sendPduHandle %s: _sendPdu() failed with %r' % (requestHandle, statusInformation)) cbFun(requestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) return requestHandle class BulkCommandGenerator(BulkCommandGeneratorSingleRun): def _handleResponse( self, snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, PDU, timeout, retryCount, rspPDU, sendRequestHandle, cbInfo ): (cbFun, cbCtx) = cbInfo varBindTable = v2c.apiBulkPDU.getVarBindTable(PDU, rspPDU) if v2c.apiBulkPDU.getErrorStatus(rspPDU): errorIndication, varBinds = None, () elif not varBindTable: errorIndication, varBinds = errind.emptyResponse, () else: errorIndication, varBinds = getNextVarBinds( v2c.apiBulkPDU.getVarBinds(PDU), varBindTable[-1] ) if not cbFun(sendRequestHandle, errorIndication, v2c.apiBulkPDU.getErrorStatus(rspPDU), v2c.apiBulkPDU.getErrorIndex(rspPDU, muteErrors=True), varBindTable, cbCtx): debug.logger & debug.flagApp and debug.logger('_handleResponse: sendRequestHandle %s, app says to stop walking' % sendRequestHandle) return # app says enough if not varBinds: return # no more objects available v2c.apiBulkPDU.setRequestID(PDU, v2c.getNextRequestID()) v2c.apiBulkPDU.setVarBinds(PDU, varBinds) sendRequestHandle = getNextHandle() try: self._sendPdu( snmpEngine, transportDomain, transportAddress, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, PDU, timeout, retryCount, 0, # retries sendRequestHandle, (self.processResponsePdu, (cbFun, cbCtx)) ) except StatusInformation: statusInformation = sys.exc_info()[1] debug.logger & debug.flagApp and debug.logger('sendReq: sendPduHandle %s: _sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) cbFun(sendRequestHandle, statusInformation['errorIndication'], 0, 0, (), cbCtx) pysnmp-4.2.5/pysnmp/entity/rfc3413/twisted/0000755000076400001440000000000012222743671020611 5ustar ilyausers00000000000000pysnmp-4.2.5/pysnmp/entity/rfc3413/twisted/__init__.py0000644000076400001440000000007311775060103022714 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/entity/rfc3413/twisted/ntforg.py0000644000076400001440000000152512153626041022457 0ustar ilyausers00000000000000from twisted.internet import defer from pysnmp.entity.rfc3413 import ntforg from pyasn1.compat.octets import null def _cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx.callback((errorIndication, errorStatus, errorIndex, varBinds)) class NotificationOriginator(ntforg.NotificationOriginator): def sendNotification( self, snmpEngine, notificationTarget, notificationName, additionalVarBinds=None, contextName=null ): df = defer.Deferred() ntforg.NotificationOriginator.sendNotification( self, snmpEngine, notificationTarget, notificationName, additionalVarBinds, _cbFun, df, contextName=null ) return df pysnmp-4.2.5/pysnmp/entity/rfc3413/twisted/cmdgen.py0000644000076400001440000000561011655706725022432 0ustar ilyausers00000000000000from twisted.internet import defer from pysnmp.entity.rfc3413 import cmdgen from pyasn1.compat.octets import null def _cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx.callback((errorIndication, errorStatus, errorIndex, varBinds)) class GetCommandGenerator(cmdgen.GetCommandGenerator): def sendReq( self, snmpEngine, addrName, varBinds, contextEngineId=None, contextName=null ): df = defer.Deferred() cmdgen.GetCommandGenerator.sendReq( self, snmpEngine, addrName, varBinds, _cbFun, df, contextEngineId, contextName ) return df class SetCommandGenerator(cmdgen.SetCommandGenerator): def sendReq( self, snmpEngine, addrName, varBinds, contextEngineId=None, contextName=null ): df = defer.Deferred() cmdgen.SetCommandGenerator.sendReq( self, snmpEngine, addrName, varBinds, _cbFun, df, contextEngineId, contextName ) return df def _cbFunWithDeferred(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): df = cbCtx['df'] df.callback( (errorIndication, errorStatus, errorIndex, varBinds) ) # Callback function may return another deferred to indicate # it wishes to continue MIB walk. if isinstance(df.result, defer.Deferred): cbCtx['df'] = df.result return 1 # continue walking class NextCommandGenerator(cmdgen.NextCommandGenerator): def sendReq( self, snmpEngine, addrName, varBinds, contextEngineId=None, contextName=null ): df = defer.Deferred() cmdgen.NextCommandGenerator.sendReq( self, snmpEngine, addrName, varBinds, _cbFunWithDeferred, { 'df': df }, # anonymous dictionary used for cbCtx contextEngineId, contextName ) return df class BulkCommandGenerator(cmdgen.BulkCommandGenerator): def sendReq( self, snmpEngine, addrName, nonRepeaters, maxRepetitions, varBinds, contextEngineId=None, contextName=null ): df = defer.Deferred() cmdgen.BulkCommandGenerator.sendReq( self, snmpEngine, addrName, nonRepeaters, maxRepetitions, varBinds, _cbFunWithDeferred, { 'df': df }, # anonymous dictionary used for cbCtx contextEngineId=None, contextName=null ) return df pysnmp-4.2.5/pysnmp/entity/rfc3413/mibvar.py0000644000076400001440000000524612011756757020774 0ustar ilyausers00000000000000# # THESE FUNCTIONS ARE OBSOLETE AND MUST NOT BE USED! # USE pysnmp.entity.rfc3413.oneliner.mibvar INSTEAD # # MIB variable pretty printers/parsers from pyasn1.type import univ from pysnmp.smi.error import NoSuchObjectError # Name def mibNameToOid(mibView, name): if isinstance(name[0], tuple): f = lambda x='',y='': (x,y) modName, symName = f(*name[0]) if modName: # load module if needed mibView.mibBuilder.loadModules(modName) else: mibView.mibBuilder.loadModules() # load all (slow) if symName: oid, label, suffix = mibView.getNodeNameByDesc(symName, modName) else: oid, label, suffix = mibView.getFirstNodeName(modName) suffix = name[1:] modName, symName, _s = mibView.getNodeLocation(oid) mibNode, = mibView.mibBuilder.importSymbols( modName, symName ) if hasattr(mibNode, 'createTest'): # table column XXX modName, symName, _s = mibView.getNodeLocation(oid[:-1]) rowNode, = mibView.mibBuilder.importSymbols(modName, symName) return oid, rowNode.getInstIdFromIndices(*suffix) else: # scalar or incomplete spec return oid, suffix elif not isinstance(name, tuple): name = tuple(univ.ObjectIdentifier(name)) oid, label, suffix = mibView.getNodeNameByOid(name) return oid, suffix __scalarSuffix = (univ.Integer(0),) def oidToMibName(mibView, oid): if not isinstance(oid, tuple): oid = tuple(univ.ObjectIdentifier(oid)) _oid, label, suffix = mibView.getNodeNameByOid(oid) modName, symName, __suffix = mibView.getNodeLocation(_oid) mibNode, = mibView.mibBuilder.importSymbols( modName, symName ) if hasattr(mibNode, 'createTest'): # table column __modName, __symName, __s = mibView.getNodeLocation(_oid[:-1]) rowNode, = mibView.mibBuilder.importSymbols(__modName, __symName) return (symName, modName), rowNode.getIndicesFromInstId(suffix) elif not suffix: # scalar return (symName, modName), suffix elif suffix == (0,): # scalar return (symName, modName), __scalarSuffix else: raise NoSuchObjectError( str='No MIB 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.2.5/pysnmp/entity/__init__.py0000644000076400001440000000007311775060106020147 0ustar ilyausers00000000000000# This file is necessary to make this directory a package. pysnmp-4.2.5/pysnmp/entity/config.py0000644000076400001440000006555412220132230017654 0ustar ilyausers00000000000000# Initial SNMP engine configuration functions. During further operation, # SNMP engine might be configured remotely (through SNMP). from pyasn1.compat.octets import null from pysnmp.carrier.asynsock.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.eso.priv import des3, aes192, aes256 from pysnmp import error # 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 usmNoAuthProtocol = noauth.NoAuth.serviceID # Privacy protocol usmDESPrivProtocol = des.Des.serviceID usm3DESEDEPrivProtocol = des3.Des3.serviceID usmAesCfb128Protocol = aes.Aes.serviceID usmAesCfb192Protocol = aes192.Aes192.serviceID usmAesCfb256Protocol = aes256.Aes256.serviceID usmNoPrivProtocol = nopriv.NoPriv.serviceID # Auth services authServices = { hmacmd5.HmacMd5.serviceID: hmacmd5.HmacMd5(), hmacsha.HmacSha.serviceID: hmacsha.HmacSha(), noauth.NoAuth.serviceID: noauth.NoAuth() } # Privacy services privServices = { des.Des.serviceID: des.Des(), des3.Des3.serviceID: des3.Des3(), aes.Aes.serviceID: aes.Aes(), aes192.Aes192.serviceID: aes192.Aes192(), aes256.Aes256.serviceID: aes256.Aes256(), nopriv.NoPriv.serviceID: nopriv.NoPriv() } def __cookV1SystemInfo(snmpEngine, communityIndex): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') snmpCommunityEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.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 snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (8,) + tblIdx, 'createAndGo'), (snmpCommunityEntry.name + (1,) + tblIdx, communityIndex), (snmpCommunityEntry.name + (2,) + tblIdx, communityName), (snmpCommunityEntry.name + (3,) + tblIdx, securityName is not None and securityName or communityIndex), (snmpCommunityEntry.name + (4,) + tblIdx, contextEngineId), (snmpCommunityEntry.name + (5,) + tblIdx, contextName), (snmpCommunityEntry.name + (6,) + tblIdx, transportTag), (snmpCommunityEntry.name + (7,) + tblIdx, 'nonVolatile')) ) def delV1System(snmpEngine, communityIndex): snmpCommunityEntry, tblIdx, snmpEngineID = __cookV1SystemInfo( snmpEngine, communityIndex ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpCommunityEntry.name + (8,) + tblIdx, 'destroy'),) ) def __cookV3UserInfo(snmpEngine, securityName, securityEngineId): snmpEngineID, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if securityEngineId is None: snmpEngineID = snmpEngineID.syntax else: snmpEngineID = snmpEngineID.syntax.clone(securityEngineId) usmUserEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-USER-BASED-SM-MIB', 'usmUserEntry') tblIdx1 = usmUserEntry.getInstIdFromIndices( snmpEngineID, securityName ) pysnmpUsmSecretEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmSecretEntry') tblIdx2 = pysnmpUsmSecretEntry.getInstIdFromIndices(securityName) return snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 def addV3User(snmpEngine, userName, authProtocol=usmNoAuthProtocol, authKey=None, privProtocol=usmNoPrivProtocol, privKey=None, securityEngineId=None, securityName=None, # deprecated parameters follow contextEngineId=None): if securityName is None: securityName = userName if securityEngineId is None: # backward compatibility securityEngineId = contextEngineId ( snmpEngineID, usmUserEntry, tblIdx1, pysnmpUsmSecretEntry, tblIdx2 ) = __cookV3UserInfo( snmpEngine, userName, securityEngineId ) # Load augmenting table before creating new row in base one pysnmpUsmKeyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('PYSNMP-USM-MIB', 'pysnmpUsmKeyEntry') # Load clone-from (may not be needed) zeroDotZero, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-SMI', 'zeroDotZero') snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((usmUserEntry.name + (13,) + tblIdx1, 'createAndGo'), (usmUserEntry.name + (2,) + tblIdx1, userName), (usmUserEntry.name + (3,) + tblIdx1, securityName), (usmUserEntry.name + (4,) + tblIdx1, zeroDotZero.name), (usmUserEntry.name + (5,) + tblIdx1, authProtocol), (usmUserEntry.name + (8,) + tblIdx1, privProtocol)) ) # Localize keys if authProtocol in authServices: hashedAuthPassphrase = authServices[authProtocol].hashPassphrase( authKey and authKey or null ) localAuthKey = authServices[authProtocol].localizeKey( hashedAuthPassphrase, snmpEngineID ) else: raise error.PySnmpError('Unknown auth protocol %s' % (authProtocol,)) if privProtocol in privServices: hashedPrivPassphrase = privServices[privProtocol].hashPassphrase( authProtocol, privKey and privKey or null ) localPrivKey = privServices[privProtocol].localizeKey( authProtocol, hashedPrivPassphrase, snmpEngineID ) else: raise error.PySnmpError( 'Unknown priv protocol %s' % (privProtocol,) ) # Commit localized keys snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmKeyEntry.name + (1,) + tblIdx1, localAuthKey), (pysnmpUsmKeyEntry.name + (2,) + tblIdx1, localPrivKey), (pysnmpUsmKeyEntry.name + (3,) + tblIdx1, hashedAuthPassphrase), (pysnmpUsmKeyEntry.name + (4,) + tblIdx1, hashedPrivPassphrase)) ) # Commit passphrases snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((pysnmpUsmSecretEntry.name + (4,) + tblIdx2, 'createAndGo'), (pysnmpUsmSecretEntry.name + (2,) + tblIdx2, authKey), (pysnmpUsmSecretEntry.name + (3,) + tblIdx2, privKey),) ) def delV3User(snmpEngine, userName, securityEngineId=None, # deprecated parameters follow contextEngineId=None): if securityEngineId is None: # backward compatibility securityEngineId = contextEngineId ( snmpEngineID, 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'),) ) # 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][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): snmpTargetParamsEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetParamsEntry') tblIdx = snmpTargetParamsEntry.getInstIdFromIndices(name) return snmpTargetParamsEntry, tblIdx def addTargetParams( snmpEngine, name, securityName, securityLevel, mpModel=3 # 0 == SNMPv1, 1 == SNMPv2c, 3 == SNMPv3 ): if mpModel == 0: securityModel = 1 elif mpModel == 1 or mpModel == 2: securityModel = 2 elif mpModel == 3: securityModel = 3 else: raise error.PySnmpError('Unknown MP model %s' % mpModel) snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo(snmpEngine, name) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'createAndGo'), (snmpTargetParamsEntry.name + (1,) + tblIdx, name), (snmpTargetParamsEntry.name + (2,) + tblIdx, mpModel), (snmpTargetParamsEntry.name + (3,) + tblIdx, securityModel), (snmpTargetParamsEntry.name + (4,) + tblIdx, securityName), (snmpTargetParamsEntry.name + (5,) + tblIdx, securityLevel)) ) def delTargetParams(snmpEngine, name): snmpTargetParamsEntry, tblIdx = __cookTargetParamsInfo( snmpEngine, name ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetParamsEntry.name + (7,) + tblIdx, 'destroy'),) ) def __cookTargetAddrInfo(snmpEngine, addrName): snmpTargetAddrEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-TARGET-MIB', 'snmpTargetAddrEntry') tblIdx = snmpTargetAddrEntry.getInstIdFromIndices(addrName) return snmpTargetAddrEntry, tblIdx def addTargetAddr( snmpEngine, addrName, transportDomain, transportAddress, params, timeout=None, retryCount=None, tagList=null ): snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo( snmpEngine, addrName ) if transportDomain[:len(snmpUDPDomain)] == snmpUDPDomain: SnmpUDPAddress, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMPv2-TM', 'SnmpUDPAddress') transportAddress = SnmpUDPAddress(transportAddress) elif transportDomain[:len(snmpUDP6Domain)] == snmpUDP6Domain: TransportAddressIPv6, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('TRANSPORT-ADDRESS-MIB', 'TransportAddressIPv6') transportAddress = TransportAddressIPv6(transportAddress) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'createAndGo'), (snmpTargetAddrEntry.name + (1,) + tblIdx, addrName), (snmpTargetAddrEntry.name + (2,) + tblIdx, transportDomain), (snmpTargetAddrEntry.name + (3,) + tblIdx, transportAddress), (snmpTargetAddrEntry.name + (4,) + tblIdx, timeout), (snmpTargetAddrEntry.name + (5,) + tblIdx, retryCount), (snmpTargetAddrEntry.name + (6,) + tblIdx, tagList), (snmpTargetAddrEntry.name + (7,) + tblIdx, params),) ) def delTargetAddr(snmpEngine, addrName): snmpTargetAddrEntry, tblIdx = __cookTargetAddrInfo( snmpEngine, addrName ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpTargetAddrEntry.name + (9,) + tblIdx, 'destroy'),) ) def 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.cache['automaticTransportDispatcher'] = 0 snmpEngine.transportDispatcher.registerTransport( transportDomain, transport ) if 'automaticTransportDispatcher' in snmpEngine.cache: snmpEngine.cache['automaticTransportDispatcher'] += 1 def delTransport(snmpEngine, transportDomain): if not snmpEngine.transportDispatcher: return snmpEngine.transportDispatcher.unregisterTransport(transportDomain) # automatically shutdown automatically created transportDispatcher if 'automaticTransportDispatcher' in snmpEngine.cache: snmpEngine.cache['automaticTransportDispatcher'] -= 1 if not snmpEngine.cache['automaticTransportDispatcher']: snmpEngine.transportDispatcher.closeDispatcher() snmpEngine.unregisterTransportDispatcher() del snmpEngine.cache['automaticTransportDispatcher'] addSocketTransport = addTransport delSocketTransport = delTransport # VACM shortcuts def addContext(snmpEngine, contextName): vacmContextEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmContextEntry' ) tblIdx = vacmContextEntry.getInstIdFromIndices(contextName) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmContextEntry.name + (1,) + tblIdx, contextName),) ) def __cookVacmGroupInfo(snmpEngine, securityModel, securityName): vacmSecurityToGroupEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmSecurityToGroupEntry' ) tblIdx = vacmSecurityToGroupEntry.getInstIdFromIndices( securityModel, securityName ) return vacmSecurityToGroupEntry, tblIdx def addVacmGroup(snmpEngine, groupName, securityModel, securityName): vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( snmpEngine, securityModel, securityName ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'createAndGo'), (vacmSecurityToGroupEntry.name + (1,) + tblIdx, securityModel), (vacmSecurityToGroupEntry.name + (2,) + tblIdx, securityName), (vacmSecurityToGroupEntry.name + (3,) + tblIdx, groupName),) ) def delVacmGroup(snmpEngine, securityModel, securityName): vacmSecurityToGroupEntry, tblIdx = __cookVacmGroupInfo( snmpEngine, securityModel, securityName ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmSecurityToGroupEntry.name + (5,) + tblIdx, 'destroy'),) ) def __cookVacmAccessInfo(snmpEngine, groupName, contextName, securityModel, securityLevel): vacmAccessEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmAccessEntry' ) tblIdx = vacmAccessEntry.getInstIdFromIndices( groupName, contextName, securityModel, securityLevel ) return vacmAccessEntry, tblIdx def addVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel, prefix, readView, writeView, notifyView): vacmAccessEntry, tblIdx = __cookVacmAccessInfo( snmpEngine, groupName, contextName, securityModel, securityLevel ) addContext(snmpEngine, contextName) # this is leaky snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'createAndGo'), (vacmAccessEntry.name + (1,) + tblIdx, contextName), (vacmAccessEntry.name + (2,) + tblIdx, securityModel), (vacmAccessEntry.name + (3,) + tblIdx, securityLevel), (vacmAccessEntry.name + (4,) + tblIdx, prefix), (vacmAccessEntry.name + (5,) + tblIdx, readView), (vacmAccessEntry.name + (6,) + tblIdx, writeView), (vacmAccessEntry.name + (7,) + tblIdx, notifyView),) ) def delVacmAccess(snmpEngine, groupName, contextName, securityModel, securityLevel): vacmAccessEntry, tblIdx = __cookVacmAccessInfo( snmpEngine, groupName, contextName, securityModel, securityLevel ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmAccessEntry.name + (9,) + tblIdx, 'destroy'),) ) def __cookVacmViewInfo(snmpEngine, viewName, subTree): vacmViewTreeFamilyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols( 'SNMP-VIEW-BASED-ACM-MIB', 'vacmViewTreeFamilyEntry' ) tblIdx = vacmViewTreeFamilyEntry.getInstIdFromIndices( viewName, subTree ) return vacmViewTreeFamilyEntry, tblIdx def addVacmView(snmpEngine, viewName, viewType, subTree, mask): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( snmpEngine, viewName, subTree ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'createAndGo'), (vacmViewTreeFamilyEntry.name + (1,) + tblIdx, viewName), (vacmViewTreeFamilyEntry.name + (2,) + tblIdx, subTree), (vacmViewTreeFamilyEntry.name + (3,) + tblIdx, mask), (vacmViewTreeFamilyEntry.name + (4,) + tblIdx, viewType),) ) def delVacmView(snmpEngine, viewName, subTree): vacmViewTreeFamilyEntry, tblIdx = __cookVacmViewInfo( snmpEngine, viewName, subTree ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((vacmViewTreeFamilyEntry.name + (6,) + tblIdx, 'destroy'),) ) # VACM simplicity wrappers def __cookVacmUserInfo(snmpEngine, securityModel, securityName, securityLevel): groupName = 'v-%s-%d' % (hash(securityName), securityModel) SnmpSecurityLevel, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpSecurityLevel') securityLevel = SnmpSecurityLevel(securityLevel) return ( groupName, securityLevel, 'r' + groupName, 'w' + groupName, 'n' + groupName ) def addVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=(), contextName=null): ( groupName, securityLevel, readView, writeView, notifyView ) = __cookVacmUserInfo( snmpEngine, securityModel, securityName, securityLevel, ) addVacmGroup( snmpEngine, groupName, securityModel, securityName ) addVacmAccess( snmpEngine, groupName, contextName, securityModel, securityLevel, 1, readView, writeView, notifyView ) if readSubTree: addVacmView( snmpEngine, readView, "included", readSubTree, null, ) if writeSubTree: addVacmView( snmpEngine, writeView, "included", writeSubTree, null, ) if notifySubTree: addVacmView( snmpEngine, notifyView, "included", notifySubTree, null, ) def delVacmUser(snmpEngine, securityModel, securityName, securityLevel, readSubTree=(), writeSubTree=(), notifySubTree=()): ( groupName, securityLevel, readView, writeView, notifyView ) = __cookVacmUserInfo( snmpEngine, securityModel, securityName, securityLevel, ) delVacmGroup( snmpEngine, securityModel, securityName ) delVacmAccess( snmpEngine, groupName, null, securityModel, securityLevel ) if readSubTree: delVacmView( snmpEngine, readView, readSubTree ) if writeSubTree: delVacmView( snmpEngine, writeView, writeSubTree ) if notifySubTree: delVacmView( snmpEngine, notifyView, notifySubTree ) # Obsolete shortcuts for add/delVacmUser() wrappers def addRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser( snmpEngine, securityModel, securityName, securityLevel, subTree ) def delRoUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser( snmpEngine, securityModel, securityName, securityLevel, subTree ) def addRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): addVacmUser( snmpEngine, securityModel, securityName, securityLevel, subTree, subTree ) def delRwUser(snmpEngine, securityModel, securityName, securityLevel, subTree): delVacmUser( snmpEngine, securityModel, securityName, securityLevel, subTree, subTree ) def addTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): addVacmUser( snmpEngine, securityModel, securityName, securityLevel, (), (), subTree, ) def delTrapUser(snmpEngine,securityModel,securityName,securityLevel,subTree): delVacmUser( snmpEngine, securityModel, securityName, securityLevel, (), (), subTree, ) # Notification target setup def __cookNotificationTargetInfo(snmpEngine, notificationName, paramsName, filterSubtree=None): snmpNotifyEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyEntry') tblIdx1 = snmpNotifyEntry.getInstIdFromIndices( notificationName ) snmpNotifyFilterProfileEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterProfileEntry') tblIdx2 = snmpNotifyFilterProfileEntry.getInstIdFromIndices( paramsName ) profileName = '%s-filter' % hash(notificationName) if filterSubtree: snmpNotifyFilterEntry, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('SNMP-NOTIFICATION-MIB', 'snmpNotifyFilterEntry') tblIdx3 = snmpNotifyFilterEntry.getInstIdFromIndices( profileName, filterSubtree ) else: snmpNotifyFilterEntry = tblIdx3 = None return ( snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, tblIdx3 ) def addNotificationTarget(snmpEngine, notificationName, paramsName, transportTag, notifyType=None, filterSubtree=None, filterMask=None, filterType=None): ( snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( snmpEngine, notificationName, paramsName, filterSubtree ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyEntry.name + (5,) + tblIdx1, 'createAndGo'), (snmpNotifyEntry.name + (2,) + tblIdx1, transportTag), (snmpNotifyEntry.name + (3,) + tblIdx1, notifyType),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'createAndGo'), (snmpNotifyFilterProfileEntry.name + (1,) + tblIdx2, profileName),) ) if not snmpNotifyFilterEntry: return snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'createAndGo'), (snmpNotifyFilterEntry.name + (1,) + tblIdx3, filterSubtree), (snmpNotifyFilterEntry.name + (2,) + tblIdx3, filterMask), (snmpNotifyFilterEntry.name + (3,) + tblIdx3, filterType),) ) def delNotificationTarget(snmpEngine, notificationName, paramsName, filterSubtree=None): ( snmpNotifyEntry, tblIdx1, snmpNotifyFilterProfileEntry, tblIdx2, profileName, snmpNotifyFilterEntry, tblIdx3 ) = __cookNotificationTargetInfo( snmpEngine, notificationName, paramsName, filterSubtree ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyEntry.name + (5,) + tblIdx1, 'destroy'),) ) snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterProfileEntry.name + (3,) + tblIdx2, 'destroy'),) ) if not snmpNotifyFilterEntry: return snmpEngine.msgAndPduDsp.mibInstrumController.writeVars( ((snmpNotifyFilterEntry.name + (5,) + tblIdx3, 'destroy'),) ) # rfc3415: A.1 def setInitialVacmParameters(snmpEngine): # rfc3415: A.1.1 --> initial-semi-security-configuration # rfc3415: A.1.2 addContext(snmpEngine, "") # rfc3415: A.1.3 addVacmGroup(snmpEngine, "initial", 3, "initial") # rfc3415: A.1.4 addVacmAccess(snmpEngine, "initial", "", 3, "noAuthNoPriv", "exact", "restricted", None, "restricted") addVacmAccess(snmpEngine, "initial", "", 3, "authNoPriv", "exact", "internet", "internet", "internet") addVacmAccess(snmpEngine, "initial", "", 3, "authPriv", "exact", "internet", "internet", "internet") # rfc3415: A.1.5 (semi-secure) addVacmView(snmpEngine, "internet", "included", (1,3,6,1),"") addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,2,1,1),"") addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,2,1,11),"") addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,10,2,1),"") addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,11,2,1),"") addVacmView(snmpEngine, "restricted", "included", (1,3,6,1,6,3,15,1,1),"") pysnmp-4.2.5/pysnmp/entity/engine.py0000644000076400001440000001017612215400600017645 0ustar ilyausers00000000000000# SNMP engine from pysnmp.proto.rfc3412 import MsgAndPduDispatcher from pysnmp.proto.mpmod.rfc2576 import SnmpV1MessageProcessingModel, \ SnmpV2cMessageProcessingModel from pysnmp.proto.mpmod.rfc3412 import SnmpV3MessageProcessingModel from pysnmp.proto.secmod.rfc2576 import SnmpV1SecurityModel, \ SnmpV2cSecurityModel from pysnmp.proto.secmod.rfc3414 import SnmpUSMSecurityModel from pysnmp.proto.acmod import rfc3415, void from pysnmp import error class SnmpEngine: def __init__(self, snmpEngineID=None, maxMessageSize=65507, msgAndPduDsp=None): self.cache = {} 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 = snmpEngineBoots.syntax + 1 origSnmpEngineID, = self.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMP-FRAMEWORK-MIB', 'snmpEngineID') if snmpEngineID is not None: origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID) self.snmpEngineID = origSnmpEngineID.syntax # 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 pysnmp-4.2.5/setup.py0000644000076400001440000001005312220277430014701 0ustar ilyausers00000000000000#!/usr/bin/env python """SNMP library for Python SNMP v1/v2c/v3 engine and apps written in pure-Python. Supports Manager/Agent/Proxy roles, scriptable MIBs, asynchronous operation and multiple transports. """ import sys import os 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 :: 3 Topic :: Communications Topic :: Software Development :: Libraries :: Python Modules 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 (as root on Linux): wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/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) try: from setuptools import setup params = { 'install_requires': [ 'pyasn1>=0.1.2' ], 'zip_safe': True } if sys.platform.lower()[:3] != 'win': params['install_requires'].append('pycrypto>=2.4.1') except ImportError: for arg in sys.argv: if 'egg' in arg: howto_install_setuptools() sys.exit(1) from distutils.core import setup params = {} if sys.version_info[:2] > (2, 4): params['requires'] = [ 'pyasn1(>=0.1.2)' ] if sys.platform.lower()[:3] != 'win': params['requires'].append('pycrypto(>=2.4.1)') if sys.platform.lower()[:3] == 'win': try: import Crypto except ImportError: sys.stderr.write("""WARNING! WARNING! WARNING! PyCrypto binaries are required for SNMPv3 encryption to work. You may wish to grab them from http://www.voidspace.org.uk/python/modules.shtml and install into your system. """) doclines = [ x.strip() for x in __doc__.split('\n') if x ] params.update( { 'name': 'pysnmp', 'version': open(os.path.join('pysnmp','__init__.py')).read().split('\'')[1], 'description': doclines[0], 'long_description': ' '.join(doclines[1:]), 'maintainer': 'Ilya Etingof ', 'author': 'Ilya Etingof', 'author_email': 'ilya@glas.net', 'url': 'http://sourceforge.net/projects/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.twisted', 'pysnmp.carrier.twisted.dgram', 'pysnmp.entity', 'pysnmp.entity.rfc3413', 'pysnmp.entity.rfc3413.oneliner', 'pysnmp.entity.rfc3413.twisted', 'pysnmp.proto', 'pysnmp.proto.mpmod', 'pysnmp.proto.secmod', 'pysnmp.proto.secmod.rfc3414', 'pysnmp.proto.secmod.rfc3414.auth', 'pysnmp.proto.secmod.rfc3414.priv', 'pysnmp.proto.secmod.rfc3826', 'pysnmp.proto.secmod.rfc3826.priv', 'pysnmp.proto.secmod.eso', 'pysnmp.proto.secmod.eso.priv', 'pysnmp.proto.acmod', 'pysnmp.proto.proxy', 'pysnmp.proto.api' ], 'scripts': [ os.path.join('tools','libsmi2pysnmp'), os.path.join('tools', 'build-pysnmp-mib') ] } ) setup(**params) pysnmp-4.2.5/examples/0000755000076400001440000000000012222743671015015 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/0000755000076400001440000000000012222743671016203 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/0000755000076400001440000000000012222743671020016 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/agent/0000755000076400001440000000000012222743671021114 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/0000755000076400001440000000000012222743671022413 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/trap-v1-with-custom-values.py0000644000076400001440000000204312063714267030036 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification using the following options: # # * 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' # from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 ntfOrg = ntforg.NotificationOriginator() errorIndication = ntfOrg.sendNotification( ntforg.CommunityData('public', mpModel=0), ntforg.UdpTransportTarget(('localhost', 162)), 'trap', '1.3.6.1.4.1.20408.4.1.1.2.0.432', ('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', rfc1902.OctetString('my system')) ) if errorIndication: print('Notification not sent: %s' % errorIndication) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/trap-async-multiple-transports-and-protocols.py0000644000076400001440000000226712071650011033670 0ustar ilyausers00000000000000# # Notification Originator # # Send multiple SNMP notifications using the following options: # # * 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 # from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 # List of targets in the followin format: # ( ( authData, transportTarget ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) ( ntforg.CommunityData('public', mpModel=0), ntforg.UdpTransportTarget(('localhost', 162)) ), # 2-nd target (SNMPv2c over IPv4/UDP) ( ntforg.CommunityData('public'), ntforg.UdpTransportTarget(('localhost', 162)) ) ) ntfOrg = ntforg.AsynNotificationOriginator() for authData, transportTarget in targets: ntfOrg.sendNotification( authData, transportTarget, 'trap', ntforg.MibVariable('SNMPv2-MIB', 'coldStart'), ( ( rfc1902.ObjectName('1.3.6.1.2.1.1.1.0'), rfc1902.OctetString('my name') ), ) ) ntfOrg.snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/inform-v3-with-custom-contextengineid.py0000644000076400001440000000255112063714266032257 0ustar ilyausers00000000000000# # Notification Originator # # 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. # from pysnmp.entity import engine from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 snmpEngine = engine.SnmpEngine() snmpContext = context.SnmpContext( snmpEngine,contextEngineId=rfc1902.OctetString(hexValue='8000000004030201') ) ntfOrg = ntforg.NotificationOriginator(snmpEngine, snmpContext) errorIndication, errorStatus, errorIndex, varBinds = ntfOrg.sendNotification( ntforg.UsmUserData('usr-md5-none', 'authkey1'), ntforg.UdpTransportTarget(('localhost', 162)), 'inform', '1.3.6.1.6.3.1.1.5.2' ) if errorIndication: print('Notification not sent: %s' % errorIndication) elif errorStatus: print('Notification Receiver returned error: %s @%s' % (errorStatus, errorIndex)) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/trap-v2c-with-mib-lookup.py0000644000076400001440000000133312063714267027452 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification using the following options: # # * SNMPv2c # * with community name 'public' # * over IPv4/UDP # * send TRAP notification # * with TRAP ID 'coldStart' specified as a MIB symbol # * include managed object information specified as a MIB symbol # from pysnmp.entity.rfc3413.oneliner import ntforg ntfOrg = ntforg.NotificationOriginator() errorIndication = ntfOrg.sendNotification( ntforg.CommunityData('public'), ntforg.UdpTransportTarget(('localhost', 162)), 'trap', ntforg.MibVariable('SNMPv2-MIB', 'coldStart'), ( ntforg.MibVariable('SNMPv2-MIB', 'sysName', 0), 'new name' ) ) if errorIndication: print('Notification not sent: %s' % errorIndication) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/trap-v1-with-default-values.py0000644000076400001440000000162612063714267030156 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification 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' # from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 ntfOrg = ntforg.NotificationOriginator() errorIndication = ntfOrg.sendNotification( ntforg.CommunityData('public', mpModel=0), ntforg.UdpTransportTarget(('localhost', 162)), 'trap', '1.3.6.1.6.3.1.1.5.2', ('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', rfc1902.OctetString('my system')) ) if errorIndication: print('Notification not sent: %s' % errorIndication) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/inform-v3.py0000644000076400001440000000202312067077132024601 0ustar ilyausers00000000000000## # Notification Originator # # Send SNMP 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' # from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 ntfOrg = ntforg.NotificationOriginator() errorIndication, errorStatus, errorIndex, varBinds = ntfOrg.sendNotification( ntforg.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), ntforg.UdpTransportTarget(('localhost', 162)), 'inform', '1.3.6.1.6.3.1.1.5.2', ('1.3.6.1.2.1.1.5.0', rfc1902.OctetString('system name')) ) if errorIndication: print('Notification not sent: %s' % errorIndication) elif errorStatus: print('Notification Receiver returned error: %s @%s' % (errorStatus, errorIndex)) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/trap-v3-with-custom-engineid.py0000644000076400001440000000252012072034320030304 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification using the following options: # # * SNMPv3 # * with local snmpEngineId = 0x8000000001020304 # * 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. # from pysnmp.entity import engine from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 # This SNMP Engine ID value should also be configured to TRAP receiver. snmpEngineId = rfc1902.OctetString(hexValue='8000000001020304') ntfOrg = ntforg.NotificationOriginator(engine.SnmpEngine(snmpEngineId)) errorIndication = ntfOrg.sendNotification( ntforg.UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=ntforg.usmHMACSHAAuthProtocol, privProtocol=ntforg.usmAesCfb128Protocol), ntforg.UdpTransportTarget(('127.0.0.1', 162)), 'trap', ntforg.MibVariable('SNMPv2-MIB', 'authenticationFailure') ) if errorIndication: print('Notification not sent: %s' % errorIndication) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/inform-async-multiple-transports-and-protocols.py0000644000076400001440000000346112071642147034224 0ustar ilyausers00000000000000# # Notification Originator # # Send multiple SNMP notifications using the following options: # # * SNMPv2c and SNMPv3 # * with community name 'public' or USM username usr-md5-des # * 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 # from pysnmp.entity.rfc3413.oneliner import ntforg from pysnmp.proto import rfc1902 # List of targets in the followin format: # ( ( authData, transportTarget ), ... ) targets = ( # 1-st target (SNMPv2c over IPv4/UDP) ( ntforg.CommunityData('public'), ntforg.UdpTransportTarget(('localhost', 162)) ), # 2-nd target (SNMPv3 over IPv4/UDP) ( ntforg.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), ntforg.UdpTransportTarget(('localhost', 162)) ) ) ntfOrg = ntforg.AsynNotificationOriginator() def cbFun(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())) for authData, transportTarget in targets: sendPduHandle = ntfOrg.sendNotification( authData, transportTarget, 'inform', ntforg.MibVariable('SNMPv2-MIB', 'coldStart'), ( ( rfc1902.ObjectName('1.3.6.1.2.1.1.1.0'), rfc1902.OctetString('my name') ), ), cbInfo=(cbFun, None) ) ntfOrg.snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/inform-v3-with-custom-contextname.py0000644000076400001440000000264612072034677031423 0ustar ilyausers00000000000000# # Notification Originator # # 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. # from pysnmp.entity import engine from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.oneliner import ntforg snmpEngine = engine.SnmpEngine() snmpContext = context.SnmpContext(snmpEngine) # register default collection of Managed Objects under new contextName snmpContext.registerContextName('my-context', snmpContext.getMibInstrum()) ntfOrg = ntforg.NotificationOriginator(snmpEngine, snmpContext) errorIndication, errorStatus, errorIndex, varBinds = ntfOrg.sendNotification( ntforg.UsmUserData('usr-md5-none', 'authkey1'), ntforg.UdpTransportTarget(('localhost', 162)), 'inform', '1.3.6.1.6.3.1.1.5.2', contextName='my-context' ) if errorIndication: print('Notification not sent: %s' % errorIndication) elif errorStatus: print('Notification Receiver returned error: %s @%s' % (errorStatus, errorIndex)) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/agent/ntforg/inform-v2c-with-mib-lookup.py0000644000076400001440000000210012064021627027757 0ustar ilyausers00000000000000# # Notification Originator # # 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 # * perform response OIDs and values resolution at MIB # from pysnmp.entity.rfc3413.oneliner import ntforg ntfOrg = ntforg.NotificationOriginator() errorIndication, errorStatus, errorIndex, varBinds = ntfOrg.sendNotification( ntforg.CommunityData('public'), ntforg.UdpTransportTarget(('localhost', 162)), 'inform', ntforg.MibVariable('SNMPv2-MIB', 'coldStart'), ( ntforg.MibVariable('SNMPv2-MIB', 'sysName', 0), 'my system' ), lookupNames=True, lookupValues=True ) if errorIndication: print('Notification not sent: %s' % errorIndication) elif errorStatus: print('Notification Receiver returned error: %s @%s' % (errorStatus, errorIndex)) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/0000755000076400001440000000000012222743671021430 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/0000755000076400001440000000000012222743671022665 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/getbulk-v2c.py0000644000076400001440000000205312141543377025365 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP GETBULK request 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 # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), 0, 25, '1.3.6.1.2.1.2.2.1.2', '1.3.6.1.2.1.2.2.1.3', ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v3-with-mib-lookup.py0000644000076400001440000000167512141543377027403 0ustar ilyausers00000000000000# # Command Generator # # 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 # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.UsmUserData('usr-md5-none', 'authkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('IF-MIB', 'ifInOctets', '1') ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v3-table-object-by-index.py0000644000076400001440000000202212141543377030407 0ustar ilyausers00000000000000# # Command Generator # # 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 MIB object # * perform response OIDs and values resolution at MIB # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.UsmUserData('usr-none-none'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('IF-MIB', 'ifInOctets', '1'), lookupNames=True, lookupValues=True ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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())) ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/set-v3-with-custom-contextengineid-and-contextname.pypysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/set-v3-with-custom-contextengineid-and-contextn0000644000076400001440000000253012222736626034001 0ustar ilyausers00000000000000# # Command Generator # # 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) # from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.UsmUserData('usr-md5-none', 'authkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), (cmdgen.MibVariable('SNMPv2-MIB', 'sysORDescr', 1), 'new system name'), contextEngineId=rfc1902.OctetString(hexValue='80004fb805636c6f75644dab22cc'), contextName='da761cfc8c94d3aceef4f60f049105ba' ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/set-v2c-with-value-type-mib-lookup.py0000644000076400001440000000170112141543377031640 0ustar ilyausers00000000000000# # Command Generator # # 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) # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), (cmdgen.MibVariable('SNMPv2-MIB', 'sysORDescr', 1), 'new system name') ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-v3-pull-whole-mib-with-options.py0000644000076400001440000000260512141543377032544 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP GETNEXT requests using the following options: # # * with SNMPv3, user 'usr-sha-aes128', SHA auth, AES128 privacy # * over Local Domain Sockets # * to an Agent at demo.snmplabs.com:161 # * for all OIDs past IF-MIB (load up all MIBs in search path) # * run till end-of-mib condition is reported by Agent OR maxRows == 100 # * ignoring non-increasing OIDs whenever reported by Agent # # make sure IF-MIB.py is search path # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=cmdgen.usmHMACSHAAuthProtocol, privProtocol=cmdgen.usmAesCfb128Protocol), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('IF-MIB', '').loadMibs(), lexicographicMode=True, maxRows=100, ignoreNonIncreasingOid=True ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/getbulk-v3-with-custom-mib-path-and-options.py0000644000076400001440000000244612141543377033442 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP GETBULK 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 all OIDs past TCP-MIB::tcpConnTable # * TCP-MIB will be searched by a user-specified path # * run till end-of-mib condition is reported by Agent OR maxRows == 20 # * ignoring non-increasing OIDs whenever reported by Agent # # make sure IF-MIB.py is search path # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd( cmdgen.UsmUserData('usr-none-none'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), 0, 50, cmdgen.MibVariable('TCP-MIB', 'tcpConnTable').addMibSource('/tmp/mymibs'), lexicographicMode=True, maxRows=100, ignoreNonIncreasingOid=True ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/set-v3-with-custom-contextengineid.py0000644000076400001440000000237612222736627032041 0ustar ilyausers00000000000000# # Command Generator # # 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 taken from MIB) # from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.UsmUserData( 'usr-md5-des', 'authkey1', 'privkey1', securityEngineId=rfc1902.OctetString( hexValue='80004fb805636c6f75644dab22cc' ) ), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), (cmdgen.MibVariable('SNMPv2-MIB', 'sysORDescr', 1), 'new system name'), ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/getbulk-v3-over-ipv6-with-mib-lookup.py0000644000076400001440000000257712122057166032111 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP GETBULK 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 # * 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 OR maxRows == 20 # * perform response OIDs and values resolution at MIB # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() # Send a series of SNMP GETBULK requests # make sure IF-MIB.py and IP-MIB.py are in search path errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.Udp6TransportTarget(('::1', 161)), 1, 25, cmdgen.MibVariable('IP-MIB', 'ipAdEntAddr'), cmdgen.MibVariable('IF-MIB', 'ifEntry'), lookupNames=True, lookupValues=True, maxRows=20 ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-async-multiple-transports-and-protocols.pypysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-async-multiple-transports-and-protocols0000644000076400001440000000572712141543377034245 0ustar ilyausers00000000000000## # Asynchronous Command Generator # # Send a bunch of SNMP GETNEXT requests all at once 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 # * for multiple MIB subtrees and tables # from pysnmp.entity.rfc3413.oneliner import cmdgen # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) ( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( '1.3.6.1.2.1', '1.3.6.1.3.1') ), # 2-nd target (SNMPv2c over IPv4/UDP) ( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( '1.3.6.1.4.1', ) ), # 3-nd target (SNMPv3 over IPv4/UDP) ( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'system'), ) ), # 4-th target (SNMPv3 over IPv6/UDP) ( cmdgen.UsmUserData('usr-md5-none', 'authkey1'), cmdgen.Udp6TransportTarget(('::1', 161)), ( cmdgen.MibVariable('IF-MIB', 'ifTable'), ) ) # N-th target # ... ) # Wait for responses or errors, submit GETNEXT requests for further OIDs def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): (varBindHead, authData, transportTarget) = cbCtx print('%s via %s' % (authData, transportTarget)) if errorIndication: print(errorIndication) return if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) return varBindTableRow = varBindTable[-1] for idx in range(len(varBindTableRow)): name, val = varBindTableRow[idx] if val is not None and varBindHead[idx] <= name: # still in table break else: print('went out of table at %s' % (name, )) return for varBindRow in varBindTable: for oid, val in varBindRow: if val is None: print(oid.prettyPrint()) else: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return True # continue table retrieval cmdGen = cmdgen.AsynCommandGenerator() # Submit initial GETNEXT requests and wait for responses for authData, transportTarget, varNames in targets: varBindHead = [ x[0] for x in cmdGen.makeReadVarBinds(varNames) ] cmdGen.nextCmd( authData, transportTarget, varNames, # User-space callback function and its context (cbFun, (varBindHead, authData, transportTarget)), lookupNames=True, lookupValues=True ) cmdGen.snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v3-with-specific-engine-id.py0000644000076400001440000000415112150103701030716 0ustar ilyausers00000000000000# # Command Generator # # 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.entity import engine from pysnmp.entity.rfc3413.oneliner import cmdgen snmpEngine = engine.SnmpEngine() cmdGen = cmdgen.CommandGenerator(snmpEngine) transportTarget = cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)) # # Discover remote SNMP EngineID # authData = cmdgen.UsmUserData('non-existing-user') errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( authData, transportTarget ) # Check for errors and print out results if errorIndication == 'unknownUserName': snmpV3MessageProcessor = snmpEngine.messageProcessingSubsystems[3] securityEngineId, contextEngineId, contextName = snmpV3MessageProcessor.getPeerEngineInfo(*transportTarget.getTransportInfo()) if securityEngineId: print('securityEngineId = %s' % securityEngineId.prettyPrint()) else: print('Peer EngineID not available') raise Exception() else: print('Can\'t discover peer EngineID', errorIndication) raise Exception() # # Query remote SNMP Engine using usmUserTable entry configured for it # authData = cmdgen.UsmUserData('usr-md5-none', 'authkey1', securityEngineId=securityEngineId) errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( authData, transportTarget, '1.3.6.1.2.1.1.1.0' ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v1.py0000644000076400001440000000205112141543377024341 0ustar ilyausers00000000000000# # Command Generator # # 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, # * one in label and another in MIB symbol form # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0'), cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0) ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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())) ././@LongLink0000000000000000000000000000014700000000000011217 Lustar 00000000000000pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/get-threaded-multiple-transports-and-protocols.pypysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/get-threaded-multiple-transports-and-protocols.0000644000076400001440000001066112217303034034044 0ustar ilyausers00000000000000# # Multithreaded, synchronous Command Generator # # 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 if version_info[0] == 2: from Queue import Queue else: from queue import Queue from threading import Thread from pysnmp.entity.rfc3413.oneliner import cmdgen # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) ( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # 2-nd target (SNMPv2c over IPv4/UDP) ( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # 3-nd target (SNMPv2c over IPv4/UDP) - same community and # different transport address. ( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('localhost', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysContact', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0) ) ), # 4-nd target (SNMPv3 over IPv4/UDP) ( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # 5-th target (SNMPv3 over IPv6/UDP) ( cmdgen.UsmUserData('usr-md5-none', 'authkey1'), cmdgen.Udp6TransportTarget(('::1', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # N-th target # ... ) class Worker(Thread): def __init__(self, requests, responses): Thread.__init__(self) self.requests = requests self.responses = responses self.cmdGen = cmdgen.CommandGenerator() self.setDaemon(True) self.start() def run(self): while True: authData, transportTarget, varNames = self.requests.get() self.responses.append( self.cmdGen.getCmd( authData, transportTarget, *varNames, **{ 'lookupNames': True, 'lookupValues': True } ) ) if hasattr(self.requests, 'task_done'): # 2.5+ self.requests.task_done() class ThreadPool: 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, varNames in targets: pool.addRequest(authData, transportTarget, varNames) # Wait for responses or errors pool.waitCompletion() # Walk through responses for errorIndication, errorStatus, errorIndex, varBinds in pool.getResponses(): print('Response for %s from %s:' % (authData, transportTarget)) if errorIndication: print(errorIndication) if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?' ) ) for oid, val in varBinds: if val is None: print(oid.prettyPrint()) else: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v3-over-ipv6-with-mib-lookup.py0000644000076400001440000000202312222736704031220 0ustar ilyausers00000000000000# # Command Generator # # 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: one passed as a MibVariable object while others are # * in string form # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.Udp6TransportTarget(('::1', 161)), cmdgen.MibVariable('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' ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v3-table-object-by-multiple-indices.py0000644000076400001440000000221712141543377032555 0ustar ilyausers00000000000000# # Command Generator # # 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 # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1', authProtocol=cmdgen.usmHMACSHAAuthProtocol, privProtocol=cmdgen.usmAesCfb128Protocol ), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('TCP-MIB', 'tcpConnLocalAddress', '0.0.0.0', 22, '0.0.0.0', 0) ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v2c.py0000644000076400001440000000160312141543377024507 0ustar ilyausers00000000000000# # Command Generator # # 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 # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), '1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.6.0' ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-v1.py0000644000076400001440000000233312141543377025243 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP GETNEXT request 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 # # make sure IF-MIB.py is in search path # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('IF-MIB', 'ifDescr'), cmdgen.MibVariable('IF-MIB', 'ifType'), cmdgen.MibVariable('IF-MIB', 'ifMtu'), cmdgen.MibVariable('IF-MIB', 'ifSpeed'), cmdgen.MibVariable('IF-MIB', 'ifPhysAddress') ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/get-v3-with-custom-security-name.py0000644000076400001440000000234212150151753031403 0ustar ilyausers00000000000000# # Command Generator # # 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.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.UsmUserData('usr-md5-none', 'authkey1', securityName='myuser'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), '1.3.6.1.2.1.1.1.0' ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/get-async-multiple-transports-and-protocols.py0000644000076400001440000000604012141543377033762 0ustar ilyausers00000000000000# # Asynchronous Command Generator # # Send a bunch of SNMP GET requests all at once 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 # * for instances of SNMPv2-MIB::sysDescr.0 and # SNMPv2-MIB::sysLocation.0 MIB objects # from pysnmp.entity.rfc3413.oneliner import cmdgen # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1-st target (SNMPv1 over IPv4/UDP) ( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # 2-nd target (SNMPv2c over IPv4/UDP) ( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # 3-nd target (SNMPv2c over IPv4/UDP) - same community and # different transport address. ( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('localhost', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysContact', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0) ) ), # 4-nd target (SNMPv3 over IPv4/UDP) ( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # 5-th target (SNMPv3 over IPv6/UDP) ( cmdgen.UsmUserData('usr-md5-none', 'authkey1'), cmdgen.Udp6TransportTarget(('::1', 161)), ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0) ) ), # N-th target # ... ) # Wait for responses or errors def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): (authData, transportTarget) = cbCtx print('%s via %s' % (authData, transportTarget)) if errorIndication: print(errorIndication) return 1 if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?' ) ) return 1 for oid, val in varBinds: if val is None: print(oid.prettyPrint()) else: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) cmdGen = cmdgen.AsynCommandGenerator() # Submit GET requests for authData, transportTarget, varNames in targets: cmdGen.getCmd( authData, transportTarget, varNames, # User-space callback function and its context (cbFun, (authData, transportTarget)), lookupNames=True, lookupValues=True ) cmdGen.snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-v3-pull-whole-mib-with-mib-lookup.py0000644000076400001440000000215712141543377033131 0ustar ilyausers00000000000000# # Command Generator # # Send 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 # * stop when response OIDs leave the scopes of the table # * perform response values resolution at MIB # # make sure IF-MIB.py is in search path # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.UsmUserData('usr-md5-none', 'authkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), cmdgen.MibVariable('IF-MIB', ''), lookupValues=True ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/set-v1-multiple-values.py0000644000076400001440000000214612141543377027510 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP SET request using the following options: # # * with SNMPv1, community 'public' # * over IPv4/UDP # * to an Agent at demo.snmplabs.com:161 # * setting two OIDs to new values (types explicitly specified) # from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.CommunityData('public', mpModel=0), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), ('1.3.6.1.2.1.1.9.1.2.1', rfc1902.ObjectName('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', rfc1902.OctetString('new system name')) ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/set-v3-with-value-type-mib-lookup.py0000644000076400001440000000214312141543377031477 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP SET request 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 # * setting SNMPv2-MIB::sysName.0 to new value (type taken from MIB) # * perform response OIDs and values resolution at MIB # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), (cmdgen.MibVariable('SNMPv2-MIB', 'sysORDescr', 1), 'new system name'), lookupNames=True, lookupValues=True ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if 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.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-v2c.py0000644000076400001440000000175112141543377025412 0ustar ilyausers00000000000000# # Command Generator # # Send 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 # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), '1.3.6.1.2.1.2.2.1.2', '1.3.6.1.2.1.2.2.1.3', ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/oneliner/manager/cmdgen/getnext-v3-over-ipv6-with-mib-lookup.py0000644000076400001440000000224012122057166032115 0ustar ilyausers00000000000000# # Command Generator # # Send SNMP GETNEXT 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 # * for all columns of the IF-MIB::ifEntry table # * stop when response OIDs leave the scopes of the table # * perform response OIDs and values resolution at MIB # # make sure IF-MIB.py is in search path # from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'), cmdgen.Udp6TransportTarget(('::1', 161)), cmdgen.MibVariable('IF-MIB', 'ifEntry'), lookupNames=True, lookupValues=True ) if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) pysnmp-4.2.5/examples/v3arch/agent/0000755000076400001440000000000012222743671017301 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/agent/ntforg/0000755000076400001440000000000012222743671020600 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/agent/ntforg/trap-v1.py0000644000076400001440000000635012153626040022441 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification using the following options: # # * SNMPv1 # * with community name 'public' # * over IPv4/UDP # * to a Manager at 127.0.0.1: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 '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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context from pysnmp.proto.api import v2c #from pysnmp import debug # Optional debugging ('all' enables full debugging) #debug.setLogger(debug.Debug('acl', 'io', 'dsp', 'msgproc', 'secmod', 'app')) # 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, ('127.0.0.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 (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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # TRAP OID: Generic Trap #6 (enterpriseSpecific) and Specific Trap 432 '1.3.6.1.4.1.20408.4.1.1.2.0.432', # additional var-binds ( # Uptime value with 12345 (v2c.ObjectIdentifier('1.3.6.1.2.1.1.3.0'), v2c.TimeTicks(12345)), # 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.2.5/examples/v3arch/agent/ntforg/trap-v1-from-specific-address.py0000644000076400001440000000454512220033654026612 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification using the following options: # # * SNMPv1 # * with community name 'public' # * over IPv4/UDP # * to a Manager at 127.0.0.1 UDP port 162 # * from local address 127.0.0.1, UDP port 61024 # * send TRAP notification # * with TRAP ID 'coldStart' specified as an OID # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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=('127.0.0.1', 61024)) ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('127.0.0.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 (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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # TRAP OID ('SNMPv2-MIB', 'coldStart') ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and stop snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/agent/ntforg/inform-v3.py0000644000076400001440000000511212153626040022762 0ustar ilyausers00000000000000# # Notification Originator # # 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 127.0.0.1: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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.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', '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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,5,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.2.5/examples/v3arch/agent/ntforg/trap-v3.py0000644000076400001440000000504012153626040022436 0ustar ilyausers00000000000000# # Notification Originator # # 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 127.0.0.1:162 # * with TRAP ID 'warmStart' specified as an OID # * include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.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 (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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,5,0), v2c.OctetString('system name')), ) ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/agent/ntforg/inform-multiple-protocols.py0000644000076400001440000000626112153626040026315 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP INFORM notifications to multiple Managers using the # following options: # # * 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 127.0.0.1:162, 127.0.0.2:162 # * with TRAP ID 'coldStart' specified as an OID # * include managed objects information: # 1.3.6.1.2.1.1.1.0 = 'Example Notificator' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.1', 162), 'my-creds-1', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('127.0.0.1', 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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,1,0), v2c.OctetString('Example Notificator')), ), cbFun ) print('Notifications are scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/agent/ntforg/trap-v2c-with-objects.py0000644000076400001440000000771612153626040025214 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP TRAP notification using the following options: # # * SNMPv2c # * with community name 'public' # * over IPv4/UDP # * send TRAP notification # * to a Manager at 127.0.0.1:162 # * with TRAP ID ACCOUNTING-CONTROL-MIB::acctngFileFull as MIB symbol # # The ACCOUNTING-CONTROL-MIB::acctngFileFull NOTIFICATION-TYPE implies # including three other var-binds into the TRAP describing the incident # occurred. These var-binds are: # ACCOUNTING-CONTROL-MIB::acctngFileMaximumSize.0 # ACCOUNTING-CONTROL-MIB::acctngFileNameSuffix.0 # ACCOUNTING-CONTROL-MIB::acctngFileName.0 # # To run this example make sure to have ACCOUNTING-CONTROL-MIB.py in # search path. # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # # 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. # mibInstrumCtl = snmpContext.getMibInstrum('') ( MibScalarInstance, ) = mibInstrumCtl.mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance' ) ( acctngFileFull, acctngFileMaximumSize, acctngFileNameSuffix, acctngFileName ) = mibInstrumCtl.mibBuilder.importSymbols( 'ACCOUNTING-CONTROL-MIB', 'acctngFileFull', 'acctngFileMaximumSize', 'acctngFileNameSuffix', 'acctngFileName' ) mibInstrumCtl.mibBuilder.exportSymbols( '__ACCOUNTING-CONTROL-MIB', MibScalarInstance(acctngFileMaximumSize.name, (0,), acctngFileMaximumSize.syntax.clone(123)), MibScalarInstance(acctngFileNameSuffix.name, (0,), acctngFileNameSuffix.syntax.clone('.log')), MibScalarInstance(acctngFileName.name, (0,), acctngFileName.syntax.clone('mylogfile')), ) # # End of Agent's Managed Object Instances initialization # # 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, ('127.0.0.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(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap type ('ACCOUNTING-CONTROL-MIB', 'acctngFileFull'), # MIB scalar/table instances of NOTIFICATION-TYPE objects instanceIndex=(0,) ) print('Notification is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/agent/ntforg/trap-v2c-multiple-targets.py0000644000076400001440000000546712153626040026115 0ustar ilyausers00000000000000# # Notification Originator # # 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 127.0.0.1:162, 127.0.0.2: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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.1', 162), 'my-creds', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('127.0.0.2', 162), 'my-creds', tagList='all-my-managers' ) # Third target config.addTargetAddr( snmpEngine, 'my-nms-3', udp.domainName, ('127.0.0.3', 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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (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.2.5/examples/v3arch/agent/ntforg/trap-v2c-multiple-transports.py0000644000076400001440000000544712153626040026661 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP TRAP notification using the following options: # # * 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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.1', 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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (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.2.5/examples/v3arch/agent/ntforg/inform-v2c.py0000644000076400001440000000546112153626040023133 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP INFORM notification using the following options: # # * SNMPv2c # * with community name 'public' # * over IPv4/UDP # * send INFORM notification # * to a Manager at 127.0.0.1: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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.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', '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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (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.2.5/examples/v3arch/agent/ntforg/trap-v2c.py0000644000076400001440000000533112153626040022603 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP TRAP notification using the following options: # # * SNMPv2c # * with community name 'public' # * over IPv4/UDP # * send TRAP notification # * to a Manager at 127.0.0.1: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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(sendRequestHandle, errorIndication, cbCtx): print('Notification %s, status - %s' % ( sendRequestHandle, errorIndication and errorIndication or 'delivered' ) ) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (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 is scheduled to be sent') # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/agent/ntforg/trap-v2c-multiple-addresses.py0000644000076400001440000000554512153626040026416 0ustar ilyausers00000000000000# # Notification Originator # # 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 127.0.0.1:162, 127.0.0.2: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' # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.dgram import udp from pysnmp.entity.rfc3413 import ntforg, context 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, ('127.0.0.1', 162), 'my-creds', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('127.0.0.2', 162), 'my-creds', tagList='all-my-managers' ) # Third target config.addTargetAddr( snmpEngine, 'my-nms-3', udp.domainName, ('127.0.0.3', 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 default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (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.2.5/examples/v3arch/agent/cmdrsp/0000755000076400001440000000000012222743671020571 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/agent/cmdrsp/v2c-custom-tabular-mib-objects.py0000644000076400001440000000614712220056432026767 0ustar ilyausers00000000000000# # Command Responder # # Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with # the following options: # # * SNMPv2c # * with SNMP community "public" # * serving custom Managed Objects Table Instances defined within this script # * allow read access only to the subtree where the custom MIB objects resides # * over IPv4/UDP, listening at 127.0.0.1:161 # # The following Net-SNMP's commands will populate and walk a table: # # $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.2.1 s 'my value' # $ snmpset -v2c -c public 127.0.0.1 1.3.6.6.1.5.3.1 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.3.1 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.asynsock.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) # --- create custom Managed Objects Table Instance --- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() ( MibTable, MibTableRow, MibTableColumn, MibScalarInstance ) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibScalarInstance' ) RowStatus, = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus') mibBuilder.exportSymbols( '__MY_MIB', # table object MibTable((1,3,6,6,1)).setMaxAccess('readcreate'), # table row object, also carries references to table indices MibTableRow((1,3,6,6,1,5)).setMaxAccess('readcreate').setIndexNames((0, '__MY_MIB', 'myTableIndex')), # table column: value MibTableColumn((1,3,6,6,1,5,2), v2c.OctetString()).setMaxAccess('readcreate'), # table column: row status MibTableColumn((1,3,6,6,1,5,3), RowStatus()).setMaxAccess('readcreate'), # table column: index, needs to be named to refer to as index column myTableIndex=MibTableColumn((1,3,6,6,1,5,1), v2c.Integer()).setMaxAccess('readcreate') ) # --- end of Managed Object Instance initialization ---- # 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.2.5/examples/v3arch/agent/cmdrsp/v2c-custom-scalar-mib-objects.py0000644000076400001440000000453612153626040026605 0ustar ilyausers00000000000000# # Command Responder # # 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 # # Either of the following Net-SNMP's 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.asynsock.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): 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.2.5/examples/v3arch/agent/cmdrsp/v2c-multiple-transports.py0000644000076400001440000000376212153626040025704 0ustar ilyausers00000000000000# # Command Responder # # 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's 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.asynsock.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.2.5/examples/v3arch/agent/cmdrsp/v3-custom-engine-id.py0000644000076400001440000000366712153626040024645 0ustar ilyausers00000000000000# # Command Responder # # 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 # # Either of the following Net-SNMP's commands 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.asynsock.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.2.5/examples/v3arch/agent/cmdrsp/v3-alternative-mib-controller.py0000644000076400001440000000446112153626040026733 0ustar ilyausers00000000000000# # Command Responder # # 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's command will send GET request to this Agent: # # $ snmpget -v3 -u usr-none-none -l noAuthNoPriv -n my-context 127.0.0.1 sysDescr.0 # from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asynsock.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, vars, acInfo=(None, None)): return vars # 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.2.5/examples/v3arch/agent/cmdrsp/v3-multiple-snmp-engines.py0000644000076400001440000000641412213330257025722 0ustar ilyausers00000000000000# # Multiple Command Responders # # 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.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.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 = AsynsockDispatcher() # 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.2.5/examples/v3arch/agent/cmdrsp/v1-read-and-write-communities.py0000644000076400001440000000405412153626040026620 0ustar ilyausers00000000000000# # Command Responder # # 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 # # 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.asynsock.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.2.5/examples/v3arch/agent/cmdrsp/v3-alternative-mib.py0000644000076400001440000000473612222117725024561 0ustar ilyausers00000000000000# # Command Responder # # 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's 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.asynsock.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.2.5/examples/v3arch/agent/cmdrsp/v3-multiple-users.py0000644000076400001440000000513312153626040024456 0ustar ilyausers00000000000000# # Command Responder # # 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's 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.asynsock.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', 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) # 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.2.5/examples/v3arch/agent/cmdrsp/v2c-multiple-interfaces.py0000644000076400001440000000375712153626040025614 0ustar ilyausers00000000000000# # Command Responder # # 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's 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.asynsock.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.2.5/examples/v3arch/manager/0000755000076400001440000000000012222743671017615 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/manager/cmdgen/0000755000076400001440000000000012222743671021052 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/manager/cmdgen/get-v3-custom-context.py0000644000076400001440000000450312222736626025527 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # 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 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((1,3,6,1,2,1,1,1,0), None), ), cbFun, contextEngineId=rfc1902.OctetString(hexValue='80004fb805636c6f75644dab22cc'), contextName=rfc1902.OctetString('da761cfc8c94d3aceef4f60f049105ba') ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/manager/cmdgen/getbulk-v2c.py0000644000076400001440000000431112153626040023541 0ustar ilyausers00000000000000# # GETBULK Command Generator # # Send a series of SNMP GETBULK requests # with SNMPv2c, community 'public' # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 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.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', 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.2.5/examples/v3arch/manager/cmdgen/getnext-v2c-from-specific-address.py0000644000076400001440000000427412220033610027727 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # Send a series of SNMP GETNEXT requests # with SNMPv2c, community 'public' # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1 1.3.6.1.4.1.1 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/set-v2c.py0000644000076400001440000000367412222736626022723 0ustar ilyausers00000000000000# # SET Command Generator # # Send a SNMP SET request # with SNMPv2c with community name 'private' # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.9.1.4.1 t 123 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/set-v1.py0000644000076400001440000000426312222736626022552 0ustar ilyausers00000000000000# # SET Command Generator # # Send a SNMP SET request # with SNMPv1 with community name 'private' # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228: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.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/get-v3.py0000644000076400001440000000370712153626040022531 0ustar ilyausers00000000000000# # GET Command Generator # # 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 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/get-v1.py0000644000076400001440000000372712153626040022531 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # with SNMPv1, community 'public' # over IPv4/UDP # to an Agent at 195.218.195.228:161 # for an OID in tuple form # # This script performs similar to the following Net-SNMP command: # # $ snmpget -v1 -c public -ObentU 195.218.195.228 1.3.6.1.2.1.1.1.0 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/getnext-v3-pull-subtree.py0000644000076400001440000000442712153626040026051 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # 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 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( (initialOID, None), ), cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() pysnmp-4.2.5/examples/v3arch/manager/cmdgen/getnext-v1.py0000644000076400001440000000431112153626040023416 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # Send a series of SNMP GETNEXT requests # with SNMPv1, community 'public' # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1 1.3.6.1.4.1.1 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/getnext-v3-over-ipv6.py0000644000076400001440000000414012153626040025253 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # Send a series of SNMP GETNEXT requests # 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.asynsock.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 def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/getbulk-v3.py0000644000076400001440000000450512153626040023404 0ustar ilyausers00000000000000# # GETBULK Command Generator # # Send a series of SNMP GETBULK requests # with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 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.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', 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.2.5/examples/v3arch/manager/cmdgen/set-v3.py0000644000076400001440000000377612153626040022553 0ustar ilyausers00000000000000# # SET Command Generator # # Send a SNMP SET request # with SNMPv3 with user 'usr-sha-none', SHA auth and no privacy protocols # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228: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.asynsock.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, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/cmdgen/get-v2c-custom-timeout.py0000644000076400001440000000373212153626040025665 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # with SNMPv2c, community 'public' # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1.1.0 # from pysnmp.entity import engine, config from pysnmp.carrier.asynsock.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, ('195.218.195.228', 161), 'my-creds', timeout=300, # in 1/100 sec retryCount=5 ) # Error/response receiver def cbFun(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().sendReq( snmpEngine, 'my-router', ( ((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.2.5/examples/v3arch/manager/ntfrcv/0000755000076400001440000000000012222743671021117 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/manager/ntfrcv/v2c-multiple-transports.py0000644000076400001440000000425212222117725026227 0ustar ilyausers00000000000000# # Notification Receiver # # 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's 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.asynsock.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 def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) print('Notification from %s, ContextEngineId "%s", ContextName "%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) 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.2.5/examples/v3arch/manager/ntfrcv/v3-multiple-users.py0000644000076400001440000000710312153626040025003 0ustar ilyausers00000000000000# # Notification Receiver # # 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's 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.asynsock.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 def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification received, 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.2.5/examples/v3arch/manager/ntfrcv/v2c-multiple-interfaces.py0000644000076400001440000000422212153626040026126 0ustar ilyausers00000000000000# # Notification Receiver # # 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's 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.asynsock.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 def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) print('Notification from %s, ContextEngineId "%s", ContextName "%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) 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.2.5/examples/v3arch/proxy/0000755000076400001440000000000012222743671017364 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/proxy/cmd/0000755000076400001440000000000012222743671020127 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/proxy/cmd/v3-to-v2c-conversion.py0000644000076400001440000001022612153626040024316 0ustar ilyausers00000000000000# # SNMP Command Proxy example # # 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 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from pysnmp.carrier.asynsock.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,), ('195.218.195.228', 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 = snmpEngine, stateReference varBinds = v2c.apiPDU.getVarBinds(PDU) try: if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', v2c.apiBulkPDU.getNonRepeaters(PDU), v2c.apiBulkPDU.getMaxRepetitions(PDU), varBinds, self.handleResponse, cbCtx ) elif PDU.tagSet in self.cmdGenMap: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', varBinds, self.handleResponse, cbCtx ) except error.PySnmpError: self.handleResponse( stateReference, 'error', 0, 0, varBinds, cbCtx ) # SNMP response relay def handleResponse(self, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: errorStatus = 5 errorIndex = 0 varBinds = () snmpEngine, stateReference = cbCtx self.sendRsp( snmpEngine, stateReference, errorStatus, errorIndex, varBinds ) 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.2.5/examples/v3arch/proxy/cmd/udp6-to-udp4-conversion.py0000644000076400001440000001014412153626040025025 0ustar ilyausers00000000000000# # SNMP Command Proxy example # # 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 195.218.195.228: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 195.218.195.228:161 sysDescr.0 # from pysnmp.carrier.asynsock.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, ('195.218.195.228', 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 = snmpEngine, stateReference varBinds = v2c.apiPDU.getVarBinds(PDU) try: if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', v2c.apiBulkPDU.getNonRepeaters(PDU), v2c.apiBulkPDU.getMaxRepetitions(PDU), varBinds, self.handleResponse, cbCtx ) elif PDU.tagSet in self.cmdGenMap: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', varBinds, self.handleResponse, cbCtx ) except error.PySnmpError: self.handleResponse( stateReference, 'error', 0, 0, varBinds, cbCtx ) # SNMP response relay def handleResponse(self, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: errorStatus = 5 errorIndex = 0 varBinds = () snmpEngine, stateReference = cbCtx self.sendRsp( snmpEngine, stateReference, errorStatus, errorIndex, varBinds ) 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.2.5/examples/v3arch/proxy/cmd/v2c-to-v1-conversion.py0000644000076400001440000001003412153626040024311 0ustar ilyausers00000000000000# # SNMP Command Proxy example # # 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 195.218.195.228: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 195.218.195.228:161 system # from pysnmp.carrier.asynsock.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,), ('195.218.195.228', 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 = snmpEngine, stateReference varBinds = v2c.apiPDU.getVarBinds(PDU) try: if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', v2c.apiBulkPDU.getNonRepeaters(PDU), v2c.apiBulkPDU.getMaxRepetitions(PDU), varBinds, self.handleResponse, cbCtx ) elif PDU.tagSet in self.cmdGenMap: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', varBinds, self.handleResponse, cbCtx ) except error.PySnmpError: self.handleResponse( stateReference, 'error', 0, 0, varBinds, cbCtx ) # SNMP response relay def handleResponse(self, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: errorStatus = 5 errorIndex = 0 varBinds = () snmpEngine, stateReference = cbCtx self.sendRsp( snmpEngine, stateReference, errorStatus, errorIndex, varBinds ) 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.2.5/examples/v3arch/proxy/cmd/v2c-to-v3-conversion.py0000644000076400001440000001001312153626040024310 0ustar ilyausers00000000000000# # SNMP Command Proxy example # # 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 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from pysnmp.carrier.asynsock.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,), ('195.218.195.228', 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 = snmpEngine, stateReference varBinds = v2c.apiPDU.getVarBinds(PDU) try: if PDU.tagSet == v2c.GetBulkRequestPDU.tagSet: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', v2c.apiBulkPDU.getNonRepeaters(PDU), v2c.apiBulkPDU.getMaxRepetitions(PDU), varBinds, self.handleResponse, cbCtx ) elif PDU.tagSet in self.cmdGenMap: self.cmdGenMap[PDU.tagSet].sendReq( snmpEngine, 'distant-agent', varBinds, self.handleResponse, cbCtx ) except error.PySnmpError: self.handleResponse( stateReference, 'error', 0, 0, varBinds, cbCtx ) # SNMP response relay def handleResponse(self, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: errorStatus = 5 errorIndex = 0 varBinds = () snmpEngine, stateReference = cbCtx self.sendRsp( snmpEngine, stateReference, errorStatus, errorIndex, varBinds ) 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.2.5/examples/v3arch/twisted/0000755000076400001440000000000012222743671017666 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/agent/0000755000076400001440000000000012222743671020764 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/agent/ntforg/0000755000076400001440000000000012222743671022263 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/agent/ntforg/trap-v1.py0000644000076400001440000000660412153626041024127 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP notification using the following options: # # * SNMPv1 # * with community name 'public' # * over IPv4/UDP # * using Twisted framework for network transport # * to a Manager at 127.0.0.1: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 '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' # from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.carrier.twisted.dgram import udp from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.twisted import ntforg from pysnmp.proto import rfc1902 # 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) config.addTargetParams(snmpEngine, 'my-creds', 'my-area', 'noAuthNoPriv', 0) # Transport setup # # Setup transport endpoint and bind it with security settings yielding # a target name. Since Notifications could be sent to multiple Managers # at once, more than one target entry may be configured (and tagged). # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('127.0.0.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 (1), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 1, 'my-area', 'noAuthNoPriv', (), (), (1,3,6)) # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Prepare notification to be sent yielding Twisted deferred object ntforg.NotificationOriginator(snmpContext).sendNotification( snmpEngine, # Notification targets 'my-notification', # TRAP OID: Generic Trap #6 (enterpriseSpecific) and Specific Trap 432 '1.3.6.1.4.1.20408.4.1.1.2.0.432', # additional var-binds holding SNMPv1 TRAP details ( # Uptime value with 12345 (rfc1902.ObjectName('1.3.6.1.2.1.1.3.0'), rfc1902.TimeTicks(12345)), # Agent Address with '127.0.0.1' (rfc1902.ObjectName('1.3.6.1.6.3.18.1.3.0'), rfc1902.IpAddress('127.0.0.1')), # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 (rfc1902.ObjectName('1.3.6.1.6.3.1.1.4.3.0'), rfc1902.ObjectName('1.3.6.1.4.1.20408.4.1.1.2')), # managed object '1.3.6.1.2.1.1.1.0' = 'my system' (rfc1902.ObjectName('1.3.6.1.2.1.1.1.0'), rfc1902.OctetString('my system')) ) ) print('Notification is scheduled to be sent') # Schedule Twisted mainloop shutdown shortly reactor.callWhenRunning(lambda: reactor.stop()) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/agent/ntforg/inform-v3.py0000644000076400001440000000550512153626041024454 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP INFORM notification using the following options: # # * SNMPv3 # * with user 'usr-md5-none', auth: MD5, priv NONE # * over IPv4/UDP # * using Twisted framework for network transport # * to a Manager at 127.0.0.1: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' # from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.carrier.twisted.dgram import udp from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.twisted import ntforg from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SNMPv3/USM setup # Add USM user config.addV3User( snmpEngine, 'usr-md5-none', config.usmHMACMD5AuthProtocol, 'authkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-none', 'authNoPriv') # Transport setup # # Setup transport endpoint and bind it with security settings yielding # a target name. Since Notifications could be sent to multiple Managers # at once, more than one target entry may be configured (and tagged). # config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('127.0.0.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', '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)) # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx print('Notification status - %s' % ( errorIndication and errorIndication or 'delivered' ) ) # Optionally stop Twisted reactor reactor.stop() # Build and submit notification message to dispatcher df = ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('system name')), ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) print('Notification is scheduled to be sent') # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/agent/ntforg/trap-v3.py0000644000076400001440000000523312153626041024126 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP TRAP notification using the following options: # # * SNMPv3 # * with user 'usr-md5-des', auth: MD5, priv DES # * over IPv4/UDP # * using Twisted framework for network transport # * send TRAP notification # * to a Manager at 127.0.0.1:162 # * with TRAP ID 'warmStart' specified as an OID # * include managed object information 1.3.6.1.2.1.1.5.0 = 'system name' # from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.carrier.twisted.dgram import udp from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.twisted import ntforg from pysnmp.proto import rfc1902 # 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=rfc1902.OctetString(hexValue='8000000001020304') ) # SNMPv3/USM setup # Add USM user config.addV3User( snmpEngine, 'usr-md5-des', config.usmHMACMD5AuthProtocol, 'authkey1', config.usmDESPrivProtocol, 'privkey1' ) config.addTargetParams(snmpEngine, 'my-creds', 'usr-md5-des', 'authPriv') # Transport setup # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('127.0.0.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 (3), securityLevel # and SecurityName config.addContext(snmpEngine, '') config.addVacmUser(snmpEngine, 3, 'usr-md5-des', 'authPriv', (), (), (1,3,6)) # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('system name')), ) ) print('Notification is scheduled to be sent') # Schedule Twisted mainloop shutdown shortly reactor.callWhenRunning(lambda: reactor.stop()) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/agent/ntforg/trap-v2c-multiple-targets.py0000644000076400001440000000611212153626041027565 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP TRAP notifications to multiple Managers using the # following options: # # * SNMPv2c # * with community name 'public' # * over IPv4/UDP # * using Twisted framework for network transport # * send TRAP notification # * to multiple Managers at 127.0.0.1:162, 127.0.0.2: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' # from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.carrier.twisted.dgram import udp from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.twisted import ntforg from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SNMPv2c setup # 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) # Transport setup # # Setup transport endpoint and bind it with security settings yielding # a target name. Since Notifications could be sent to multiple Managers # at once, more than one target entry may be configured (and tagged). # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) # First target config.addTargetAddr( snmpEngine, 'my-nms-1', udp.domainName, ('127.0.0.1', 162), 'my-creds', tagList='all-my-managers' ) # Second target config.addTargetAddr( snmpEngine, 'my-nms-2', udp.domainName, ('127.0.0.2', 162), 'my-creds', tagList='all-my-managers' ) # Third target config.addTargetAddr( snmpEngine, 'my-nms-3', udp.domainName, ('127.0.0.3', 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)) # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Build and submit notification message to dispatcher ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('Example Notificator')), ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('Notificator Example')) ) ) print('Notification is scheduled to be sent') # Schedule Twisted mainloop shutdown shortly reactor.callWhenRunning(lambda: reactor.stop()) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/agent/ntforg/inform-v2c.py0000644000076400001440000000576712153626041024630 0ustar ilyausers00000000000000# # Notification Originator # # Send SNMP INFORM notification using the following options: # # * SNMPv2c # * with community name 'public' # * over IPv4/UDP # * using Twisted framework for network transport # * send INFORM notification # * to a Manager at 127.0.0.1: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' # from twisted.internet import reactor from pysnmp.entity import engine, config from pysnmp.carrier.twisted.dgram import udp from pysnmp.entity.rfc3413 import context from pysnmp.entity.rfc3413.twisted import ntforg from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SNMPv2c setup # 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) # Transport setup # # Setup transport endpoint and bind it with security settings yielding # a target name. Since Notifications could be sent to multiple Managers # at once, more than one target entry may be configured (and tagged). # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-nms', udp.domainName, ('127.0.0.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', '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)) # Create default SNMP context where contextEngineId == SnmpEngineId snmpContext = context.SnmpContext(snmpEngine) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator(snmpContext) # Error/confirmation receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBinds) = cbCtx print('Notification status - %s' % ( errorIndication and errorIndication or 'delivered' ) ) # Optionally stop Twisted reactor reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = ntfOrg.sendNotification( snmpEngine, # Notification targets 'my-notification', # Trap OID (SNMPv2-MIB::coldStart) (1,3,6,1,6,3,1,1,5,1), # ( (oid, value), ... ) ( ((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('Example Notificator')), ((1,3,6,1,2,1,1,5,0), rfc1902.OctetString('Notificator Example')) ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) print('Notification is scheduled to be sent') # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/agent/cmdrsp/0000755000076400001440000000000012222743671022254 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/agent/cmdrsp/v2c-custom-scalar-mib-objects.py0000644000076400001440000000436712153626040030272 0ustar ilyausers00000000000000# # Command Responder # # 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's 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): 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.2.5/examples/v3arch/twisted/agent/cmdrsp/v1-read-and-write-communities.py0000644000076400001440000000355512153626040030310 0ustar ilyausers00000000000000# # Command Responder # # 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'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 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.2.5/examples/v3arch/twisted/agent/cmdrsp/v3-multiple-users.py0000644000076400001440000000475112153626040026146 0ustar ilyausers00000000000000# # Command Responder # # 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 # * using Twisted framework for network transport # # Either of the following Net-SNMP's 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.2.5/examples/v3arch/twisted/agent/cmdrsp/v2c-multiple-interfaces.py0000644000076400001440000000347112153626040027270 0ustar ilyausers00000000000000# # Command Responder # # 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's 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.2.5/examples/v3arch/twisted/manager/0000755000076400001440000000000012222743671021300 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/0000755000076400001440000000000012222743671022535 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/get-v3-custom-context.py0000644000076400001440000000447712153626041027214 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # with SNMPv3 with user 'usr-md5-none', SHA auth and no privacy protocols # for MIB instance identified by contextEngineId: 8000000001020304, # contextName: my-context # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 8000000001020304 -n my-context -ObentU 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1902 from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.GetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1.1.0', None), ), contextEngineId=rfc1902.OctetString(hexValue='8000000001020304'), contextName=rfc1902.OctetString('my-context') ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/getbulk-v2c.py0000644000076400001440000000534012153626041025230 0ustar ilyausers00000000000000# # GETBULK Command Generator # # Send a series of SNMP GETBULK requests # with SNMPv2c, community 'public' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1 1.3.6.1.4.1.1 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1905 from pysnmp.carrier.twisted.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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Stop reactor when we are done walking (optional) for oid, val in varBindRow: if not val.isSameTypeWith(rfc1905.endOfMibView): break else: reactor.stop() return # Re-create deferred for next GETBULK iteration df = defer.Deferred() df.addCallback(cbFun) return df # This also indicates that we wish to continue walking # Stop reactor on SNMP error (optional) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.BulkCommandGenerator().sendReq( snmpEngine, 'my-router', 0, 25, # non-repeaters, max-repetitions ( ('1.3.6.1.2.1.1', None), ('1.3.6.1.4.1.1', None) ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/getnext-v2c-from-specific-address.py0000644000076400001440000000530612220033543031414 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # Send a series of SNMP GETNEXT requests # with SNMPv2c, community 'public' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228:161 # sending packets from any 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 195.218.195.228 1.3.6.1.2.1.1 1.3.6.1.4.1.1 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1905 from pysnmp.carrier.twisted.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.UdpTwistedTransport().openClientMode(('0.0.0.0', 61024)) ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Stop reactor when we are done walking (optional) for oid, val in varBindRow: if not val.isSameTypeWith(rfc1905.endOfMibView): break else: reactor.stop() return # Re-create deferred for next GETNEXT iteration df = defer.Deferred() df.addCallback(cbFun) return df # This also indicates that we wish to continue walking # Stop reactor on SNMP error (optional) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.NextCommandGenerator().sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1', None), ('1.3.6.1.2.1.11', None) ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/set-v2c.py0000644000076400001440000000404612153626041024370 0ustar ilyausers00000000000000# # SET Command Generator # # Send a SNMP SET request # with SNMPv2c, community 'private' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228:161 # for OIDs in tuple form and an integer-typed value # # This script performs similar to the following Net-SNMP command: # # $ snmpset -v2c -c private -ObentU 195.218.195.228:161 1.3.6.1.2.1.1.9.1.4.1 t 123 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1902 from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.SetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ((1,3,6,1,2,1,1,9,1,3,1), rfc1902.Integer(123)), ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/set-v1.py0000644000076400001440000000443712153626041024230 0ustar ilyausers00000000000000# # SET Command Generator # # Send a SNMP SET request # with SNMPv1, community 'private' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228: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 twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1902 from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.SetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ((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.Integer(123)) ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/get-v3.py0000644000076400001440000000412712153626041024212 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # with SNMPv3 with user 'usr-sha-aes', SHA auth and AES128 privacy protocols # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.1.0 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.GetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1.1.0', None), ), ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/get-v1.py0000644000076400001440000000415312153626041024207 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # with SNMPv1, community 'public' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228:161 # for an OID in tuple form # # This script performs similar to the following Net-SNMP command: # # $ snmpget -v1 -c public -ObentU 195.218.195.228 1.3.6.1.2.1.1.1.0 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.GetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1.1.0', None), ('1.3.6.1.2.1.1.2.0', None) ), ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/getnext-v3-pull-subtree.py0000644000076400001440000000551312153626041027532 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # Send a series of SNMP GETNEXT requests # with SNMPv3 with user 'usr-none-none', no auth and no privacy protocols # over IPv4/UDP # using Twisted framework for network transport # to an Agent at 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1902, rfc1905 from pysnmp.carrier.twisted.dgram import udp # 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, no auth, no priv 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?' ) ) else: for varBindRow in varBindTable: for oid, val in varBindRow: if initialOID.isPrefixOf(oid): print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) else: reactor.stop() return False # signal dispatcher to stop # Stop reactor when we are done walking (optional) for oid, val in varBindRow: if not val.isSameTypeWith(rfc1905.endOfMibView): break else: reactor.stop() return # Re-create deferred for next GETNEXT iteration df = defer.Deferred() df.addCallback(cbFun) return df # This also indicates that we wish to continue walking # Stop reactor on SNMP error (optional) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.NextCommandGenerator().sendReq( snmpEngine, 'my-router', ( (initialOID, None), ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/getnext-v1.py0000644000076400001440000000535612153626041025114 0ustar ilyausers00000000000000# # GETNEXT Command Generator # # Send a series of SNMP GETNEXT requests # with SNMPv1, community 'public' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1 1.3.6.1.4.1.1 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1905 from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBindTable) = 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 varBindTable[-1][int(errorIndex)-1][0] or '?' ) ) else: for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Stop reactor when we are done walking (optional) for oid, val in varBindRow: if not val.isSameTypeWith(rfc1905.endOfMibView): break else: reactor.stop() return # Re-create deferred for next GETNEXT iteration df = defer.Deferred() df.addCallback(cbFun) return df # This also indicates that we wish to continue walking # Stop reactor on SNMP error (optional) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.NextCommandGenerator().sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1', None), ('1.3.6.1.4.1.1', None) ), ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/getbulk-v3.py0000644000076400001440000000553312153626041025072 0ustar ilyausers00000000000000# # GETBULK Command Generator # # Send a series of SNMP GETBULK requests # with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols # over IPv4/UDP # using Twisted framework for network transport # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1 1.3.6.1.4.1.1 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1905 from pysnmp.carrier.twisted.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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (errorIndication, errorStatus, errorIndex, varBindTable) = cbCtx if errorIndication: print(errorIndication) elif errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1][0] or '?' ) ) else: for varBindRow in varBindTable: for oid, val in varBindRow: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) # Stop reactor when we are done walking (optional) for oid, val in varBindRow: if not val.isSameTypeWith(rfc1905.endOfMibView): break else: reactor.stop() return # Re-create deferred for next GETBULK iteration df = defer.Deferred() df.addCallback(cbFun) return df # This also indicates that we wish to continue walking # Stop reactor on SNMP error (optional) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.BulkCommandGenerator().sendReq( snmpEngine, 'my-router', 0, 25, # non-repeaters, max-repetitions ( ((1,3,6,1,2,1,1), None), ((1,3,6,1,4,1,1), None) ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/set-v3.py0000644000076400001440000000420112153626041024217 0ustar ilyausers00000000000000# # SET Command Generator # # Send a SNMP SET request # with SNMPv3 with user 'usr-sha-none', SHA auth and no privacy protocols # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228:161 1.3.6.1.2.1.1.9.1.3.1 s 'my new value' # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.proto import rfc1902 from pysnmp.carrier.twisted.dgram import udp # 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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds' ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.SetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ((1,3,6,1,2,1,1,9,1,3,1), rfc1902.OctetString('my new value')), ) ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/cmdgen/get-v2c-custom-timeout.py0000644000076400001440000000412112153626041027342 0ustar ilyausers00000000000000# # GET Command Generator # # Send a SNMP GET request # with SNMPv2c, community 'public' # using Twisted framework for network transport # over IPv4/UDP # to an Agent at 195.218.195.228: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 195.218.195.228 1.3.6.1.2.1.1.1.0 # from twisted.internet import reactor, defer from pysnmp.entity import engine, config from pysnmp.entity.rfc3413.twisted import cmdgen from pysnmp.carrier.twisted.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.UdpTwistedTransport().openClientMode() ) config.addTargetAddr( snmpEngine, 'my-router', udp.domainName, ('195.218.195.228', 161), 'my-creds', timeout=300, # in 1/100 sec retryCount=5 ) # Error/response receiver def cbFun(cbCtx): (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())) reactor.stop() # Prepare request to be sent yielding Twisted deferred object df = cmdgen.GetCommandGenerator().sendReq( snmpEngine, 'my-router', ( ('1.3.6.1.2.1.1.1.0', None), ), ) # Register error/response receiver function at deferred df.addCallback(cbFun) # Run Twisted main loop reactor.run() pysnmp-4.2.5/examples/v3arch/twisted/manager/ntfrcv/0000755000076400001440000000000012222743671022602 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v3arch/twisted/manager/ntfrcv/v3-multiple-users.py0000644000076400001440000000675712153626041026505 0ustar ilyausers00000000000000# # Notification Receiver # # 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's 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 def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print('Notification received, 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.2.5/examples/v3arch/twisted/manager/ntfrcv/v2c-multiple-interfaces.py0000644000076400001440000000400612153626041027612 0ustar ilyausers00000000000000# # Notification Receiver # # 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 Twisted framework for network transport # * print received data on stdout # # Either of the following Net-SNMP's 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 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 Twisted main loop reactor.run() pysnmp-4.2.5/examples/smi/0000755000076400001440000000000012222743671015605 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/smi/instrum.py0000644000076400001440000000264611655706724017677 0ustar ilyausers00000000000000# Managed Objects implementation 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): 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.2.5/examples/smi/backend.py0000644000076400001440000000174211655706724017561 0ustar ilyausers00000000000000# 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('Remote manager write/create access to MIB instrumentation: '), print(mibInstrum.writeVars( ( ((1,3,6,1,6,3,18,1,1,1,2,109,121,110,109,115), 'mycomm'), ((1,3,6,1,6,3,18,1,1,1,3,109,121,110,109,115), 'mynmsname'), ((1,3,6,1,6,3,18,1,1,1,7,109,121,110,109,115), 'volatile')) ) ) print('Remote manager read access to MIB instrumentation (table walk)') oid, val = (), None while 1: oid, val = mibInstrum.readNextVars(((oid, val),))[0] if exval.endOfMib.isSameTypeWith(val): break print(oid, val.prettyPrint()) print('Unloading MIB modules...'), mibBuilder.unloadModules() print('done') pysnmp-4.2.5/examples/smi/view.py0000644000076400001440000000440611655706724017144 0ustar ilyausers00000000000000# SNMP manager-side MIB management from pysnmp.smi import builder, view, error # Create MIB loader/builder mibBuilder = builder.MibBuilder() # Optionally set an alternative path to compiled MIBs #print('Setting MIB sources...') #mibSources = mibBuilder.getMibSources() + ( # builder.DirMibSource('/opt/pysnmp_mibs'), # ) #mibBuilder.setMibSources(*mibSources) #print(mibBuilder.getMibSources()) #print('done') print('Loading MIB modules...'), mibBuilder.loadModules( 'SNMPv2-MIB', 'SNMP-FRAMEWORK-MIB', 'SNMP-COMMUNITY-MIB' ) print('done') print('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 convertion: '), oid = rowNode.getInstIdFromIndices('router') print(oid) print('Conceptual table index oid to value convertion: '), 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.2.5/examples/v1arch/0000755000076400001440000000000012222743671016201 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v1arch/agent/0000755000076400001440000000000012222743671017277 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v1arch/agent/ntforg.py0000644000076400001440000000321212003212610021123 0ustar ilyausers00000000000000# Notification Originator Application (TRAP) from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.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 = AsynsockDispatcher() # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp.domainName, ('localhost', 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.2.5/examples/v1arch/agent/cmdrsp.py0000644000076400001440000001073712003212610021126 0ustar ilyausers00000000000000# Command Responder Application (GET/GETNEXT) from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api import time, bisect class SysDescr: 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: 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 = AsynsockDispatcher() 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.2.5/examples/v1arch/manager/0000755000076400001440000000000012222743671017613 5ustar ilyausers00000000000000pysnmp-4.2.5/examples/v1arch/manager/nextgen.py0000644000076400001440000000602712141543377021643 0ustar ilyausers00000000000000# GETNEXT Command Generator from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.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") 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 = AsynsockDispatcher() 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.2.5/examples/v1arch/manager/ntfrcv.py0000644000076400001440000000524112003212611021447 0ustar ilyausers00000000000000# Notification Receiver (TRAP PDU) from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.dgram import udp, udp6, unix from pyasn1.codec.ber import decoder from pysnmp.proto import api 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.getVarBindList(reqPDU) else: varBinds = pMod.apiPDU.getVarBindList(reqPDU) print('Var-binds:') for oid, val in varBinds: print('%s = %s' % (oid.prettyPrint(), val.prettyPrint())) return wholeMsg transportDispatcher = AsynsockDispatcher() 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.2.5/examples/v1arch/manager/setgen.py0000644000076400001440000000432612141543377021460 0ustar ilyausers00000000000000# SET Command Generator from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.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") 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 = AsynsockDispatcher() 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.2.5/examples/v1arch/manager/getgen.py0000644000076400001440000000540612141543377021444 0ustar ilyausers00000000000000# GET Command Generator from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.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") 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 = AsynsockDispatcher() 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.2.5/examples/v1arch/manager/bulkgen.py0000644000076400001440000000651712141543377021626 0ustar ilyausers00000000000000# GETBULK Command Generator (SNMPv2c only) from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto.api import v2c from time import time # SNMP table header headVars = [ v2c.ObjectIdentifier((1,3,6)) ] # Build PDU reqPDU = v2c.GetBulkRequestPDU() v2c.apiBulkPDU.setDefaults(reqPDU) v2c.apiBulkPDU.setNonRepeaters(reqPDU, 0) v2c.apiBulkPDU.setMaxRepetitions(reqPDU, 25) v2c.apiBulkPDU.setVarBinds(reqPDU, [ (x, v2c.null) for x in headVars ]) # Build message reqMsg = v2c.Message() v2c.apiMessage.setDefaults(reqMsg) v2c.apiMessage.setCommunity(reqMsg, 'public') v2c.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow - startedAt > 3: raise Exception("Request timed out") def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU, headVars=headVars): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message()) rspPDU = v2c.apiMessage.getPDU(rspMsg) # Match response to request if v2c.apiBulkPDU.getRequestID(reqPDU)==v2c.apiBulkPDU.getRequestID(rspPDU): # 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 = AsynsockDispatcher() 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.2.5/tools/0000755000076400001440000000000012222743671014337 5ustar ilyausers00000000000000pysnmp-4.2.5/tools/build-pysnmp-mib0000644000076400001440000000405111474673436017463 0ustar ilyausers00000000000000#!/bin/sh # # Convert MIB text into PySNMP-compilant MIB/managed objects module. # See http://pysnmp.sf.net for more information. # basedir=$(dirname "$0") libsmi2pysnmp=$basedir/libsmi2pysnmp # part of pysnmp distro smidump=smidump # part of libsmi distro while getopts o: o do case "$o" in o) outFile=$OPTARG ;; [?]) echo >&2 "\ Convert MIB text file into PySNMP-compliant module, see http://pysnmp.sf.net. Usage: $0 [-o pysnmp-mib-file ] [ mib-text-file ]\ " exit 1;; esac done [ -n "$outFile" ] && { exec 5>"$outFile" 1>&5 || { echo >&2 "Redirection failed"; exit 1; } } shift $((OPTIND-1)) [ $# -gt 1 ] && { echo >&2 "Extra arguments given"; exit 1; } [ -z $1 ] && { mibFile="-"; } || { mibFile=$1; export SMIPATH="$SMIPATH:$(echo $mibFile | sed -e 's,[^/]*$,.,')"; } egrep -q 'FROM *RFC' $mibFile 2> /dev/null && ! egrep -q 'FROM *SNMPv2-' $mibFile 2> /dev/null && { oldMib='yes'; } || { [ $? -eq 1 ] && { oldMib='no'; } || { echo >&2 "cant open $mibFile"; exit 1; } } [ $oldMib = 'yes' ] && { # pysnmp SMI is SMIv2 [ -x "$(which mktemp)" ] && tmpFile=$(mktemp -t buildmibs.XXXXXXX) || tmpFile=/tmp/buildmibs.$$ $smidump -k -f smiv2 $mibFile > $tmpFile 2> /dev/null || { [ -f $tmpFile ] && rm -f $tmpFile; echo >&2 "$smidump -k -f smiv2 $mibFile fails"; echo >&2 "make sure you are using libsmi version > 0.4.5 (or svn)"; exit ; } $smidump -k -f python $tmpFile 2> /dev/null | $libsmi2pysnmp || { [ -f $tmpFile ] && rm -f $tmpFile; [ -n "$outFile" ] && rm -f $outFile; echo >&2 "$smidump -k -f python $mibFile | $libsmi2pysnmp fails"; echo >&2 "make sure you are using libsmi version > 0.4.5 (or svn)"; exit } rm -f $tmpFile } || { $smidump -k -f python $mibFile 2> /dev/null | $libsmi2pysnmp || { [ -n "$outFile" ] && rm -f $outFile; echo >&2 "$smidump -k -f python $mibFile | $libsmi2pysnmp fails"; echo >&2 "make sure you are using libsmi version > 0.4.5 (or svn)"; exit } } exit pysnmp-4.2.5/tools/libsmi2pysnmp0000644000076400001440000006463111746476041017110 0ustar ilyausers00000000000000#!/usr/bin/env python # Walk libsmi-generated tree of MIB symbols and build pysnmp.smi # compliant module import sys, time version = '0.1.3' genTextLoader = 1 class Error(Exception): pass if len(sys.argv) > 1: if sys.argv[1] == '--no-text': genTextLoader = 0 else: sys.stderr.write('SNMP MIB to pysnmp objects converter, version %s.\n\ Usage:\n\ %s [--no-text]\n\ Takes:\n\ smidump -f python \n\ program output on stdin, generates python code on stdout.\n\ The smidump tool is available at http://www.ibr.cs.tu-bs.de/projects/libsmi/\n\ The --no-text option disables code generation for MIB text comments.\n' % (version, sys.argv[0])) sys.exit(-1) inputText = '' while 1: c = sys.stdin.read() if not c: break inputText = inputText + c if not inputText: sys.stderr.write('Empty input\n') sys.exit(-1) codeObj = compile(inputText, '', 'exec') g = {} try: eval(codeObj, g) except Exception: raise Error('MIB module load error: %s' % (sys.exc_info[1],)) mib = g['MIB'] dstModName = mib['moduleName'] out = sys.stdout __symsTable = { 'MODULE-IDENTITY': ('ModuleIdentity',), 'OBJECT-TYPE': ('MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn'), 'NOTIFICATION-TYPE': ('NotificationType',), 'TEXTUAL-CONVENTION': ('TextualConvention',), 'MODULE-COMPLIANCE': ('ModuleCompliance',), 'OBJECT-GROUP': ('ObjectGroup',), 'NOTIFICATION-GROUP': ('NotificationGroup',), 'AGENT-CAPABILITIES': ('AgentCapabilities',), 'OBJECT-IDENTITY': ('ObjectIdentity',), 'TRAP-TYPE': ('NotificationType',), # smidump always uses NotificationType 'NOTIFICATION-TYPE': ('NotificationType',) } def symTrans(symbol): if symbol in __symsTable: return __symsTable[symbol] return symbol, def transOpers(symbol): return symbol.replace('-', '_') def addLabelForSymbol(symbol): if symbol.find('-') != -1: return '.setLabel(\"%s\")' % symbol return '' __oidToTuple = lambda x: str(tuple([ int(y) for y in x.split('.') ])) def __reprIntVal(value): try: return int(value) except ValueError: return repr(value) def __genDefVal(baseType, symDef): if baseType == 'OctetString': if symDef['default'][:2] == '0x': return '%s' % repr(symDef['default'][2:]), True else: return '%s' % repr(symDef['default']), False elif baseType == 'Integer': return '%s' % __reprIntVal(symDef['default']), False elif baseType in ('Integer32', 'Unsigned32'): return '%s' % __reprIntVal(symDef['default']), False elif baseType == 'ObjectIdentifier': return '%s' % __oidToTuple(symDef['default']), False elif baseType == 'IpAddress': defVal = '' for i in range(2, len(symDef['default']), 2): if defVal: defVal = defVal + '.' defVal = defVal + str( int(symDef['default'][i:i+2], 16) ) return '\"%s\"' % defVal, False elif baseType == 'Bits': defVal = '(' for bit in symDef['default'].replace(',', '').replace('(', '').replace(')', '').split(): defVal = defVal + '\"%s\",' % bit defVal = defVal + ')' return defVal, False elif baseType == 'Enumeration': if symDef['default'] in symDef['syntax']['type']: return '%s' % \ symDef['syntax']['type'][symDef['default']]['number'], False else: return '\"%s\"' % symDef['default'], False else: sys.stderr.write('WARNING: guessing DEFVAL type \'%s\' for %s\n' % (symDef['default'], baseType)) if symDef['default'][:2] == '0x': return '%s' % repr(symDef['default'][2:]), True else: defVal = symDef['default'] try: int(defVal) except ValueError: pass return '%s' % repr(defVal), False # Ugly kludge against smidump bug which does not distinguish # size/range constraints __kludgyStringTypes = { 'OctetString': 1 } __buggySmiTypes = { 'NetworkAddress': 'IpAddress' # this is up to smidump, but it does not care } def __genTypeDef(symName, symDef, classMode=0): r = '' if classMode: typeDef = symDef identFiller = ' '; identValue = 0 else: typeDef = symDef['syntax']['type'] if 'name' in typeDef: baseType = typeDef['name'] if 'basetype' in typeDef: baseType = typeDef['basetype'] if 'parent module' in typeDef: parentType = typeDef['parent module']['type'] else: parentType = baseType # Ugly hack to overcome smidump bug in smiv1->smiv2 convertion if baseType in __buggySmiTypes: baseType = __buggySmiTypes[baseType] if parentType in __buggySmiTypes: parentType = __buggySmiTypes[parentType] if classMode: r = r + 'class %s(' % symName if 'format' in typeDef: r = r + '%s, ' % symTrans('TEXTUAL-CONVENTION')[0] identValue = identValue + 1 if baseType in ('Enumeration', 'Bits'): if baseType == 'Enumeration': parentType = 'Integer' if classMode: r = r + '%s):\n' % parentType r = r + identFiller*identValue _r = r else: r = r + ', %s()' % parentType if baseType == 'Enumeration': if classMode: r = r + 'subtypeSpec = %s.subtypeSpec+' % parentType else: r = r + '.subtype(subtypeSpec=' # Python has certain limit on the number of func params if len(typeDef) > 127: r = r + 'ConstraintsUnion(' r = r + 'SingleValueConstraint(' cnt = 1 for e, v in typeDef.items(): if isinstance(v, dict) and 'nodetype' in v and \ v['nodetype'] == 'namednumber': r = r + '%s,' % v['number'] if cnt % 127 == 0: r = r + '), SingleValueConstraint(' cnt = cnt + 1 if len(typeDef) > 127: r = r + ')' if classMode: r = r + ')\n' r = r + identFiller*identValue else: r = r + '))' if classMode: r = r + 'namedValues = NamedValues(' else: r = r + '.subtype(namedValues=NamedValues(' typedesc = list(typeDef.items()) typedesc.sort(key=lambda x: str(x[1])) cnt = 1 for e, v in typedesc: if isinstance(v, dict) and 'nodetype' in v and \ v['nodetype'] == 'namednumber': r = r + '(\"%s\", %s), ' % (e, v['number']) if cnt % 127 == 0: r = r + ') + NamedValues(' cnt = cnt + 1 if classMode: r = r + ')\n' r = r + identFiller*identValue else: r = r + '))' else: if classMode: r = r + '%s):\n' % parentType r = r + identFiller*identValue _r = r else: r = r + ', %s()' % parentType if classMode: if 'format' in typeDef: r = r + 'displayHint = \"%s\"\n' % typeDef['format'] r = r + identFiller*identValue if baseType in __kludgyStringTypes: __subtypeSpec = 'ValueSizeConstraint' else: __subtypeSpec = 'ValueRangeConstraint' single_range = 0 if 'range' in typeDef: single_range = 1 # ATTENTION: libsmi-0.4.5 does not support "ranges". Use libsmi # SVN version or an older patch from Randy Couey: # http://www.glas.net/~ilya/download/tools/pysnmp/libsmi-0.4.5-perl_python_range_union.patch if 'ranges' in typeDef: # if more than one size/range is given, then we need to # create a ConstraintsUnion to hold all of them. if len(typeDef['ranges']) > 1: single_range = 0 if classMode: r = r + 'subtypeSpec = %s.subtypeSpec+ConstraintsUnion(' % parentType else: r = r + '.subtype(subtypeSpec=ConstraintsUnion(' for range in typeDef['ranges']: r = r + '%s(%s,%s),' % (__subtypeSpec, __reprIntVal(range['min']), __reprIntVal(range['max'])) if classMode: r = r + ')\n' r = r + identFiller*identValue else: r = r + '))' # only one size/range constraint was given if single_range: if classMode: r = r + 'subtypeSpec = %s.subtypeSpec+%s(%s,%s)\n' % (parentType, __subtypeSpec, __reprIntVal(typeDef['range']['min']), __reprIntVal(typeDef['range']['max'])) r = r + identFiller*identValue if baseType in __kludgyStringTypes and \ typeDef['range']['min'] == typeDef['range']['max']: r = r + 'fixedLength = %s\n' % typeDef['range']['min'] r = r + identFiller*identValue else: r = r + '.subtype(subtypeSpec=%s(%s, %s))' % (__subtypeSpec, __reprIntVal(typeDef['range']['min']), __reprIntVal(typeDef['range']['max'])) if baseType in __kludgyStringTypes and \ typeDef['range']['min'] == typeDef['range']['max']: r = r + '.setFixedLength(%s)' % typeDef['range']['min'] if 'default' in symDef and 'basetype' not in symDef: defVal, inHex = __genDefVal(baseType, symDef) if defVal is not None: if classMode: if inHex: r = r + 'defaultHexValue = %s\n' % defVal else: r = r + 'defaultValue = %s\n' % defVal else: if inHex: r = r + '.clone(hexValue=%s)' % defVal else: r = r + '.clone(%s)' % defVal if classMode: if r == _r: r = r + 'pass\n' r = r + '\n' return r out.write( "# PySNMP SMI module. Autogenerated from smidump -f python %s\n" % dstModName ) out.write( "# by libsmi2pysnmp-%s at %s,\n" % (version, time.asctime(time.localtime())) ) out.write("# Python version %s\n\n" % str(sys.version_info)) out.write('# Imports\n\n') # smidump sometimes does not fully convert into SMIv2 __replacementModules = { ('RFC1213-MIB', 'mib-2'): ('SNMPv2-SMI', 'mib-2'), ('RFC1213-MIB', 'transmission'): ('SNMPv2-SMI', 'transmission'), ('RFC1213-MIB', 'ifIndex'): ('IF-MIB', 'ifIndex'), ('RFC1213-MIB', 'ifAdminStatus'): ('IF-MIB', 'ifAdminStatus'), ('RFC1213-MIB', 'ifOperStatus'): ('IF-MIB', 'ifOperStatus'), ('RFC1213-MIB', 'PhysAddress'): ('SNMPv2-TC', 'PhysAddress'), ('RFC1213-MIB', 'ipAdEntAddr'): ('IP-MIB', 'ipAdEntAddr') } imports = {} for imp in ( { 'module': 'ASN1', 'name': 'Integer' }, { 'module': 'ASN1', 'name': 'OctetString' }, { 'module': 'ASN1', 'name': 'ObjectIdentifier' }, { 'module': 'ASN1-ENUMERATION', 'name': 'NamedValues' }, { 'module': 'ASN1-REFINEMENT', 'name': 'ConstraintsUnion' }, { 'module': 'ASN1-REFINEMENT', 'name': 'ConstraintsIntersection' }, { 'module': 'ASN1-REFINEMENT', 'name': 'SingleValueConstraint' }, { 'module': 'ASN1-REFINEMENT', 'name': 'ValueRangeConstraint' }, { 'module': 'ASN1-REFINEMENT', 'name': 'ValueSizeConstraint' }, { 'module': 'SNMPv2-SMI', 'name': 'Bits' }, # XXX { 'module': 'SNMPv2-SMI', 'name': 'Integer32' }, # libsmi bug { 'module': 'SNMPv2-SMI', 'name': 'TimeTicks' }, # bug in some IETF MIB { 'module': 'SNMPv2-SMI', 'name': 'MibIdentifier' }, # OBJECT IDENTIFIER ) + mib.get('imports', ()): if (imp['module'], imp['name']) in __replacementModules: imp['module'], imp['name'] = __replacementModules[ (imp['module'], imp['name']) ] if imp['module'] not in imports: imports[imp['module']] = [] if not imp['module']: sys.stderr.write('WARNING: empty MIB module name seen in smidump output at %s\n' % dstModName) imports[imp['module']].append(imp['name']) [ x.sort() for x in imports.values() ] modNames = list(imports.keys()); modNames.sort() for modName in modNames: out.write('( ') for symName in imports[modName]: for s in symTrans(symName): out.write('%s, ' % transOpers(s)) out.write(') = mibBuilder.importSymbols(\"%s\"' % modName) for symName in imports[modName]: for s in symTrans(symName): out.write(', \"%s\"' % s) out.write(')\n') if 'typedefs' in mib: typedefs = [ item for item in mib['typedefs'].items() if 'parent module' not in item[1] ] typedefs.sort() typedefs_left = [ item for item in mib['typedefs'].items() if 'parent module' in item[1] ] typedefs_left.sort() typedefs_seen = set([ item[0] for item in typedefs ]) while len(typedefs_left): delayed = [] for t in typedefs_left: if t[1]['parent module']['name'] in ( \ # implicitly imported MIBs 'SNMPv2-TC', 'SNMPv2-SMI' ) or t[1]['parent module']['type'] in typedefs_seen: typedefs_seen.add(t[0]) typedefs.append(t) continue delayed.append(t) if len(delayed) == len(typedefs_left): for t in typedefs_left: sys.stderr.write('WARNING: unresolved type %s(%s::%s)\n' % (t[0], t[1]['parent module']['name'], t[1]['parent module']['type'])) sys.stderr.write('WARNING: %d unresolvable types used\n' % len(delayed)) typedefs.extend(typedefs_left) break typedefs_left = delayed else: typedefs = () if typedefs: out.write('\n# Types\n\n') for symName, symDef in typedefs: out.write('%s' % __genTypeDef(symName, symDef, 1)) if dstModName in mib and 'identity node' in mib[dstModName]: moduleIdentityNode = mib[dstModName]['identity node'] else: moduleIdentityNode = '' if 'nodes' in mib: nodes = list(mib['nodes'].items()) nodes.sort(key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ]) else: nodes = () if nodes: out.write('\n# Objects\n\n') row_create = {} for symName, symDef in nodes: if symDef['nodetype'] == 'node': out.write('%s = ' % transOpers(symName)) if symName == moduleIdentityNode: out.write('ModuleIdentity(%s)' % __oidToTuple(symDef['oid'])) if dstModName in mib: m = mib[dstModName] if 'revisions' in m: out.write('.setRevisions((') for r in m["revisions"]: out.write('\"%s\",' % r["date"]) out.write('))') out.write('%s' % addLabelForSymbol(symName)) if genTextLoader: if 'organization' in m: out.write('\nif mibBuilder.loadTexts: %s.setOrganization("%s")' % (transOpers(symName), m['organization'].replace('\n', '\\n'))) if 'contact' in m: out.write('\nif mibBuilder.loadTexts: %s.setContactInfo("%s")' % (transOpers(symName), m['contact'].replace('\n', '\\n'))) if 'description' in m: out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), m['description'].replace('\n', '\\n'))) out.write('\n') continue elif 'description' in symDef: out.write('ObjectIdentity(%s)' % __oidToTuple(symDef['oid'])) else: out.write('MibIdentifier(%s)' % __oidToTuple(symDef['oid'])) elif symDef['nodetype'] == 'scalar': out.write('%s = ' % transOpers(symName)) out.write('MibScalar(%s' % __oidToTuple(symDef['oid'])) out.write('%s)' % __genTypeDef(symName, symDef)) out.write('.setMaxAccess(\"%s\")' % symDef['access']) if 'units' in symDef: out.write('.setUnits(\"%s\")' % symDef['units']) elif symDef['nodetype'] == 'table': out.write('%s = ' % transOpers(symName)) out.write('MibTable(%s)' % __oidToTuple(symDef['oid'])) elif symDef['nodetype'] == 'row': out.write('%s = ' % transOpers(symName)) # determine if row creation is permitted, and store # status for later inspection by column nodes. if 'create' in symDef: row_create[symDef['oid']] = symDef['create'] else: row_create[symDef['oid']] = 'false' out.write('MibTableRow(%s)' % __oidToTuple(symDef['oid'])) if symDef['linkage'] and isinstance(symDef['linkage'][0], str): out.write('.setIndexNames(') cnt = 0 for idx in symDef['linkage']: if cnt: out.write(', ') else: cnt = cnt + 1 # smidump does not distinguish outer/inner indices for _modName, _symNames in imports.items(): for _symName in _symNames: if _symName == idx: modName = _modName break else: continue break else: modName = dstModName if idx == symDef['linkage'][-1] and \ 'implied' in symDef and \ symDef['implied'] == 'true': impliedFlag = 1 else: impliedFlag = 0 out.write('(%d, \"%s\", \"%s\")' % ( impliedFlag, modName, idx )) out.write(')') elif symDef['nodetype'] == 'column': out.write('%s = ' % transOpers(symName)) out.write('MibTableColumn(%s' % __oidToTuple(symDef['oid'])) out.write('%s)' % __genTypeDef(symName, symDef)) # smidump does not tag columns as read-create. # we must check the parent row object to determine if column is # createable parent = '.'.join(symDef['oid'].split('.')[:-1]) if row_create[parent] == 'true' and symDef['access']=='readwrite': out.write('.setMaxAccess(\"%s\")' % 'readcreate') else: out.write('.setMaxAccess(\"%s\")' % symDef['access']) elif symDef['nodetype'] == 'capabilities': out.write('%s = ' % transOpers(symName)) out.write('AgentCapabilities(%s)' % __oidToTuple(symDef['oid'])) else: sys.stderr.write('Warning: skipping unknown node type %s, oid %s\n' % (symDef['nodetype'], symName)) continue out.write('%s' % addLabelForSymbol(symName)) if genTextLoader: if 'description' in symDef: out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n'))) out.write('\n') out.write('\n# Augmentions\n') for symName, symDef in mib['nodes'].items(): if symDef['nodetype'] == 'row': if symDef['linkage'] and isinstance(symDef['linkage'][0], dict): for idx in symDef['linkage']: for m, indices in idx.items(): if m != dstModName: out.write( '%s, = mibBuilder.importSymbols(\"%s\", \"%s\")\n'%( transOpers(indices['relatedNode']), m, indices['relatedNode'] )) out.write( '%s.registerAugmentions((\"%s\", \"%s\"))\n' % ( indices['relatedNode'], dstModName, symName )) out.write('%s.setIndexNames(*%s.getIndexNames())\n' % ( symName, transOpers(indices['relatedNode']) )) if 'notifications' in mib: notifications = list(mib['notifications'].items()) notifications.sort( key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ] ) else: notifications = () if notifications: out.write('\n# Notifications\n\n') for symName, symDef in notifications: out.write('%s = ' % transOpers(symName)) if symDef['nodetype'] == 'notification': out.write('NotificationType(%s)' % __oidToTuple(symDef['oid'])) out.write('.setObjects(*(') for objName, objDef in symDef['objects'].items(): if (objDef['module'], objName) in __replacementModules: objDef['module'], objName = __replacementModules[ (objDef['module'], objName) ] out.write('(\"%s\", \"%s\"), ' % (objDef['module'], objName)) out.write(') )') out.write('%s' % addLabelForSymbol(symName)) if genTextLoader: if 'description' in symDef: out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n'))) out.write('\n') if 'groups' in mib: groups = list(mib['groups'].items()) groups.sort(key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ]) else: groups = () if groups: out.write('\n# Groups\n\n') for symName, symDef in groups: out.write('%s = ' % transOpers(symName)) if symDef['nodetype'] == 'group': if symName.find('otification') < 0: # hackerish out.write('ObjectGroup(') else: out.write('NotificationGroup(') out.write('%s)' % __oidToTuple(symDef['oid'])) out.write('.setObjects(*(') for objName, objDef in symDef['members'].items(): if (objDef['module'], objName) in __replacementModules: objDef['module'], objName = __replacementModules[ (objDef['module'], objName) ] out.write('(\"%s\", \"%s\"), ' % (objDef['module'], objName)) out.write(') )') out.write('%s' % addLabelForSymbol(symName)) if genTextLoader: if 'description' in symDef: out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n'))) out.write('\n') if 'compliances' in mib: compliances = list(mib['compliances'].items()) compliances.sort( key=lambda x: [ int(y) for y in x[1].get('oid').split('.') ] ) else: compliances = () if compliances: out.write('\n# Compliances\n\n') for symName, symDef in compliances: out.write('%s = ' % transOpers(symName)) if symDef['nodetype'] == 'compliance': out.write('ModuleCompliance(') out.write('%s)' % __oidToTuple(symDef['oid'])) if 'requires' in symDef: out.write('.setObjects(*(') for objName, objDef in symDef['requires'].items(): if (objDef['module'], objName) in __replacementModules: objDef['module'], objName = __replacementModules[ (objDef['module'], objName) ] # XXX nodetype not stored out.write('(\"%s\", \"%s\"), ' % (objDef['module'], objName)) out.write(') )') # XXX refinements not stored out.write('%s' % addLabelForSymbol(symName)) if genTextLoader: if 'description' in symDef: out.write('\nif mibBuilder.loadTexts: %s.setDescription("%s")' % (transOpers(symName), symDef['description'].replace('\n', '\\n'))) out.write('\n') out.write('\n# Exports\n\n') if moduleIdentityNode: out.write('# Module identity\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) out.write(', PYSNMP_MODULE_ID=%s' % transOpers(moduleIdentityNode)) out.write(')\n\n') if typedefs: out.write('# Types\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) idx = 1 for symName, symObj in typedefs: if idx % 127 == 0: out.write(')\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) out.write(', %s=%s' % (symName, symName)) idx = idx + 1 out.write(')\n\n') if nodes: out.write('# Objects\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) idx = 1 for symName, symObj in nodes: if idx % 127 == 0: out.write(')\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) out.write(', %s=%s' % ((transOpers(symTrans(symName)[0]),)*2)) idx = idx + 1 out.write(')\n\n') if notifications: out.write('# Notifications\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) idx = 1 for symName, symObj in notifications: if idx % 127 == 0: out.write(')\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) out.write(', %s=%s' % ((transOpers(symName),)*2)) idx = idx + 1 out.write(')\n\n') if groups: out.write('# Groups\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) idx = 1 for symName, symObj in groups: if idx % 127 == 0: out.write(')\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) out.write(', %s=%s' % ((transOpers(symName),)*2)) idx = idx + 1 out.write(')\n\n') if compliances: out.write('# Compliances\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) idx = 1 for symName, symObj in compliances: if idx % 127 == 0: out.write(')\n') out.write('mibBuilder.exportSymbols(\"%s\"' % dstModName) out.write(', %s=%s' % ((transOpers(symName),)*2)) idx = idx + 1 out.write(')\n') # XXX # implement API version checking pysnmp-4.2.5/LICENSE0000644000076400001440000000246212122114472014176 0ustar ilyausers00000000000000Copyright (c) 2005-2013, 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.