.\" Man page generated from reStructuredText. . . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .TH "PYSNMP" "1" "Sep 04, 2023" "4.4" "SNMP library for Python" .SH NAME pysnmp \- PySNMP Documentation .sp PySNMP is a cross\-platform, pure\-\fI\%Python\fP \fI\%SNMP\fP engine implementation. It features fully\-functional SNMP engine capable to act in Agent/Manager/Proxy roles, talking SNMP v1/v2c/v3 protocol versions over IPv4/IPv6 and other network transports. .sp Despite its name, SNMP is not really a simple protocol. For instance its third version introduces complex and open\-ended security framework, multilingual capabilities, remote configuration and other features. PySNMP implementation closely follows intricate system details and features bringing most possible power and flexibility to its users. .sp Current PySNMP stable version is 4.4. It runs with Python 2.4 through 3.7 and is recommended for new applications as well as for migration from older, now obsolete, PySNMP releases. All site documentation and examples are written for the 4.4 and later versions in mind. Older materials are still available under the obsolete section. .sp Besides the libraries, a set of pure\-Python \fI\%command\-line tools\fP are shipped along with the system. Those tools mimic the interface and behaviour of popular Net\-SNMP snmpget/snmpset/snmpwalk utilities. They may be useful in a cross\-platform situations as well as a testing and prototyping instrument for pysnmp users. .sp PySNMP software is free and open\-source. Source code is hosted in a \fI\%Github repo\fP\&. The library is being distributed under 2\-clause BSD\-style license. .sp PySNMP library development has been initially sponsored by a \fI\%PSF\fP grant. .SH QUICK START .sp You already know something about SNMP and have no courage to dive into this implementation? Try out quick start page! .SS Quick start .sp Once you downloaded and installed PySNMP library on your Linux/Windows/OS X system, you should be able to solve the very basic SNMP task right from your Python prompt \- fetch some data from a remote SNMP Agent (you\(aqd need at least version 4.3.0 to run code from this page). .SS Fetch SNMP variable .sp So just cut&paste the following code right into your Python prompt. The code will performs SNMP GET operation for a sysDescr.0 object at a publically available SNMP Command Responder at \fI\%demo.snmplabs.com\fP: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp If everything works as it should you will get: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C \&... SNMPv2\-MIB::sysDescr.\(dq0\(dq = SunOS zeus.snmplabs.com 4.1.3_U1 1 sun4m >>> .ft P .fi .UNINDENT .UNINDENT .sp on your console. .SS Send SNMP TRAP .sp To send a trivial TRAP message to our hosted Notification Receiver at \fI\%demo.snmplabs.com\fP , just cut&paste the following code into your interactive Python session: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp Many ASN.1 MIB files could be downloaded from \fI\%mibs.snmplabs.com\fP or PySNMP could be \fI\%configured\fP to download them automatically. .sp For more sophisticated examples and use cases please refer to \fI\%examples\fP and \fI\%library reference\fP pages. .SH DOCUMENTATION .SS Documentation .SS SNMP history .sp In the early days of networking, when computer networks were research artifacts rather than a critical infrastructure used by almost every second human on Earth, \(dqnetwork management\(dq was practically unknown. Whenever one encountered a network problem, he might run a few pings to locate the source of the problem and then modify system settings, reboot hardware or software, or call a remote colleague to check console at the machine room. .sp An interesting discussion of the first major \(dqcrash\(dq of the ARPAnet in 1980, long before network management tools were available, and the efforts taken to recover from and understand the crash can be read in \fI\%RFC 789\fP\&. The astonishment of the engineers taking part in post\-mortem investigation could be read between the lines. As the public Internet and private intranets have grown from small networks into a large global infrastructure, the need to more systematically manage the huge number of hardware and software components within these networks has grown more important as well. .sp SNMP was quickly designed and deployed by a group of university network researchers and users at a time when the need for network management was becoming painfully clear. .sp SNMP milestones: .INDENT 0.0 .IP \(bu 2 Research project, successor of SGMP .IP \(bu 2 SNMPv1 in 1988: initial revision .IP \(bu 2 SNMPv2 in 1993: improvements .IP \(bu 2 SNMPv3 in 1999: full redesign .IP \(bu 2 SNMPv3: backward compatible .IP \(bu 2 SNMPv3: full Internet standard (STD0062) .UNINDENT .sp SNMP was initially thought as an interim solution to fill the need for network management tool while a more theoretically sound system was being developed by the ISO. Anticipating the transition to the new network management system, SNMP designers made SNMP modular. Although that transition never occurred, the modularity of SNMP help it evolving through three major versions and found widespread use and acceptance. .sp The IETF recognizes SNMP version 3 as defined by \fI\%RFC 3411\fP .. \fI\%RFC 3418\fP as the current standard version of SNMP. The IETF has designated SNMPv3 a full Internet standard, the highest maturity level for an RFC. In practice, SNMP implementations often support multiple versions: typically SNMPv1, SNMPv2c, and SNMPv3 .SS Is it still relevant? .sp Considering how old SNMP is you might be wondering why it is still in use and is there a more modern alternative? Apparently, SNMP is still the primary way to do performance and fault management. SNMP is universally supported by all networking hardware manufactures and network management applications. .sp Perhaps one reason for SNMP being so tenacious is that, considering SNNP\(aqs wide deployment, it takes too much effort to migrate to anything else. But the other reason is that no significant drawbacks have been found in SNMP at least in the areas of fault and performance management. .sp Additionally, SNMP is free and not controlled by any particular vendor. No copyright or licensing fees are required, so anyone can use it or build SNMP products on it. .sp Despite significant efforts made by technology companies and standards bodies over all these years, no other network monitoring standard was adopted so far. The most prominent open alternative is probably NETCONF (\fI\%RFC 6241\fP). However it mostly targets configuration management tasks rather than fault or performance monitoring. Additionally, NETCONF is significantly more resource intensive than SNMP is. .sp It is obviously possible to for everybody to come up with its own ad\-hoc management system. That can be done very easily on top of HTTPS/JSON, for example. However that would only work with your application. Also, SSL engine might be heavier on resources. .SS Current and future uses .sp As for current SNMP deployment, its virtually impossible to estimate how many SNMP\-enabled devices run on the modern Internet today. For example, every home router and most of the desktop printers have embedded SNMP agent inside. .sp Expanding on that, you may found SNMP useful for your home network monitoring. For instance you could easily setup an open source network monitoring application to watch, collect and graph bandwidth utilization of your home Wi\-Fi router. .sp A significant innovation might be coming in the following years. And that is Internet of Things. All those small and low\-power gadgets need to be monitored and managed. And that may bring new life to the SNMP technology. Almost three decades ago SNMP was designed for heavily resource\-constrained computers of that time. Later on the computers grew in power and resources. But now we are back to building a massive amount of low\-power computers for \(dqthings\(dq where original lightweight and well\-understood SNMP can serve us again! .SS SNMP design .sp Contrary to what the name might suggest, SNMP is much more than just a protocol for moving management data. Over time it has grown to be more complex than its initial designers probably planned it. .SS Terminology and entities .sp The network management field has its own specific terminology for various components of a network management architecture, and so we adopt that terminology here. The peculiarity of this terminology is that the word \(dqmanagement\(dq is greatly overused. So bare with it. .sp There are three principle components of a network management architecture: a managing entity, the managed entity, and a network management protocol. [image] .INDENT 0.0 .IP \(bu 2 The managing entity is an application running in a centralized network management station (NMS). It is the managing entity that controls the collection, processing, analysis, and/or display of network management information. It is here that actions are initiated to control network behavior and here that the human network administrator interacts with the network devices. .IP \(bu 2 A managed entity is typically hardware or software application that resides on a managed network. It enumerates and formalizes some of its properties and states, important for healthy operation, thus making them available to the managing entity. For example, a managed entity could be a host, router, switch, printer, or any other device. .IP \(bu 2 The third piece of a network management system is the network management protocol. The protocol runs between the managing entity and the managed entity, allowing the managing entity to query the status of managed entity and make the latter carrying out actions via its agents. .UNINDENT .SS Structure and components .sp SNMP consists of four parts: .INDENT 0.0 .IP \(bu 2 Definitions of network management objects known as MIB objects. Management information is represented as a collection of managed objects that together form a virtual information store, known as the Management Information Base (MIB). A MIB object might be a counter, descriptive information such as software version; status information such as whether or not a device is healthy, or protocol\-specific information such as a routing path to a destination. MIB objects thus define the management information maintained by a managed node. Related MIB objects are gathered into so\-called MIB modules. .IP \(bu 2 Data definition language, called SMI (Structure of Management Information) that introduces base data types, allows for creating their subtypes and more complex data structures. MIB objects are expressed in this data definition language. .IP \(bu 2 Protocol (SNMP) for conveying information and commands between a managing and managed entities. SNMP is designed around a client\-server model. What\(aqs interesting that both managing and managed entities contain client and server components. .IP \(bu 2 Extensible security framework and system administration capabilities. .UNINDENT .sp The latter features were completely absent in SNMP versions prior to SNMPv3. .SS Data types .sp SMI introduces eleven base data types used for representing managed objects states. They are either pure ASN.1 types or their specializations. Pure ASN.1 types: .INDENT 0.0 .IP \(bu 2 INTEGER .IP \(bu 2 OCTET STRING .IP \(bu 2 OBJECT IDENTIFIER .UNINDENT .sp ASN.1 is a really aged and quite complex set of standards that deals with structuring and serializing data in a portable way. .sp SNMP\-specific subtypes of those base ASN.1 types are: .INDENT 0.0 .IP \(bu 2 Integer32/Unsigned32 \- 32\-bit integer .IP \(bu 2 Counter32/Counter64 \- ever increasing number .IP \(bu 2 Gauge32 \- positive, non\-wrapping 31\-bit integer .IP \(bu 2 TimeTicks \- time since some event .IP \(bu 2 IPaddress \- IPv4 address .IP \(bu 2 Opaque \- uninterpreted ASN.1 string .UNINDENT .sp In addition to these scalar types, SNMP defines a way to collect them into ordered arrays. From these arrays 2\-d tables could be built. .sp PySNMP relies on the \fI\%PyASN1\fP package for modeling all SNMP types. With PyASN1, instances of ASN.1 types are represented by Python objects that look like either a string or an integer. .sp We can convert PyASN1 objects into Python types and back. PyASN1 objects can participate in basic arithmetic operations (numbers) or in operations with strings (concatenation, subscription etc). All SNMP base types are immutable like their Python counterparts. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pyasn1.type.univ import * >>> Integer(21) * 2 Integer(42) >>> Integer(\-1) + Integer(1) Integer(0) >>> int(Integer(42)) 42 >>> OctetString(\(aqHello\(aq) + \(aq, \(aq + >>> OctetString(hexValue=\(aq5079534e4d5021\(aq) OctetString(\(aqHello, PySNMP!\(aq) .ft P .fi .UNINDENT .UNINDENT .sp Users of PySNMP library may encounter PyASN1 classes and objects when passing data to or receiving data from PySNMP. .sp The one data type we will discuss in more detail shortly is the OBJECT IDENTIFIER data type, which is used to name an object. With this system, objects are identified in a hierarchical manner. .SS Object Identifier .sp OIDs are widly used in computing for identifying objects. This system can be depicted as a tree whose nodes are assigned by different organizations, knowledge domains, types of concepts or objects, concrete instances of objects. From human perspective, an OID is a long sequence of numbers, coding the nodes, separated by dots. [image] .sp Each \(aqbranch\(aq of this tree has a number and a name, and the complete path from the top of the tree down to the point of interest forms the name of that point. This complete path is the OID, the \(dqidentifier of an object\(dq respectively. Nodes near the top of the tree are of an extremely general nature. .sp Top level MIB object IDs (OIDs) belong to different standard organizations. Vendors define private branches including managed objects for their own products. .sp At the top of the hierarchy are the International Organization for Standardization (ISO) and the Telecommunication Standardization Sector of the International Telecommunication Union (ITU\-T), the two main standards organizations dealing with ASN.1, as well as a brach for joint efforts by these two organizations. .sp In PyASN1 model, OID looks like an immutable sequence of numbers. Like it is with Python tuples, PyASN1 OID objects can be concatinated or split apart. Subscription operation returns a numeric sub\-OID. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pyasn1.type.univ import * >>> internetId = ObjectIdentifier((1, 3, 6, 1)) >>> internetId ObjectIdentifier(\(aq1.3.6.1\(aq) >>> internetId[2] 6 >>> [ x for x in internetId ] [1, 3, 6, 1] >>> internetId + (2,) ObjectIdentifier(\(aq1.3.6.1.2\(aq) >>> internetId[1:3] ObjectIdentifier(\(aq3.6\(aq) >>> internetId[1] >>> = 2 \&... TypeError: object does not support item assignment .ft P .fi .UNINDENT .UNINDENT .SS Collections of objects .sp Management Information Base (MIB) can be thought of as a formal description of a collection of relevant managed objects whose values collectively reflect the current \(dqstate\(dq of some subsystem at a managed entity. These values may be queried, modified by or reported to a managing entity by sending SNMP messages to the agent that is executing in a managed node. .sp For example, the typical objects to monitor on a printer are the different cartridge states and maybe the number of printed files, and on a switch the typical objects of interest are the incoming and outgoing traffic as well as the rate of package loss or the number of packets addressed to a broadcast address. .sp Every managed device keeps a database of values for each of the definitions written in the MIB. So, the available data is actually not dependent on the database, but on the implementation. It is important to realize that MIB files never contain data, they are functionally similar to database schemas rather than data stores. .sp To organize MIB modules and objects properly, all the manageable features of all products (from each vendor) are arranged in this MIB tree structure. Each MIB module and object is uniquely identified by an Object Identifier. .sp Both SNMP managed and managing entities could consume MIB information. .INDENT 0.0 .IP \(bu 2 Managing entity .INDENT 2.0 .IP \(bu 2 Looks up OID by MIB object name .IP \(bu 2 Casts value to proper type of MIB object .IP \(bu 2 Humans read comments left by other humans .UNINDENT .IP \(bu 2 Managed entity .INDENT 2.0 .IP \(bu 2 Implements MIB objects in code .UNINDENT .UNINDENT .sp From human perspective, MIB is a text file written in a subset of ASN.1 language. We maintain \fI\%a collection\fP of 9000+ MIB modules that you can use for your projects. .sp PySNMP converts ASN.1 MIB files into Python modules, then SNMP engine loads those modules at runtime on demand. PySNMP MIB modules are universal \-\- the same module can be consumed by both managed and managing entities. .sp MIB conversion is performed automatically by PySNMP, but technically, it is handled by PySNMP sister project called \fI\%PySMI\fP\&. However you can also perform said conversion by hand with PySMI\(aqs \fImibdump.py\fP tool. .SS Protocol operations .sp SNMP is designed around a client\-server model. Both managing and managed entities contain client and server components. Clients and servers exchange data in a name\-value form. Values are strongly typed. .sp Central to protocol entity is \fISNMP engine\fP that coordinates workings of all SNMP components. [image] .sp Two modes of protocol operation are defined: .INDENT 0.0 .IP \(bu 2 Request\-response messages .IP \(bu 2 Unsolicited messages .UNINDENT .sp Protocol carries SNMP messages. Besides header information used for protocol operations, management information is transferred in so\-called Protocol Data Units (PDU). Seven PDU types are defined in SNMP addressing conceptually different operations to be performed by either managing or managed entities (Manager or Agent repectively). .INDENT 0.0 .IP \(bu 2 Manager\-to\-agent .INDENT 2.0 .IP \(bu 2 GetRequest, SetRequest, GetNextRequest, GetBulkRequest, InformRequest .UNINDENT .IP \(bu 2 Manager\-to\-manager .INDENT 2.0 .IP \(bu 2 InformRequest, Response .UNINDENT .IP \(bu 2 Agent\-to\-manager .INDENT 2.0 .IP \(bu 2 SNMPv2\-Trap, Response .UNINDENT .UNINDENT .SS Core applications .sp The standard (\fI\%RFC 3413\fP) identifies a few \(dqstandard\(dq SNMP applications that are associated with either managing or managed entities. [image] .sp PySNMP implements all these standard applications (via \fINative SNMP API\fP) carefully following RFCs and their abstract service interfaces. The backside of this approach is that it\(aqs way too detailed and verbose for most SNMP tasks. To make SNMP easy to use, PySNMP introduces \fIHigh\-level SNMP API\fP\&. .SS PySNMP architecture .sp We can look at PySNMP\(aqs internal structure from the view point of SNMP protocol evolution. SNMP was evolving for many years from a relatively simple way to structure and retrieve data (SNMPv1/v2c) all the way to extensible and modularized framework that supports strong crypto out\-of\-the\-box (SNMPv3). .sp In the order from most ancient SNMP services to the most current ones, what follows are different layers of PySNMP APIs: .INDENT 0.0 .IP \(bu 2 The most basic and low\-level is SNMPv1/v2c protocol scope. Here programmer is supposed to build/parse SNMP messages and their payload \-\- Protocol Data Unit (PDU), handle protocol\-level errors, transport issues and so on. Although considered rather complex to deal with, this API probably gives best performance, memory footprint and flexibility, unless MIB access and/or SNMPv3 support is needed. .IP \(bu 2 SNMPv3 standards come with abstract service interfaces to SNMP engines and its components. PySNMP implementation adopts this abstract API to a great extent, so it can be used directly. As additional benefit, SNMP RFCs could be referred to API semantics when programming PySNMP at this level. User could implements his own SNMP application using this API. .IP \(bu 2 SNMPv3 (\fI\%RFC 3413\fP) introduced a concept of core \(dqSNMP Applications\(dq. PySNMP implements them all (in \fIpysnmp.entity.rfc3413\fP), so user can base his application right on top of one (or multiple) of those SNMP core applications. .IP \(bu 2 Finally, to make SNMP more simple for, at least, most frequent tasks, PySNMP comes with a high\-level API to core SNMP applications and some of SNMP engine services. This API is known under the name \fIpysnmp.hlapi\fP and should be used whenever possible. .UNINDENT .sp Another view to PySNMP internals could be from the code standpoint: PySNMP consists of a handful of large, self\-contained components with well\-defined interfaces. The following figure explains PySNMP functional structure. [image] .sp PySNMP inner components: .INDENT 0.0 .IP \(bu 2 SNMP Engine is a central, umbrella object that controls the other components of the SNMP system. Typical user application has a single instance of SNMP Engine class possibly shared by many SNMP Applications of all kinds. As the other linked\-in components tend to buildup various configuration and housekeeping information in runtime, SNMP Engine object appears to be expensive to configure to a usable state. .IP \(bu 2 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. .IP \(bu 2 Message and PDU Dispatcher is the locus of SNMP message processing activities. Its main responsibilities include dispatching PDUs from SNMP Applications through various subsystems all the way down to Transport Dispatcher, and passing SNMP messages coming from network up to SNMP Applications. It maintains logical connection with Management Instrumentation Controller which carries out operations on Managed Objects, here for the purpose of LCD access. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 Access Control subsystem uses LCD information to authorize remote access to Managed Objects. This is used when running in agent role. .IP \(bu 2 A collection of MIB modules and objects that are used by SNMP engine for keeping its configuration and operational statistics. They are collectively called Local Configuration Datastore (LCD). .UNINDENT .sp In most cases user is expected to only deal with the high\-level API to all these PySNMP components. However implementing SNMP Agents, Proxies and some non\-trivial features of managers require using the Standard Applications API. In those cases general understanding of SNMP operations and SNMP Engine components would be helpful. .SS Common operations .sp In this tutorial we will gradually build and run a few different SNMP command requests and notifications. We will be using PySNMP synchronous \fI\%high\-level API\fP which is the simplest to use. .SS Creating SNMP Engine .sp SNMP engine is a central, umbrella object in PySNMP. All PySNMP operations involve \fBSnmpEngine\fP class instance. PySNMP app can run multiple independent SNMP engines each guided by its own \fISnmpEngine\fP object. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> SnmpEngine() SnmpEngine(snmpEngineID=OctetString(hexValue=\(aq80004fb80567\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp SNMP engine has unique identifier that can be assigned automatically or administratively. This identifier is used in SNMP protocol operations. .SS Making SNMP query .sp We will send SNMP GET command to read a MIB object from SNMP agent. For that purpose we will call synchronous, high\-level \fBgetCmd()\fP function. Other SNMP commands can be used in a vary similar way by calling corresponding functions. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> [ x for x in dir() if \(aqCmd\(aq in x] [\(aqbulkCmd\(aq, \(aqgetCmd\(aq, \(aqnextCmd\(aq, \(aqsetCmd\(aq] >>> getCmd .ft P .fi .UNINDENT .UNINDENT .SS Choosing SNMP protocol and credentials .sp We have a choice of three SNMP protocol versions. To employ SNMP versions 1 or 2c, we pass properly initialized instance of \fBCommunityData\fP class. For the third SNMP version we pass \fBUsmUserData\fP class instance. .sp SNMP community name, as well as the choice between SNMP v1 and v2c, is conveyed to SNMP LCD via \fBCommunityData\fP object. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> CommunityData(\(aqpublic\(aq, mpModel=0) # SNMPv1 CommunityData(\(aqpublic\(aq) >>> CommunityData(\(aqpublic\(aq, mpModel=1) # SNMPv2c CommunityData(\(aqpublic\(aq) .ft P .fi .UNINDENT .UNINDENT .sp Use of \fBUsmUserData\fP object for LCD configuration implies using SNMPv3. Besides setting up USM user name, \fIUsmUserData\fP object can also carry crypto keys and crypto protocols to SNMP engine LCD. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> UsmUserData(\(aqtestuser\(aq, authKey=\(aqmyauthkey\(aq) UsmUserData(userName=\(aqtestuser\(aq, authKey=) >>> UsmUserData(\(aqtestuser\(aq, authKey=\(aqmyauthkey\(aq, privKey=\(aqmyenckey\(aq) UsmUserData(userName=\(aqtestuser\(aq, authKey=, privKey=) .ft P .fi .UNINDENT .UNINDENT .sp PySNMP supports MD5 and SHA message authentication algorithms, DES, AES128/192/256 and 3DES encryption algoritms. .sp For sake of simplicity, let\(aqs use SNMPv2. Although completely insecure, it\(aqs still the most popular SNMP version in use. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), \&... .ft P .fi .UNINDENT .UNINDENT .SS Setting transport and target .sp PySNMP supports UDP\-over\-IPv4 and UDP\-over\-IPv6 network transports. In this example we will query \fI\%public SNMP Simulator\fP available over IPv4 on the Internet at \fIdemo.snmplabs.com\fP\&. Transport configuration is passed to SNMP LCD in form of properly initialized \fBUdpTransportTarget\fP or \fBUdp6TransportTarget\fP objects respectively. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... .ft P .fi .UNINDENT .UNINDENT .SS Addressing SNMP context .sp SNMP context is a parameter in SNMP (v3) message header that addresses specific collection of MIBs served by SNMP engine at managed entity. SNMP engine could serve many identical MIB objects representing completely different instances of hardware or software being managed. This is where SNMP context could be used. .sp To indicate SNMP context at high\-level API a properly initialized \fBContextData\fP object should be used. For this example we will use the \(aqempty\(aq context (default). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... .ft P .fi .UNINDENT .UNINDENT .SS Specifying MIB object .sp Finally, we have to specify the MIB object we want to read. On protocol level, MIB objects are identified by OIDs, but humans tend to address them by name: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ snmpget \-v2c \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 SNMPv2\-MIB::sysDescr.0 = STRING: SunOS zeus.snmplabs.com $ $ snmpget \-v2c \-c public demo.snmplabs.com 1.3.6.1.2.1.1.1.0 SNMPv2\-MIB::sysDescr.0 = STRING: SunOS zeus.snmplabs.com .ft P .fi .UNINDENT .UNINDENT .sp Both object name and OID come from MIB. Name and OID linking is done by high\-level SMI construct called \fIOBJECT\-TYPE\fP\&. Here is an example MIB object definition for \fIsysUpTime\fP with OID ...mgmt.mib\-2.system.3 and value type \fITimeTicks\fP\&. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C sysUpTime OBJECT\-TYPE SYNTAX TimeTicks MAX\-ACCESS read\-only STATUS current DESCRIPTION \(dqThe time (in hundredths of a second) since the network management portion of the system was last re\-initialized.\(dq ::= { system 3 } .ft P .fi .UNINDENT .UNINDENT .sp In PySNMP we use the \fBObjectIdentity\fP class that is responsible for MIB objects identification. \fIObjectIdentity\fP represents ways to address MIB object from human perspective. It needs to consult MIB to enter a fully \(dqresolved\(dq state. ObjectIdentity could be initialized with MIB object name, after a MIB look up it starts behaving like an OID. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> x = ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq) >>> # ... calling MIB lookup ... >>> tuple(x) (1, 3, 6, 1, 2, 1, 1, 1) >>> x = ObjectIdentity(\(aqiso.org.dod.internet.mgmt.mib\-2.system.sysDescr\(aq) >>> # ... calling MIB lookup ... >>> str(x) \(aq1.3.6.1.2.1.1.1\(aq .ft P .fi .UNINDENT .UNINDENT .sp MIB resolution means the service of MIB object name into OID transformation or vice versa. .sp The \fBObjectType\fP class instance represents \fIOBJECT\-TYPE\fP SMI constuct in PySNMP. ObjectType is a container object that references ObjectIdentity and SNMP type instances. As a Python object it looks like a tuple of (OID, value). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> x = ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0), \(aqLinux i386 box\(aq)) >>> # ... calling MIB lookup ... >>> x[0].prettyPrint() \(aqSNMPv2\-MIB::sysDescr.0\(aq >>> x[1].prettyPrint() \(aqLinux i386 box\(aq .ft P .fi .UNINDENT .UNINDENT .sp The trailing zero is an indication of MIB object \fIinstance\fP\&. Objects described in MIBs are just declarations, they never contain any data. Data is stored in MIB object instances addressed by appending extra information (known as \fIindex\fP) to MIB object identifiers. .sp For scalar MIB objects index is \(aq0\(aq by convention. The \fIObjectIdentity\fP class takes indices as its initializers. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> x = ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq, 0) >>> # ... calling MIB lookup ... >>> tuple(x) (1, 3, 6, 1, 2, 1, 1, 1, 0) .ft P .fi .UNINDENT .UNINDENT .sp We will be reading \fIsysDescr\fP scalar MIB object instance as defined in \fI\%SNMPv2\-MIB\fP module. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> g = getCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) .ft P .fi .UNINDENT .UNINDENT .sp By default PySNMP will search your local filesystem for ASN.1 MIB files you refer to. It can also be configured to automatically download them from remote hosts, as \fI\%shown\fP in the examples. We maintain a \fI\%collection\fP of ASN.1 MIB modules that you can use in your SNMP projects. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 An \(dqASN.1 MIB\(dq is a plain\-text description of identifiers and types. It is the common format that is distributed by manufacturers to describe their SNMP services, and is the same format used by Perl\(aqs Net::SNMP and almost all SNMP tools. .UNINDENT .UNINDENT .SS Reading scalar value .sp We are finally in a position to send SNMP query and hopefully receive something meaningful in response. .sp The distinctive feature of synchronous API is that it is built around the idea of Python generator. Any function invocation ends up with a generator object. Iteration over the generator object performs actual SNMP communication. On each iteration SNMP message gets built and sent out, response is awaited, received and parsed. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysUpTime\(aq, 0))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.3.0\(aq), TimeTicks(44430646))]) .ft P .fi .UNINDENT .UNINDENT .SS Working with SNMP tables .sp SNMP defines a concept of table. Tables are used when a single given MIB object may apply to many instances of a property. For example, properties of network interfaces are put into SNMP table. Each instance of a property is addressed by a suffix appended to base MIB object. .sp Tables are specified in MIBs, their index (or indices) are declared via the \fIINDEX\fP clause. Table index is non\-zero integer, or string or any base SNMP type. .sp At the protocol level all indices take shape of OID parts. For humans to work with indices comfortably, SNMP management applications rely on DISPLAY\-HINT clause for automatic indices conversion between their OID and SNMP type\-specific, human\-friendly representation. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C ifEntry OBJECT\-TYPE SYNTAX IfEntry INDEX { ifIndex } ::= { ifTable 1 } ifIndex OBJECT\-TYPE SYNTAX InterfaceIndex ::= { ifEntry 1 } ifDescr OBJECT\-TYPE SYNTAX DisplayString (SIZE (0..255)) ::= { ifEntry 2 } InterfaceIndex ::= TEXTUAL\-CONVENTION DISPLAY\-HINT \(dqd\(dq SYNTAX Integer32 (1..2147483647) .ft P .fi .UNINDENT .UNINDENT .sp In PySNMP parlance: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> x = ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifDescr\(aq, 123) >>> # ... calling MIB lookup ... >>> str(x) \(aq1.3.6.1.2.1.2.2.1.2.123\(aq .ft P .fi .UNINDENT .UNINDENT .sp Some SNMP tables are indexed by many indices. Each of these indices become parts of OID concatinated to each other and ultimately to MIB object OID. .sp From semantic standpoint, each index reflects an important and distinct property of a MIB object. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C tcpConnectionEntry OBJECT\-TYPE SYNTAX TcpConnectionEntry INDEX { tcpConnectionLocalAddressType, tcpConnectionLocalAddress, tcpConnectionLocalPort, tcpConnectionRemAddressType, tcpConnectionRemAddress, tcpConnectionRemPort } ::= { tcpConnectionTable 1 } tcpConnectionLocalPort OBJECT\-TYPE SYNTAX InetPortNumber ::= { tcpConnectionEntry 3 } .ft P .fi .UNINDENT .UNINDENT .sp PySNMP\(aqs \fBObjectIdentity\fP class takes any number of indices in human\-friendly representation and converts them into full OID: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> x = ObjectIdentity(\(aqTCP\-MIB\(aq, \(aqtcpConnectionState\(aq, \&... \(aqipv4\(aq, \(aq195.218.254.105\(aq, 41511, \&... \(aqipv4\(aq, \(aq194.67.1.250\(aq, 993) >>> # ... calling MIB lookup ... >>> str(x) \(aq1.3.6.1.2.1.6.19.1.7.1.4.195.218.254.105.41511.1.4.194.67.1.250.993\(aq .ft P .fi .UNINDENT .UNINDENT .sp Let\(aqs read TCP\-MIB::tcpConnectionState object for a TCP connection: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqTCP\-MIB\(aq, \(aqtcpConnectionState\(aq, \&... \(aqipv4\(aq, \(aq195.218.254.105\(aq, 41511, \&... \(aqipv4\(aq, \(aq194.67.1.250\(aq, 993) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(ObjectName(\(aq1.3.6.1.2.1.6.19.1.7.1.4.195.218.254.105.41511.1.4.194.67.1.250.993\(aq)), Integer(5))]) .ft P .fi .UNINDENT .UNINDENT .SS SNMP command operations .sp SNMP allows you to request a MIB object that is \(dqnext\(dq to the given one. That way you can read MIB objects you are not aware about in advance. MIB objects are conceptually sorted by their OIDs. This feature is implemented by the \fBnextCmd()\fP function. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> g = nextCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq), DisplayString(\(aqSunOS zeus.snmplabs.com\(aq))]) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.2.0\(aq), ObjectIdentity(ObjectIdentifier(\(aq1.3.6.1.4.1.8072.3.2.10\(aq)))]) .ft P .fi .UNINDENT .UNINDENT .sp Iteration over the generator object \(dqwalk\(dq over SNMP agent\(aqs MIB objects. .sp SNMPv2c introduced significant optimization to the \fIGETNEXT\fP command \- the revised version is called \fIGETBULK\fP and is capable to gather and respond a bunch of \(dqnext\(dq MIB objects at once. Additional non\-repeaters and max\-repetitions parameters can be used to influence MIB objects batching. .sp PySNMP hides this \fIGETBULK\fP optimization at the protocol level, the \fBbulkCmd()\fP function exposes the same generator API as \fIgetNext()\fP for convenience. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> N, R = 0, 25 >>> g = bulkCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... N, R, \&... ObjectType(ObjectIdentity(\(aq1.3.6\(aq))) >>> >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq), DisplayString(\(aqSunOS zeus.snmplabs.com\(aq))]) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.2.0\(aq), ObjectIdentifier(\(aq1.3.6.1.4.1.20408\(aq))]) .ft P .fi .UNINDENT .UNINDENT .sp Python generators can not only produce data, but it is also possible to send data into running generator object. That feature is used by the high\-level API to repeat the same SNMP operation for a new set of MIB objects. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = nextCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifTable\(aq))) >>> >>> g.send([ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq))]) (None, 0, 0, [(ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.2.2.1.10.1\(aq), Counter32(284817787))]) .ft P .fi .UNINDENT .UNINDENT .sp You could operate on many unrelated MIB object just by listing them in a single PDU. Response PDU will carry a list of MIB objects and their values in exactly the same order as they were in request message. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = getCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), \&... ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysUpTime\(aq, 0)) \&... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq), DisplayString(\(aqSunOS zeus.snmplabs.com\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.3.0\(aq), TimeTicks(44430646))]) .ft P .fi .UNINDENT .UNINDENT .sp Configuration management part of SNMP relies on SNMP \fISET\fP command. Although its implementation on managed entity\(aqs side proved to be somewhat demanding (due to locking and transactional behavior requirements). So vendors tend to leave it out thus rendering managed entity being read\-only. .sp PySNMP supports \fISET\fP uniformly through \fBsetCmd()\fP function. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = setCmd(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), \&... ContextData(), \&... ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0), \(aqLinux i386\(aq) \&... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq), DisplayString(\(aqLinux i386\(aq))]) .ft P .fi .UNINDENT .UNINDENT .SS Sending SNMP notifications .sp Managed entity could send unsolicited messages to the managing entity. That is called notification in SNMP. Notifications help reduce polling, what may become a problem for large networks. .sp SNMP notifications are enumerated and each has definite semantics. This is done through a special, high\-level SMI construct called \fINOTIFICATION\-TYPE\fP\&. Like \fIOBJECT\-TYPE\fP, that defines a MIB object, \fINOTIFICATION\-TYPE\fP has a unique OID, but instead of SNMP value references a sequence of other MIB objects. These MIB objects are specified with the \fIOBJECTS\fP clause and when notification is being sent, their current values are included into the notification message. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C linkUp NOTIFICATION\-TYPE OBJECTS { ifIndex, ifAdminStatus, ifOperStatus } STATUS current DESCRIPTION \(dq...\(dq ::= { snmpTraps 4 } .ft P .fi .UNINDENT .UNINDENT .sp To model \fINOTIFICATION\-TYPE\fP construct in PySNMP, we have the \fBNotificationType\fP class that is a container object. It is identified by the \fBObjectIdentity\fP class and reference a sequence of \fBObjectType\fP class instances. .sp From behavior standpoint, \fINotificationType\fP looks like a sequence of \fIObjectType\fP class instances. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> x = NotificationType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq)) >>> # ... calling MIB lookup ... >>> >>> [ str(y) for x in n ] [\(aqSNMPv2\-MIB::snmpTrapOID.0 = 1.3.6.1.6.3.1.1.5.3\(aq, \(aqIF\-MIB::ifIndex = \(aq, \(aqIF\-MIB::ifAdminStatus = \(aq, \(aqIF\-MIB::ifOperStatus = \(aq] .ft P .fi .UNINDENT .UNINDENT .sp Sending notification with PySNMP is not much different than sending SNMP command. The difference is in how PDU var\-binds are built. There are two different kinds of notifications in SNMP: \fItrap\fP and \fIinform\fP\&. .sp With \fItrap\fP, agent\-to\-manager communication is one\-way \- no response or acknowledgement is sent. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = sendNotification(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), \&... ContextData(), \&... \(aqtrap\(aq, \&... NotificationType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=(123,)) \&... ) >>> next(g) (None, 0, 0, []) .ft P .fi .UNINDENT .UNINDENT .sp The \fIinform\fP notification is much like a command. The difference is in PDU format. Informs are used for manager\-to\-manager communication as well as for agent\-to\-manager. .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> g = sendNotification(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), \&... ContextData(), \&... \(aqinform\(aq, \&... NotificationType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=(123,)) \&... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.3.0\(aq), TimeTicks(0)), ObjectType(ObjectIdentity(\(aq1.3.6.1.6.3.1.1.4.1.0\(aq), ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.4\(aq)), ObjectType(ObjectName(\(aq1.3.6.1.2.1.2.2.1.1.123\(aq), Null(\(aq\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.2.2.1.7.123\(aq), Null(\(aq\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.2.2.1.8.123\(aq), Null(\(aq\(aq))]) .ft P .fi .sp In the latter example you can see MIB objects (ifIndex, ifAdminStatus, ifOperStatus) being automatically expanded from IF\-MIB::linkUp notification. To address specific row of SNMP table objects by index, the index part of MIB objects could be passed to \fINotificationType\fP via \fIinstanceIndex\fP parameter. .sp As you can see, the actual values for expanded MIB objects are NULLs. That\(aqs because in these examples our simple scripts do not have access to those MIB objects. We can supply that missing information by passing \fINotificationType\fP a dictionary\-like object that maps MIB object OIDs to current values. .sp .nf .ft C >>> from pysnmp.hlapi import * >>> >>> mib = {ObjectIdentifier(\(aq1.3.6.1.2.1.2.2.1.1.123\(aq): 123, \&... ObjectIdentifier(\(aq1.3.6.1.2.1.2.2.1.7.123\(aq): \(aqtesting\(aq, \&... ObjectIdentifier(\(aq1.3.6.1.2.1.2.2.1.8.123\(aq): \(aqup\(aq} >>> >>> g = sendNotification(SnmpEngine(), \&... CommunityData(\(aqpublic\(aq), \&... UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), \&... ContextData(), \&... \(aqinform\(aq, \&... NotificationType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=(123,), objects=mib) \&... ) >>> next(g) (None, 0, 0, [ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.3.0\(aq), TimeTicks(0)), ObjectType(ObjectIdentity(\(aq1.3.6.1.6.3.1.1.4.1.0\(aq), ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.4\(aq)), ObjectType(ObjectName(\(aq1.3.6.1.2.1.2.2.1.1.123\(aq), InterfaceIndex(123)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.2.2.1.7.123\(aq), Integer(3)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.2.2.1.8.123\(aq), Integer(1))]) .ft P .fi .SS High\-volume messaging .sp When in comes to managing large network, reading MIB objects sequentially introduces latency. By some point the latency becomes intolerable. Solutions to parallelize queries are well known \- you could do that by offloading individual operations into multiple processes, or multiple threads of execution or build your application around the asynchronous I/O model. .sp Compared to other solutions, asynchronous model is most lightweight and scalable. The idea is simple: never wait for I/O \- do something else whenever possible. The back side of this is that execution flow becomes non\-linear what hurts program analysis by human reader. .sp PySNMP high\-level API is adapted to work with three popular asynchronous I/O frameworks \- \fI\%asyncore\fP, \fI\%twisted\fP and \fI\%asyncio\fP\&. Please, refer to PySNMP \fI\%library reference\fP and \fI\%examples\fP for more information on asynchronous API. .SS Library reference .sp Dealing with many SNMP features may quickly overwhelm developers who aim at a quick and trivial task, PySNMP employs a layered architecture approach where the topmost programming API tries to be as simple as possible to allow immediate solutions for most common use cases. It will let you perform SNMP GET/SET/WALK and TRAP/INFORM operations by pasting code snippets from PySNMP documentation and example scripts right into your Python interactive session. .sp Most of SNMP operations involve packet exchange over network. PySNMP is shipped with a set of bindings to popular asynchronous Python I/O frameworks that let you run PySNMP in parallel with other tasks your application may perform. .SS Synchronous SNMP .sp Most simple and strightforward way to use PySNMP is by employing its Synchronous, blocking API. It\(aqs also the default API offered by users on \fIpysnmp.hlapi\fP sub\-package import. .sp Command Generator .SS GET command .SS SET command .SS GETNEXT command .SS GETBULK command .sp Notification Originator .SS TRAP/INFORM notification .SS Transport configuration .sp The following shortcut classes convey configuration information to SNMP engine\(aqs Local Configuration Datastore (\fI\%RFC 2271#section\-3.4.2\fP) as well as to underlying socket API. Once committed to LCD, SNMP engine saves its configuration for the lifetime of SNMP engine object. .SS Asynchronous: asyncore .sp The \fI\%asyncore\fP module is in Python standard library since ancient times. Main loop is built around \fI\%select\fP dispatcher, user code is invoked through callback callables. .sp Command Generator .SS GET command .SS SET command .SS GETNEXT command .SS GETBULK command .sp Notification Originator .SS TRAP/INFORM notification .SS Transport configuration .SS Asynchronous: asyncio .sp The \fI\%asyncio\fP module first appeared in standard library since Python 3.3 (in provisional basis). Its main design feature is that it makes asynchronous code looking like synchronous one. That greately simplifies development and maintanence. .sp Command Generator .SS GET command .SS SET command .SS GETNEXT command .SS GETBULK command .sp Notification Originator .SS TRAP/INFORM notification .SS Transport configuration .SS Asynchronous: trollius .sp An almost compatible alternative to \fIasyncio\fP for pre\-3.3 Python is \fI\%Trollius\fP module. PySNMP\(aqs \fIasyncio\fP bindings automatically work with Trolleus. .sp Please refer to \fI\%Trollius examples\fP for more information. .SS Asynchronous: Twisted .sp \fI\%Twisted\fP is one of the earliest and hugely popular asynchronous I/O framework. It introduced a concept of \fI\%Deferred\fP for representing work\-in\-progress that is not blocking the rest of I/O operations. PySNMP provides Twisted bindings. .sp Command Generator .SS GET command .SS SET command .SS GETNEXT command .SS GETBULK command .sp Notification Originator .SS TRAP/INFORM notification .SS Transport configuration .SS SNMP Engine .sp SNMP Engine is a central, stateful object used by all SNMP v3 substsems. Calls to high\-level Applications API also consume SNMP Engine object on input. .SS Security Parameters .sp Calls to high\-level Applications API consume Security Parameters configuration object on input. The shortcut classes described in this section convey configuration information to SNMP engine\(aqs Local Configuration Datastore (\fI\%RFC 2271#section\-3.4.2\fP). Once committed to LCD, SNMP engine saves its configuration for the lifetime of SNMP engine object. .SS Community\-based .sp Security Parameters object is Security Model specific. The \fBCommunityData\fP class is used for configuring Community\-Based Security Model of SNMPv1/SNMPv2c. .SS User\-based .sp The \fBUsmUserData\fP class provides SNMPv3 User\-Based Security Model configuration for SNMP v3 systems. .sp \fBAuthentication protocol identifiers\fP .sp \fBPrivacy (encryption) protocol identifiers\fP .sp \fBKey material types\fP .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 SNMP authentication and encryption keys must be at least \fI8\fP and at most \fI32\fP octets long. .UNINDENT .UNINDENT .sp Transport configuration is I/O framework specific and is described in respective sections. .SS SNMP Context .sp SNMP engine may serve several instances of the same MIB within possibly multiple SNMP entities. SNMP context is a tool for unambiguously identifying a collection of MIB variables behind the SNMP engine. See \fI\%RFC 3411#section\-3.3.1\fP for details. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 The SNMP context information is not tied to SNMPv3/USM user, but it is transferred in SNMPv3 message header. .sp Legacy SNMPv1/v2c protocols do not accommodate the SNMP context information at all. .sp To fit legacy SNMPv1/SNMPv2c systems into unified SNMPv3 architecture, the mapping procedure is introduced by \fI\%RFC 2576#section\-5.1\fP which essentially lets you first configure and then supply the missing items (e.g. \fIcontextName\fP, \fIcontextEngineId\fP and other) to the upper layers of SNMP stack based on SNMPv1/v2c \fIcommunityName\fP and transport endpoint. .sp The SNMP context information necessary for this mapping procedure to operate is supplied through the \fBCommunityData\fP object. .UNINDENT .UNINDENT .SS MIB services .SS MIB Variables .sp SNMP MIB variable is identified by an OBJECT IDENTIFIER (OID) and is accompanied by a value belonging to one of SNMP types (\fI\%RFC 1902#section\-2\fP). This pair is collectively called a variable\-binding in SNMP parlance. .sp The \fBrfc1902\fP module implements \fI\%RFC 1902#section\-2\fP MACRO definiitons. .SS MIB notification types .sp SNMP Notifications are enumerated and imply including certain set of MIB variables. Notification Originator applications refer to MIBs for MIB notifications through \fINOTIFICATION\-TYPE\fP ASN.1 macro. It conveys a set of MIB variables to be gathered and reported in SNMP Notification. The \fBrfc1902\fP module implements \fI\%RFC 1902#section\-2\fP macro definiitons. .SS SNMP base types .sp SNMP represents real\-world objects it serves along with their states in form of values. Those values each belong to one of SNMP types (\fI\%RFC 1902#section\-2\fP) which, in turn, are based on \fI\%ASN.1\fP data description language. PySNMP types are derived from \fI\%Python ASN.1 types\fP implementation. .SS Null type .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 The \fINULL\fP type actually belongs to the base ASN.1 types. It is not defined in \fI\%RFC 1902#section\-2\fP as an SNMP type. The \fINull\fP type is exposed through \fIrfc1902\fP module just for convenience. .UNINDENT .UNINDENT .SS Integer32 type .SS Integer type .SS OctetString type .SS IpAddress type .SS ObjectIdentifier type .SS Counter32 type .SS Gauge32 type .SS Unsigned32 type .SS TimeTicks type .SS Opaque type .SS Counter64 type .SS Bits type .SH EXAMPLES .SS Example scripts .sp SNMP is not simple (PySNMP implementation takes over 15K lines of Python code), but PySNMP tries to hide the complexities and let you carry out typical SNMP operations in a quick and intuitive way. .sp PySNMP offers three groups of programming interfaces to deal with SNMP protocol. In the order from most concise to most detailed those APIs follow. .SS High\-level SNMP .sp The so called high\-level API (hlapi) is designed to be simple, concise and suitable for the most frequent operations. For that matter only Command Generator and Notification Originator Applications are currently wrapped into a nearly one\-line Python expression. .sp It comes in several flavours: one synchronous and a bunch of bindings to popular asynchronous I/O frameworks. Those varieties of APIs bring subtile differences, mostly to better match particular I/O framework customs. Unless you have a very specific task, the high\-level API might solve your SNMP needs. .SS Synchronous SNMP .sp This chapter illustrates various uses of the synchronous high\-level programming interface to some of Standard SNMP Applications, as defined in \fI\%RFC3413\fP\&. .sp \fBNOTE:\fP .INDENT 0.0 .INDENT 3.5 The following examples involve creating Python iterator, the next() call is used to invoke iterator just once. .UNINDENT .UNINDENT .sp In most examples approximate analogues of well known Net\-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net\-SNMP tools, better understanding what example code doe .sp Here\(aqs a quick example on a simple SNMP GET by high\-level API: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs in IF\-MIB .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq))): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Command Generator API usage follow. .SS SNMP versions .SS SNMPv1 .sp Send SNMP GET request using the following options: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .UNINDENT .UNINDENT .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v1 \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv2c .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two OIDs in string form .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public demo.snmplabs.com 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.6.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.6.0\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3: auth MD5, privacy DES .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 authentication, DES encryption .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for IF\-MIB::ifInOctets.1 MIB object .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 demo.snmplabs.com IF\-MIB::ifInOctets.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3: auth MD5, no privacy .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for IF\-MIB::ifInOctets.1 MIB object .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 demo.snmplabs.com IF\-MIB::ifInOctets.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3: no auth, no privacy .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no encryption .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for IF\-MIB::ifInOctets.1 MIB object .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l noAuthNoPriv \-u usr\-none\-none demo.snmplabs.com IF\-MIB::ifInOctets.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3: auth SHA, privacy AES128 .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-sha\-aes\(aq, SHA authentication, AES128 encryption .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for SNMPv2\-MIB::sysDescr.0 MIB object .UNINDENT .sp Available authentication protocols: .INDENT 0.0 .IP 1. 3 usmHMACMD5AuthProtocol .IP 2. 3 usmHMACSHAAuthProtocol .IP 3. 3 usmHMAC128SHA224AuthProtocol .IP 4. 3 usmHMAC192SHA256AuthProtocol .IP 5. 3 usmHMAC256SHA384AuthProtocol .IP 6. 3 usmHMAC384SHA512AuthProtocol .IP 7. 3 usmNoAuthProtocol .UNINDENT .sp Available privacy protocols: .INDENT 0.0 .IP 1. 3 usmDESPrivProtocol .IP 2. 3 usm3DESEDEPrivProtocol .IP 3. 3 usmAesCfb128Protocol .IP 4. 3 usmAesCfb192Protocol .IP 5. 3 usmAesCfb256Protocol .IP 6. 3 usmNoPrivProtocol .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-sha\-aes \-A authkey1 \-X privkey1 \-a SHA \-x AES demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-sha\-aes\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq, authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Modifying variables .SS Coerce value to SET to MIB spec .sp Send SNMP SET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 setting SNMPv2\-MIB::sysName.0 to new value (type taken from MIB) .UNINDENT .sp Functionally similar to: .nf $ snmpset \-v2c \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 = \(dqnew system name\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysORDescr\(aq, 1), \(aqnew system name\(aq)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SET scalars values .sp Send SNMP SET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 setting three var\-bindings to new values .UNINDENT .sp Please note, that in this example MIB lookup is only used for the second var\-bindins. For the rest, value types are inferred from passed objects. .sp Functionally similar to: .nf $ snmpset \-v1 \-c public demo.snmplabs.com 1.3.6.1.2.1.1.9.1.2.1 o 1.3.6.1.4.1.20408.1.1 1.3.6.1.2.1.1.9.1.2.1 = 1.3.6.1.4.1.20408.1.1 1.3.6.1.2.1.1.9.1.3.1 s \(dqnew system name\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.9.1.2.1\(aq), ObjectIdentifier(\(aq1.3.6.1.4.1.20408.1.1\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.9.1.2.1\(aq), \(aq1.3.6.1.4.1.20408.1.1\(aq), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.9.1.3.1\(aq), OctetString(\(aqnew system name\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library\-reference\fP\&. .SS Walking operations .SS Walk whole MIB .sp Send a series of SNMP GETNEXT requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs in IF\-MIB .UNINDENT .sp Functionally similar to: .nf $ snmpwalk \-v3 \-lauthPriv \-u usr\-md5\-none \-A authkey1 \-X privkey1 demo.snmplabs.com IF\-MIB:: .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq))): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Table operations .SS GET table row .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for IF\-MIB::ifInOctets.1 and IF\-MIB::ifOutOctets.1 MIB object .IP \(bu 2 perform response OIDs and values resolution at MIB .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 demo.snmplabs.com IF\-MIB::ifInOctets.1 IF\-MIB::ifOutOctets.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifOutOctets\(aq, 1))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Fetch table row by composite index .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-sha\-aes128\(aq, SHA auth, AES128 privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for TCP\-MIB::tcpConnLocalAddress.\(dq0.0.0.0\(dq.22.\(dq0.0.0.0\(dq.0 MIB object .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 \-a SHA \-x AES demo.snmplabs.com TCP\-MIB::tcpConnLocalAddress.\(dq0.0.0.0\(dq.22.\(dq0.0.0.0\(dq.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-sha\-aes128\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq, authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqTCP\-MIB\(aq, \(aqtcpConnLocalAddress\(aq, \(aq0.0.0.0\(aq, 22, \(aq0.0.0.0\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Fetch scalar and table variables .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy protocols .IP \(bu 2 over IPv6/UDP .IP \(bu 2 to an Agent at [::1]:161 .IP \(bu 2 with values non\-repeaters = 1, max\-repetitions = 25 .IP \(bu 2 for IP\-MIB::ipAdEntAddr and all columns of the IF\-MIB::ifEntry table .IP \(bu 2 stop when response OIDs leave the scopes of the table .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lauthPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 \-Cn1, \-Cr25 demo.snmplabs.com IP\-MIB::ipAdEntAddr IP\-MIB::ipAddrEntry .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), Udp6TransportTarget((\(aq::1\(aq, 161)), ContextData(), 1, 25, ObjectType(ObjectIdentity(\(aqIP\-MIB\(aq, \(aqipAdEntAddr\(aq)), ObjectType(ObjectIdentity(\(aqIP\-MIB\(aq, \(aqipAddrEntry\(aq)), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Fetch whole SNMP table .sp Send a series of SNMP GETNEXT requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for some columns of the IF\-MIB::ifEntry table .IP \(bu 2 stop when response OIDs leave the scopes of initial OIDs .UNINDENT .sp Functionally similar to: .nf $ snmpwalk \-v1 \-c public demo.snmplabs.com IF\-MIB::ifDescr IF\-MIB::ifType IF\-MIB::ifMtu IF\-MIB::ifSpeed IF\-MIB::ifPhysAddress IF\-MIB::ifType .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifDescr\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifType\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifMtu\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifSpeed\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifPhysAddress\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifType\(aq)), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)\-1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS MIB tweaks .SS Waive MIB lookup .sp Perform SNMP GETNEXT operation with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an OID in string form .IP \(bu 2 do not resolve response OIDs and values into human\-freidly form .UNINDENT .sp False lookupMib keyword arguments could make pysnmp waiving OIDs and values resolution in response variable\-bindings, into human friendly form. .sp Functionally similar to: .nf $ snmpwalk \-v2c \-c public \-ObentU demo.snmplabs.com 1.3.6.1.2.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1\(aq)), lookupMib=False): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Preload PySNMP MIBs .sp Send a series of SNMP GETNEXT requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy protocols .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs starting from 1.3.6 .IP \(bu 2 preload all Python MIB modules found in search path .UNINDENT .sp Functionally similar to: .nf $ snmpwalk \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 \-m ALL demo.snmplabs.com:161 1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6\(aq).loadMibs())): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Custom ASN.1 MIB path .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for IF\-MIB::ifInOctets.1 MIB object .IP \(bu 2 pass non\-default ASN.1 MIB source to MIB compiler .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public \-M /usr/share/snmp demo.snmplabs.com IF\-MIB::ifInOctets.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1).addAsn1MibSource(\(aqfile:///usr/share/snmp\(aq, \(aqhttp://mibs.snmplabs.com/asn1/@mib@\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Custom PySNMP MIBs location .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs within TCP\-MIB::tcpConnTable column .IP \(bu 2 TCP\-MIB Python module will be searched by a user\-specified filesystem path (/opt/mib/pysnmp) and in Python package (python_packaged_mibs) which should be in sys.path .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 demo.snmplabs.com TCP\-MIB::tcpConnTable .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, ObjectType( ObjectIdentity(\(aqTCP\-MIB\(aq, \(aqtcpConnTable\(aq).addMibSource(\(aq/opt/mibs/pysnmp\(aq).addMibSource(\(aqpython_packaged_mibs\(aq) ), lexicographicMode=False): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Custom request timeout .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an OID in string form .IP \(bu 2 use custom timeout and request retries values .UNINDENT .sp Transport timing settings (maximum number of request retries and individual request timeout in seconds) can be set on a per\-target basis as explained by the code that follows. .sp Keep in mind that while timeout value can be specified in fractions of a second, default pysnmp timer resolution is quite low (about 0.5 sec) so there\(aqs no much point in using timeouts which is not a multiple of 0.5 Internal timer can be programmatically adjusted to finer resolution if needed. .sp If retries value is set to 0, pysnmp will issue a single request. Even if no response arrives, there will be no retry. Likewise, retries=1 means one initial request plus one retry. .sp Functionally similar to: .nf $ snmpget \-v1 \-c public \-t 2 \-r 0 demo.snmplabs.com 1.3.6.1.2.1.1.1.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget( (\(aqdemo.snmplabs.com\(aq, 161), timeout=2.0, retries=0 ), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS GET over IPv6 .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy protocols .IP \(bu 2 over IPv6/UDP .IP \(bu 2 to an Agent at [::1]:161 .IP \(bu 2 for three OIDs in string form .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 udp6:[::1]:161 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.2.0 1.3.6.1.2.1.1.3.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), Udp6TransportTarget((\(aq::1\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.2.0\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.3.0\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Command Generator .SS Walk Agent, limit number of packets .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent OR maxCalls == 10 request\-response interactions occur .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 demo.snmplabs.com SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * for (errorIndication, errorStatus, errorIndex, varBinds) in bulkCmd(SnmpEngine(), UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq)), maxCalls=10): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Sequence Of GET\(aqs .sp Send two SNMP GET requests in a row using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for IF\-MIB::ifInOctets.1 and IF\-MIB::ifOutOctets.1 MIB objects .UNINDENT .sp Use a queue of MIB objects to query. .sp The next() call is used to forward Python iterator to the position where it could consume input .sp Functionally similar to: .nf $ snmpget \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 demo.snmplabs.com IF\-MIB::ifInOctets.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * queue = [[ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1))], [ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifOutOctets\(aq, 1))]] iter = getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData()) next(iter) while queue: errorIndication, errorStatus, errorIndex, varBinds = iter.send(queue.pop()) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Custom ContextEngineId .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy protocols .IP \(bu 2 use remote SNMP Engine ID 0x80004fb805636c6f75644dab22cc (USM autodiscovery will run) .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 setting SNMPv2\-MIB::sysName.0 to new value (type coerced from MIB) .UNINDENT .sp Functionally similar to: .nf $ snmpset \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 \-E 80004fb805636c6f75644dab22cc demo.snmplabs.com SNMPv2\-MIB::sysORDescr.1 = \(dqnew system name\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq, securityEngineId=OctetString(hexValue=\(aq80004fb805636c6f75644dab22cc\(aq)), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysName\(aq, 0), \(aqnew system name\(aq)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Custom ContextEngineId and ContextName .sp Send SNMP SET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-none\(aq, MD5 auth and no privacy protocols .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 addressing particular set of Managed Objects at remote SNMP Engine by: * contextEngineId 0x80004fb805636c6f75644dab22cc and * contextName \(aqa172334d7d97871b72241397f713fa12\(aq .IP \(bu 2 setting SNMPv2\-MIB::sysName.0 to new value (type taken from MIB) .UNINDENT .sp Functionally similar to: .nf $ snmpset \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 \-E 80004fb805636c6f75644dab22cc \-n a172334d7d97871b72241397f713fa12 demo.snmplabs.com SNMPv2\-MIB::sysORDescr.1 = \(dqnew system name\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(contextEngineId=OctetString(hexValue=\(aq80004fb805636c6f75644dab22cc\(aq), contextName=\(aqda761cfc8c94d3aceef4f60f049105ba\(aq), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysORDescr\(aq, 1), \(aqnew system name\(aq)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Custom SecurityName .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, securityName \(aqmyuser\(aq MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an OID in text form .UNINDENT .sp 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. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq, securityName=\(aqmyuser\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Discover SNMPv3 SecurityEngineId .sp Send SNMP GET request using the following scenario and options: .INDENT 0.0 .IP \(bu 2 try to communicate with a SNMPv3 Engine using: .IP \(bu 2 a non\-existing user .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 if remote SNMP Engine ID is discovered, send SNMP GET request: .IP \(bu 2 .INDENT 2.0 .TP .B with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy at discovered securityEngineId .UNINDENT .IP \(bu 2 to the same SNMP Engine ID .IP \(bu 2 for an OID in text form .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * snmpEngine = SnmpEngine() transportTarget = UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)) # # To discover remote SNMP EngineID we will tap on SNMP engine inner workings # by setting up execution point observer setup on INTERNAL class PDU processing # observerContext = {} # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at execution point\(aqs local scope snmpEngine.observer.registerObserver( lambda e, p, v, c: c.update(securityEngineId=v[\(aqsecurityEngineId\(aq]), \(aqrfc3412.prepareDataElements:internal\(aq, cbCtx=observerContext ) # Send probe SNMP request with invalid credentials authData = UsmUserData(\(aqnon\-existing\-user\(aq) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(snmpEngine, authData, transportTarget, ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) # See if our SNMP engine received REPORT PDU containing securityEngineId if \(aqsecurityEngineId\(aq not in observerContext: print(\(dqCan\(aqt discover peer EngineID, errorIndication: %s\(dq % errorIndication) raise Exception() securityEngineId = observerContext.pop(\(aqsecurityEngineId\(aq) print(\(aqRemote securityEngineId = %s\(aq % securityEngineId.prettyPrint()) # # Query remote SNMP Engine using usmUserTable entry configured for it # authData = UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq, securityEngineId=securityEngineId) errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(snmpEngine, authData, transportTarget, ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3: master auth and privacy keys .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 authentication, DES encryption .IP \(bu 2 use master auth and privacy keys instead of pass\-phrase .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for SNMPv2\-MIB::sysDescr.0 MIB object instance .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-md5\-des \-3m 0x1dcf59e86553b3afa5d32fd5d61bf0cf \-3M 0xec5ab55e93e1d85cb6846d0f23e845e0 demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, authKey=OctetString( hexValue=\(aq1dcf59e86553b3afa5d32fd5d61bf0cf\(aq), privKey=OctetString( hexValue=\(aqec5ab55e93e1d85cb6846d0f23e845e0\(aq), authKeyType=usmKeyTypeMaster, privKeyType=usmKeyTypeMaster), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3: localized auth and privacy keys .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 authentication, DES encryption .IP \(bu 2 use localized auth and privacy keys instead of pass\-phrase or master keys .IP \(bu 2 configure authoritative SNMP engine ID (0x0000000000 can be used as well) .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for SNMPv2\-MIB::sysDescr.0 MIB object instance .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v3 \-l authPriv \-u usr\-md5\-des \-e 0x80004fb805636c6f75644dab22cc \-3k 0x6b99c475259ef7976cf8d028a3381eeb \-3K 0x92b5ef98f0a216885e73944e58c07345 demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, authKey=OctetString( hexValue=\(aq6b99c475259ef7976cf8d028a3381eeb\(aq), privKey=OctetString( hexValue=\(aq92b5ef98f0a216885e73944e58c07345\(aq), authKeyType=usmKeyTypeLocalized, privKeyType=usmKeyTypeLocalized, securityEngineId=OctetString( hexValue=\(aq80004fb805636c6f75644dab22cc\(aq)), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Query Agents from multiple threads .sp Send a bunch of SNMP GET requests simultaneously using the following options: .INDENT 0.0 .IP \(bu 2 process 5 GET requests in 3 parallel threads .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq and with SNMPv2c, community \(aqpublic\(aq and with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy .IP \(bu 2 over IPv4/UDP and over IPv6/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 .IP \(bu 2 for instances of SNMPv2\-MIB::sysDescr.0 and SNMPv2\-MIB::sysLocation.0 MIB objects .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from sys import version_info from threading import Thread from pysnmp.hlapi import * if version_info[0] == 2: from Queue import Queue else: from queue import Queue # List of targets in the following format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1\-st target (SNMPv1 over IPv4/UDP) (CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 2\-nd target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 3\-nd target (SNMPv2c over IPv4/UDP) \- same community and # different transport address. (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqlocalhost\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysContact\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysName\(aq, 0)))), # 4\-nd target (SNMPv3 over IPv4/UDP) (UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 5\-th target (SNMPv3 over IPv6/UDP) (UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), Udp6TransportTarget((\(aq::1\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # N\-th target # ... ) class Worker(Thread): def __init__(self, requests, responses): Thread.__init__(self) self.snmpEngine = SnmpEngine() self.requests = requests self.responses = responses self.setDaemon(True) self.start() def run(self): while True: authData, transportTarget, varBinds = self.requests.get() self.responses.append( next(getCmd(self.snmpEngine, authData, transportTarget, ContextData(), *varBinds)) ) if hasattr(self.requests, \(aqtask_done\(aq): # 2.5+ self.requests.task_done() class ThreadPool(object): def __init__(self, num_threads): self.requests = Queue(num_threads) self.responses = [] for _ in range(num_threads): Worker(self.requests, self.responses) def addRequest(self, authData, transportTarget, varBinds): self.requests.put((authData, transportTarget, varBinds)) def getResponses(self): return self.responses def waitCompletion(self): if hasattr(self.requests, \(aqjoin\(aq): self.requests.join() # 2.5+ else: from time import sleep # this is a lame substitute for missing .join() # adding an explicit synchronization might be a better solution while not self.requests.empty(): sleep(1) pool = ThreadPool(3) # Submit GET requests for authData, transportTarget, varBinds in targets: pool.addRequest(authData, transportTarget, varBinds) # Wait for responses or errors pool.waitCompletion() # Walk through responses for errorIndication, errorStatus, errorIndex, varBinds in pool.getResponses(): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp Sending SNMP TRAP\(aqs and INFORM\(aqs is as easy with PySNMP library. The following code sends SNMP TRAP: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Notification Originator API usage follow. .SS Common notifications .SS SNMPv2c TRAP via NOTIFICATION\-TYPE .sp Initialize TRAP message contents from variables specified in \fINOTIFICATION\-TYPE\fP SMI macro. .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with TRAP ID \(aqlinkUp\(aq specified as a MIB symbol .IP \(bu 2 include values for managed objects implicitly added to notification (via NOTIFICATION\-TYPE\->OBJECTS) .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.2.2.1.1.123 i 123 1.3.6.1.2.1.2.2.1.7.123 i 1 1.3.6.1.2.1.2.2.1.8.123 i 1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=(123,), objects={(\(aqIF\-MIB\(aq, \(aqifIndex\(aq): 123, (\(aqIF\-MIB\(aq, \(aqifAdminStatus\(aq): \(aqup\(aq, (\(aqIF\-MIB\(aq, \(aqifOperStatus\(aq): \(aqup\(aq} ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS INFORM, auth: MD5 privacy: DES .sp Send SNMP INFORM notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 with TRAP ID \(aqwarmStart\(aq specified as a string OID .IP \(bu 2 include managed object information 1.3.6.1.2.1.1.5.0 = \(aqsystem name\(aq .UNINDENT .sp Functionally similar to: .nf $ snmpinform \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 demo.snmplabs.com 12345 1.3.6.1.4.1.20408.4.1.1.2 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqinform\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.5.0\(aq), \(aqsystem name\(aq) ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv1 TRAP with defaults .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3 TRAP: auth SHA, privacy: AES128 .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with authoritative snmpEngineId = 0x8000000001020304 (USM must be configured at the Receiver accordingly) .IP \(bu 2 with user \(aqusr\-sha\-aes128\(aq, auth: SHA, priv: AES128 .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with TRAP ID \(aqauthenticationFailure\(aq specified as a MIB symbol .IP \(bu 2 do not include any additional managed object information .UNINDENT .sp SNMPv3 TRAPs requires pre\-sharing the Notification Originator\(aqs value of SnmpEngineId with Notification Receiver. To facilitate that we will use static (e.g. not autogenerated) version of snmpEngineId. .sp Functionally similar to: .nf $ snmptrap \-v3 \-e 8000000001020304 \-l authPriv \-u usr\-sha\-aes \-A authkey1 \-X privkey1 \-a SHA \-x AES demo.snmplabs.com 12345 1.3.6.1.4.1.20408.4.1.1.2 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(OctetString(hexValue=\(aq8000000001020304\(aq)), UsmUserData(\(aqusr\-sha\-aes128\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq, authProtocol=usmHMACSHAAuthProtocol, privProtocol=usmAesCfb128Protocol), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqauthenticationFailure\(aq)) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS SNMPv1 TRAP variants .SS Custom SNMPv1 TRAP .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework. .sp Original v1 TRAP fields are mapped into dedicated variable\-bindings, (see \fI\%RFC2576\fP) for details. .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #6 (enterpriseSpecific) and Specific Trap 432 .IP \(bu 2 overriding Uptime value with 12345 .IP \(bu 2 overriding Agent Address with \(aq127.0.0.1\(aq .IP \(bu 2 overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 6 432 12345 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.4.1.20408.4.1.1.2.0.432\(aq), ).addVarBinds( (\(aq1.3.6.1.2.1.1.3.0\(aq, 12345), (\(aq1.3.6.1.6.3.18.1.3.0\(aq, \(aq127.0.0.1\(aq), (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv1 TRAP with defaults .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Evaluating NOTIFICATION\-TYPE .SS SNMPv2c TRAP via NOTIFICATION\-TYPE .sp Initialize TRAP message contents from variables specified in \fINOTIFICATION\-TYPE\fP SMI macro. .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with TRAP ID \(aqlinkUp\(aq specified as a MIB symbol .IP \(bu 2 include values for managed objects implicitly added to notification (via NOTIFICATION\-TYPE\->OBJECTS) .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.2.2.1.1.123 i 123 1.3.6.1.2.1.2.2.1.7.123 i 1 1.3.6.1.2.1.2.2.1.8.123 i 1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=(123,), objects={(\(aqIF\-MIB\(aq, \(aqifIndex\(aq): 123, (\(aqIF\-MIB\(aq, \(aqifAdminStatus\(aq): \(aqup\(aq, (\(aqIF\-MIB\(aq, \(aqifOperStatus\(aq): \(aqup\(aq} ) ) ) if errorIndication: print(errorIndication) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Sending additional var\-binds .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as a MIB symbol .IP \(bu 2 include managed object information specified as a MIB symbol .UNINDENT .sp Functionally similar to: .nf $ snmpinform \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqinform\(aq, NotificationType( ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqcoldStart\(aq) ).addVarBinds( ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysName\(aq, 0), \(aqmy system\(aq) ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Notification Originator .SS INFORM with custom ContextName .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with user \(aqusr\-md5\-none\(aq, MD5 auth, no priv .IP \(bu 2 send INFORM notification .IP \(bu 2 in behalf of contextEngineId = SnmpEngineId, contextName \(aqmy\-context\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 with TRAP ID \(aqwarmStart\(aq specified as a string OID .UNINDENT .sp Sending SNMPv3 Notification in behalf of non\-default ContextName requires having a collection of Managed Objects registered under the ContextName being used. .sp Functionally similar to: .nf $ snmpinform \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 \-n my\-context demo.snmplabs.com 12345 0.3.6.1.6.3.1.1.5.2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(contextName=\(aqmy\-context\(aq), \(aqinform\(aq, NotificationType(ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS INFORM with custom ContextEngineId .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with user \(aqusr\-md5\-none\(aq, MD5 auth, no priv .IP \(bu 2 send INFORM notification .IP \(bu 2 in behalf of contextEngineId 0x8000000004030201, contextName \(aq\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 with TRAP ID \(aqwarmStart\(aq specified as a string OID .UNINDENT .sp Sending SNMPv3 Notification in behalf of non\-default ContextEngineId requires having a collection of Managed Objects registered under the ContextEngineId being used. .sp Functionally similar to: .nf $ snmpinform \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 \-E 0x8000000004030201 demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( sendNotification(SnmpEngine(), UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(OctetString(hexValue=\(aq8000000004030201\(aq)), \(aqinform\(aq, NotificationType(ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. .SS Asynchronous: asyncore .sp With \fI\%asyncore\fP API your scripts get CPU time on \fI\%socket\fP events being watched for by \fI\%select\fP dispatcher. Your code live mostly in isolated functions (or any callable objects). .sp In most examples approximate analogues of well known Net\-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net\-SNMP tools, better understanding what example code doe .sp Here\(aqs a quick example on a simple SNMP GET by high\-level API: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() getCmd(snmpEngine, CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs in IF\-MIB .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) return True # request lower layers to do GETNEXT and call us back snmpEngine = SnmpEngine() nextCmd(snmpEngine, UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifTable\(aq)), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp More examples on Command Generator API usage follow. .SS Various SNMP versions .SS SNMPv2c .sp Send SNMP GET request using the following options: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .UNINDENT .UNINDENT .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() getCmd(snmpEngine, CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Walk whole MIB .sp Send a series of SNMP GETNEXT requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs in IF\-MIB .UNINDENT .sp Functionally similar to: .nf $ snmpwalk \-v3 \-lauthNoPriv \-u usr\-md5\-none \-A authkey1 \-X privkey1 .in +2 demo.snmplabs.com IF\-MIB:: .in -2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) return True # request lower layers to do GETNEXT and call us back snmpEngine = SnmpEngine() nextCmd(snmpEngine, UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifTable\(aq)), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Walking operations .SS Walk whole MIB .sp Send a series of SNMP GETNEXT requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs in IF\-MIB .UNINDENT .sp Functionally similar to: .nf $ snmpwalk \-v3 \-lauthNoPriv \-u usr\-md5\-none \-A authkey1 \-X privkey1 .in +2 demo.snmplabs.com IF\-MIB:: .in -2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) return True # request lower layers to do GETNEXT and call us back snmpEngine = SnmpEngine() nextCmd(snmpEngine, UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq)), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifTable\(aq)), cbFun=cbFun) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Command Generator .SS Walk multiple Agents at once .sp Iterate over MIBs of multiple SNMP Agents asynchronously using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq and with SNMPv2c, community \(aqpublic\(aq and with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy .IP \(bu 2 over IPv4/UDP and over IPv6/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 .IP \(bu 2 pull variables till EOM .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1\-st target (SNMPv1 over IPv4/UDP) (CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1\(aq)), ObjectType(ObjectIdentity(\(aq1.3.6.1.3.1\(aq)))), # 2\-nd target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aq1.3.6.1.4.1\(aq)),)), # 3\-nd target (SNMPv3 over IPv4/UDP) (UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq)),)), # 4\-th target (SNMPv3 over IPv6/UDP) (UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), Udp6TransportTarget((\(aq::1\(aq, 161)), (ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifTable\(aq)),)) # N\-th target # ... ) # Wait for responses or errors, submit GETNEXT requests for further OIDs # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): (authData, transportTarget) = cbCtx print(\(aq%s via %s\(aq % (authData, transportTarget)) if errorIndication: print(errorIndication) return elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) return True # continue table retrieval snmpEngine = SnmpEngine() # Submit initial GETNEXT requests and wait for responses for authData, transportTarget, varBinds in targets: nextCmd(snmpEngine, authData, transportTarget, ContextData(), *varBinds, **dict(cbFun=cbFun, cbCtx=(authData, transportTarget))) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple SNMP engines .sp Send multiple SNMP GET requests to multiple peers using multiple independend SNMP engines. Deal with peers asynchronously. SNMP options are: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq and with SNMPv2c, community \(aqpublic\(aq and with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy .IP \(bu 2 over IPv4/UDP and over IPv6/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 .IP \(bu 2 for instances of SNMPv2\-MIB::sysDescr.0 and SNMPv2\-MIB::sysLocation.0 MIB objects .UNINDENT .sp Within this script we have a single asynchronous TransportDispatcher and a single UDP\-based transport serving two independent SNMP engines. We use a single instance of AsyncCommandGenerator with each of SNMP Engines to comunicate GET command request to remote systems. .sp When we receive a [response] message from remote system we use a custom message router to choose what of the two SNMP engines data packet should be handed over. The selection criteria we employ here is based on peer\(aqs UDP port number. Other selection criterias are also possible. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher # List of targets in the following format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1\-st target (SNMPv1 over IPv4/UDP) (CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 2\-nd target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 1161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 3\-nd target (SNMPv3 over IPv4/UDP) (UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 2161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))) # N\-th target # ... ) # Wait for responses or errors # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): (snmpEngine, authData, transportTarget) = cbCtx print(\(aqsnmpEngine %s: %s via %s\(aq % (snmpEngine.snmpEngineID.prettyPrint(), authData, transportTarget)) if errorIndication: print(errorIndication) return True elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) return True else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) # Instantiate the single transport dispatcher object transportDispatcher = AsyncoreDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain transportDispatcher.registerRoutingCbFun( lambda td, ta, d: ta[1] % 3 and \(aqA\(aq or \(aqB\(aq ) snmpEngineA = SnmpEngine() snmpEngineA.registerTransportDispatcher(transportDispatcher, \(aqA\(aq) snmpEngineB = SnmpEngine() snmpEngineB.registerTransportDispatcher(transportDispatcher, \(aqB\(aq) for authData, transportTarget, varBinds in targets: snmpEngine = transportTarget.getTransportInfo()[1][1] % 3 and \e snmpEngineA or snmpEngineB getCmd(snmpEngine, authData, transportTarget, ContextData(), *varBinds, **dict(cbFun=cbFun, cbCtx=(snmpEngine, authData, transportTarget))) transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple concurrent queries .sp Send a bunch of different SNMP GET requests to different peers all at once, wait for responses asynchronously: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq and with SNMPv2c, community \(aqpublic\(aq and with SNMPv3, user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy .IP \(bu 2 over IPv4/UDP and over IPv6/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 and to an Agent at [::1]:161 .IP \(bu 2 for instances of SNMPv2\-MIB::sysDescr.0 and SNMPv2\-MIB::sysLocation.0 MIB objects .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget, varNames ), ... ) targets = ( # 1\-st target (SNMPv1 over IPv4/UDP) (CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 2\-nd target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 3\-nd target (SNMPv2c over IPv4/UDP) \- same community and # different transport address. (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqlocalhost\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysContact\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysName\(aq, 0)))), # 4\-nd target (SNMPv3 over IPv4/UDP) (UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # 5\-th target (SNMPv3 over IPv6/UDP) (UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), Udp6TransportTarget((\(aq::1\(aq, 161)), (ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))), # N\-th target # ... ) # Wait for responses or errors # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): authData, transportTarget = cbCtx print(\(aq%s via %s\(aq % (authData, transportTarget)) if errorIndication: print(errorIndication) return True elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) return True else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() # Submit GET requests for authData, transportTarget, varNames in targets: getCmd(snmpEngine, authData, transportTarget, ContextData(), *varNames, **dict(cbFun=cbFun, cbCtx=(authData, transportTarget))) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp Sending SNMP TRAP\(aqs and INFORM\(aqs is as easy with PySNMP library. The following code sends SNMP TRAP: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * snmpEngine = SnmpEngine() sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp More examples on Notification Originator API usage follow. .SS Common notifications .SS SNMPv1 TRAP with defaults .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * snmpEngine = SnmpEngine() sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Notification Originator .SS Multiple concurrent queries .sp Send a bunch of different SNMP Notifications to different peers all at once, wait for responses asynchronously: .INDENT 0.0 .IP \(bu 2 SNMPv1 and SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to multiple Managers .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as a MIB symbol .IP \(bu 2 include managed object information specified as var\-bind objects pair .UNINDENT .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 demo.snmplabs.com 6 432 12345 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq $ snmptrap \-v2c \-c public demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget ), ... ) targets = ( # 1\-st target (SNMPv1 over IPv4/UDP) (CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData()), # 2\-nd target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData()), ) snmpEngine = SnmpEngine() for authData, transportTarget, contextData in targets: sendNotification( snmpEngine, authData, transportTarget, contextData, \(aqtrap\(aq, # NotifyType NotificationType( ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqcoldStart\(aq) ).addVarBinds( (ObjectIdentifier(\(aq1.3.6.1.2.1.1.1.0\(aq), OctetString(\(aqmy name\(aq)) ) ) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple concurrent notifications .sp Send multiple SNMP notifications at once using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c and SNMPv3 .IP \(bu 2 with community name \(aqpublic\(aq or USM username usr\-md5\-des .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 to multiple Managers .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as a MIB symbol .IP \(bu 2 include managed object information specified as var\-bind objects pair .UNINDENT .nf $ snmpinform \-v2c \-c public demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 $ snmpinform \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * # List of targets in the followin format: # ( ( authData, transportTarget ), ... ) targets = ( # 1\-st target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData()), # 2\-nd target (SNMPv3 over IPv4/UDP) (UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData()), ) # noinspection PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(\(aqNotification %s not sent: %s\(aq % (sendRequestHandle, errorIndication)) elif errorStatus: print(\(aqNotification Receiver returned error for %s: %s @%s\(aq % (sendRequestHandle, errorStatus, errorIndex)) else: print(\(aqNotification %s delivered:\(aq % sendRequestHandle) for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) snmpEngine = SnmpEngine() for authData, transportTarget, contextData in targets: sendPduHandle = sendNotification( snmpEngine, authData, transportTarget, contextData, \(aqinform\(aq, # NotifyType NotificationType( ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqcoldStart\(aq) ).addVarBinds((\(aq1.3.6.1.2.1.1.1.0\(aq, \(aqmy name\(aq)), cbFun=cbFun ) snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple SNMP Engines .sp Send SNMP notifications in behalf of multiple independend SNMP engines using the following options: .INDENT 0.0 .IP \(bu 2 with a single transport dispatcher and two independent SNMP engines .IP \(bu 2 SNMPv2c and SNMPv3 .IP \(bu 2 with community name \(aqpublic\(aq or USM username usr\-md5\-des .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send IMFORM notification .IP \(bu 2 to multiple Managers .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as a MIB symbol .IP \(bu 2 include managed object information specified as var\-bind objects pair .UNINDENT .sp Within this script we have a single asynchronous TransportDispatcher and a single UDP\-based transport serving two independent SNMP engines. We use a single instance of AsyncNotificationOriginator with each of SNMP Engines to communicate INFORM notification to remote systems. .sp When we receive a [response] message from remote system we use a custom message router to choose what of the two SNMP engines data packet should be handed over. The selection criteria we employ here is based on peer\(aqs UDP port number. Other selection criterias are also possible. .nf $ snmpinform \-v2c \-c public demo.snmplabs.com:1162 123 1.3.6.1.6.3.1.1.5.1 $ snmpinform \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 demo.snmplabs.com 123 1.3.6.1.6.3.1.1.5.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi.asyncore import * from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher # List of targets in the following format: # ( ( authData, transportTarget ), ... ) targets = ( # 1\-st target (SNMPv2c over IPv4/UDP) (CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 1162)), ContextData()), # 2\-nd target (SNMPv3 over IPv4/UDP) (UsmUserData(\(aqusr\-md5\-des\(aq, \(aqauthkey1\(aq, \(aqprivkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData()), ) # noinspection PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): snmpEngine = cbCtx if errorIndication: print(\(aqNotification %s for %s not sent: %s\(aq % (sendRequestHandle, snmpEngine.snmpEngineID.prettyPrint(), errorIndication)) elif errorStatus: print(\(aqNotification Receiver returned error for request %s, SNMP Engine %s: %s @%s\(aq % (sendRequestHandle, snmpEngine.snmpEngineID.prettyPrint(), errorStatus, errorIndex)) else: print(\(aqNotification %s for SNMP Engine %s delivered:\(aq % (sendRequestHandle, snmpEngine.snmpEngineID.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) # Instantiate the single transport dispatcher object transportDispatcher = AsyncoreDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain transportDispatcher.registerRoutingCbFun( lambda td, ta, d: ta[1] % 3 and \(aqA\(aq or \(aqB\(aq ) snmpEngineA = SnmpEngine() snmpEngineA.registerTransportDispatcher(transportDispatcher, \(aqA\(aq) snmpEngineB = SnmpEngine() snmpEngineB.registerTransportDispatcher(transportDispatcher, \(aqB\(aq) for authData, transportTarget, contextData in targets: snmpEngine = (transportTarget.getTransportInfo()[1][1] % 3 and snmpEngineA or snmpEngineB) sendPduHandle = sendNotification( snmpEngine, authData, transportTarget, contextData, \(aqinform\(aq, # NotifyType NotificationType( ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqcoldStart\(aq) ).addVarBinds((\(aq1.3.6.1.2.1.1.1.0\(aq, \(aqmy name\(aq)), cbFun=cbFun, cbCtx=snmpEngine ) transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. .SS Asynchronous: asyncio .sp The \fI\%asyncio\fP module first appeared in standard library since Python 3.3 (in provisional basis). Its main design feature is that it makes asynchronous code looking like synchronous one thus eliminating \(dqcallback hell\(dq. .sp With \fIasyncio\fP built\-in facilities, you could run many SNMP queries in parallel and/or sequentially, interleave SNMP queries with I/O operations with other systems. See \fI\%asyncio resources\fP repository for other \fIasyncio\fP\-compatible modules. .sp In most examples approximate analogues of well known Net\-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net\-SNMP tools, better understanding what example code doe .sp Here\(aqs a quick example on a simple SNMP GET by high\-level API: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an instance of SNMPv2\-MIB::sysDescr.0 MIB object .IP \(bu 2 Based on asyncio I/O framework .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(): snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() asyncio.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on asyncio I/O framework .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield from bulkCmd( snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, *varBinds) if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[\-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = asyncio.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))]) ) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Command Generator API usage follow. .SS Various SNMP versions .SS SNMPv1 .sp Send SNMP GET request using the following options: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an instance of SNMPv2\-MIB::sysDescr.0 MIB object .IP \(bu 2 Based on asyncio I/O framework .UNINDENT .UNINDENT .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v1 \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(): snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() asyncio.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on asyncio I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 .in +2 demo.snmplabs.com SNMPv2\-MIB::system .in -2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield from bulkCmd( snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, *varBinds) if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[\-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = asyncio.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))]) ) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Walking operations .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on asyncio I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 .in +2 demo.snmplabs.com SNMPv2\-MIB::system .in -2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield from bulkCmd( snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, *varBinds) if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[\-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = asyncio.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))]) ) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Command Generator .SS Concurrent queries .sp Send multiple SNMP GET requests at once using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to multiple Agents at demo.snmplabs.com .IP \(bu 2 for instance of SNMPv2\-MIB::sysDescr.0 MIB object .IP \(bu 2 based on asyncio I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public demo.snmplabs.com:1161 SNMPv2\-MIB::sysDescr.0 $ snmpget \-v2c \-c public demo.snmplabs.com:2161 SNMPv2\-MIB::sysDescr.0 $ snmpget \-v2c \-c public demo.snmplabs.com:3161 SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def getone(snmpEngine, hostname): errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData(\(aqpublic\(aq), UdpTransportTarget(hostname), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.wait([getone(snmpEngine, (\(aqdemo.snmplabs.com\(aq, 1161)), getone(snmpEngine, (\(aqdemo.snmplabs.com\(aq, 2161)), getone(snmpEngine, (\(aqdemo.snmplabs.com\(aq, 3161))]) ) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Sequential queries .sp Send multiple SNMP GET requests one by one using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to multiple Agents at demo.snmplabs.com .IP \(bu 2 for instance of SNMPv2\-MIB::sysDescr.0 MIB object .IP \(bu 2 based on asyncio I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public demo.snmplabs.com:1161 SNMPv2\-MIB::sysDescr.0 $ snmpget \-v2c \-c public demo.snmplabs.com:2161 SNMPv2\-MIB::sysDescr.0 $ snmpget \-v2c \-c public demo.snmplabs.com:3161 SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def getone(snmpEngine, hostname): errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd( snmpEngine, CommunityData(\(aqpublic\(aq), UdpTransportTarget(hostname), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0)) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) @asyncio.coroutine def getall(snmpEngine, hostnames): for hostname in hostnames: yield from getone(snmpEngine, hostname) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete(getall(snmpEngine, [(\(aqdemo.snmplabs.com\(aq, 1161), (\(aqdemo.snmplabs.com\(aq, 2161), (\(aqdemo.snmplabs.com\(aq, 3161)])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp Sending SNMP TRAP\(aqs and INFORM\(aqs is as easy with PySNMP library. The following code sends SNMP TRAP: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(): snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) if errorIndication: print(errorIndication) snmpEngine.transportDispatcher.closeDispatcher() asyncio.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Notification Originator API usage follow. .SS Common notifications .SS SNMPv1 TRAP with defaults .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def run(): snmpEngine = SnmpEngine() errorIndication, errorStatus, errorIndex, varBinds = yield from sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) if errorIndication: print(errorIndication) snmpEngine.transportDispatcher.closeDispatcher() asyncio.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Notification Originator .SS Multiple concurrent notifications .sp Send multiple SNMP notifications at once using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c and SNMPv3 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 to multiple Managers .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as a MIB symbol .IP \(bu 2 include managed object information specified as var\-bind objects pair .UNINDENT .sp Here we tag each SNMP\-COMMUNITY\-MIB::snmpCommunityTable row with the same tag as SNMP\-TARGET\-MIB::snmpTargetAddrTable row what leads to excessive tables information. .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 $ snmpinform \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 $ snmptrap \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import asyncio from pysnmp.hlapi.asyncio import * @asyncio.coroutine def sendone(snmpEngine, hostname, notifyType): (errorIndication, errorStatus, errorIndex, varBinds) = yield from sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, tag=hostname), UdpTransportTarget((hostname, 162), tagList=hostname), ContextData(), notifyType, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s: at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine = SnmpEngine() loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.wait([sendone(snmpEngine, \(aqdemo.snmplabs.com\(aq, \(aqtrap\(aq), sendone(snmpEngine, \(aqdemo.snmplabs.com\(aq, \(aqinform\(aq)]) ) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. .SS Asynchronous: trollius .sp In order to use \fI\%asyncio\fP features with older Python (2.6+), you could download and install \fI\%Trollius\fP module. PySNMP\(aqs \fIasyncio\fP bindings will work with Trollius as well. .sp In most examples approximate analogues of well known Net\-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net\-SNMP tools, better understanding what example code doe .sp Here\(aqs a quick example on a simple SNMP GET by high\-level API: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an instance of SNMPv2\-MIB::sysDescr.0 MIB object .IP \(bu 2 Based on trollius I/O framework .UNINDENT .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(): snmpEngine = SnmpEngine() (errorIndication, errorStatus, errorIndex, varBinds) = yield trollius.From( getCmd(snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() trollius.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on trollius I/O framework .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield trollius.From( bulkCmd(snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, *varBinds) ) if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[\-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = trollius.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))]) ) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Command Generator API usage follow. .SS Various SNMP versions .SS SNMPv1 .sp Send SNMP GET request using the following options: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for an instance of SNMPv2\-MIB::sysDescr.0 MIB object .IP \(bu 2 Based on trollius I/O framework .UNINDENT .UNINDENT .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v1 \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(): snmpEngine = SnmpEngine() (errorIndication, errorStatus, errorIndex, varBinds) = yield trollius.From( getCmd(snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() trollius.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on trollius I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 demo.snmplabs.com SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield trollius.From( bulkCmd(snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, *varBinds) ) if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[\-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = trollius.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))]) ) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Walking operations .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on trollius I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 demo.snmplabs.com SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(varBinds): snmpEngine = SnmpEngine() while True: (errorIndication, errorStatus, errorIndex, varBindTable) = yield trollius.From( bulkCmd(snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, *varBinds) ) if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) varBinds = varBindTable[\-1] if isEndOfMib(varBinds): break snmpEngine.transportDispatcher.closeDispatcher() loop = trollius.get_event_loop() loop.run_until_complete( run([ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq))]) ) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp Sending SNMP TRAP\(aqs and INFORM\(aqs is as easy with PySNMP library. The following code sends SNMP TRAP: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .IP \(bu 2 use trollius I/O framework .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(): snmpEngine = SnmpEngine() (errorIndication, errorStatus, errorIndex, varBinds) = yield trollius.From( sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq), # mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqinform\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s: at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() trollius.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Notification Originator API usage follow. .SS Common notifications .SS SNMPv1 TRAP with defaults .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .IP \(bu 2 use trollius I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import trollius from pysnmp.hlapi.asyncio import * @trollius.coroutine def run(): snmpEngine = SnmpEngine() (errorIndication, errorStatus, errorIndex, varBinds) = yield trollius.From( sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq), # mpModel=0), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 162)), ContextData(), \(aqinform\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s: at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) snmpEngine.transportDispatcher.closeDispatcher() trollius.get_event_loop().run_until_complete(run()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. .SS Asynchronous: Twisted .sp \fI\%Twisted\fP is quite old and widly used I/O framework. With Twisted, your code will mostly live in isolated functions, but unlike as it is with callback\-based design, with Twisted work\-in\-progress is represented by a \fI\%Deferred\fP class instance effectively carrying state and context of running operation. Your callback functions will be attached to these \fIDeferred\fP objects and invoked as \fIDeferred\fP is done. .sp Based on \fITwisted\fP infrastructure, individual asynchronous functions could be chained to run sequentially or in parallel. .sp In most examples approximate analogues of well known Net\-SNMP snmp* tools command line options are shown. That may help those readers who, by chance are familiar with Net\-SNMP tools, better understanding what example code doe .sp Here\(aqs a quick example on a simple SNMP GET by high\-level API: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .IP \(bu 2 based on Twisted I/O framework .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSysDescr(reactor, hostname): d = getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((hostname, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(getSysDescr, [\(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp To make use of SNMPv3 and USM, the following code performs a series of SNMP GETNEXT operations effectively fetching a table of SNMP variables from SNMP Agent: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on Twisted I/O framework .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[\-1]): return getbulk(reactor, snmpEngine, *varBindTable[\-1]) def failure(errorIndication): print(errorIndication) def getbulk(reactor, snmpEngine, varBinds): d = bulkCmd(snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, varBinds) d.addCallback(success, reactor, snmpEngine).addErrback(failure) return d react(getbulk, [SnmpEngine(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq))]) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Command Generator API usage follow. .SS Various SNMP versions .SS SNMPv1 .sp Send SNMP GET request using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .IP \(bu 2 based on Twisted I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v1 \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSysDescr(reactor, hostname): d = getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((hostname, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(getSysDescr, [\(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on Twisted I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 demo.snmplabs.com SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[\-1]): return getbulk(reactor, snmpEngine, *varBindTable[\-1]) def failure(errorIndication): print(errorIndication) def getbulk(reactor, snmpEngine, varBinds): d = bulkCmd(snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, varBinds) d.addCallback(success, reactor, snmpEngine).addErrback(failure) return d react(getbulk, [SnmpEngine(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq))]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Walking operations .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-none\-none\(aq, no authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs past SNMPv2\-MIB::system .IP \(bu 2 run till end\-of\-mib condition is reported by Agent .IP \(bu 2 based on Twisted I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpbulkwalk \-v3 \-lnoAuthNoPriv \-u usr\-none\-none \-Cn0 \-Cr50 demo.snmplabs.com SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[\-1]): return getbulk(reactor, snmpEngine, *varBindTable[\-1]) def failure(errorIndication): print(errorIndication) def getbulk(reactor, snmpEngine, varBinds): d = bulkCmd(snmpEngine, UsmUserData(\(aqusr\-none\-none\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), 0, 50, varBinds) d.addCallback(success, reactor, snmpEngine).addErrback(failure) return d react(getbulk, [SnmpEngine(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq))]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Walk whole MIB .sp Send a series of SNMP GETNEXT requests using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3, user \(aqusr\-md5\-none\(aq, MD5 authentication, no privacy .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for all OIDs in IF\-MIB .IP \(bu 2 based on Twisted I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpwalk \-v3 \-lauthPriv \-u usr\-md5\-none \-A authkey1 \-X privkey1 demo.snmplabs.com IF\-MIB:: .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[\-1]): return getnext(reactor, snmpEngine, *varBindTable[\-1]) def failure(errorIndication): print(errorIndication) def getnext(reactor, snmpEngine, varBinds): d = nextCmd(snmpEngine, UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), varBinds) d.addCallback(success, reactor, snmpEngine).addErrback(failure) return d react(getnext, [SnmpEngine(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq))]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS SNMPv2c .sp Send SNMP GET request using the following options: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP with non\-default timeout and no retries .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 MIB object, .IP \(bu 2 based on Twisted I/O framework .UNINDENT .UNINDENT .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public \-r 0 \-t 2 demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSysDescr(reactor, hostname): snmpEngine = SnmpEngine() d = getCmd(snmpEngine, CommunityData(\(aqpublic\(aq), UdpTransportTarget((hostname, 161), timeout=2.0, retries=0), ContextData(), ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(getSysDescr, [\(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Command Generator .SS Concurrent queries .sp Send multiple SNMP GET requests at once using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for two instances of SNMPv2\-MIB::sysDescr.0 and SNMPv2\-MIB::sysLocation.0 MIB object, .IP \(bu 2 based on Twisted I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public demo.snmplabs.com SNMPv2\-MIB::sysDescr.0 $ snmpget \-v2c \-c public demo.snmplabs.com SNMPv2\-MIB::sysLocation.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.defer import DeferredList from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def getSystem(reactor, hostname): snmpEngine = SnmpEngine() def getScalar(objectType): d = getCmd(snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((hostname, 161)), ContextData(), objectType) d.addCallback(success, hostname).addErrback(failure, hostname) return d return DeferredList( [getScalar(ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysDescr\(aq, 0))), getScalar(ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq, 0)))] ) react(getSystem, [\(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Walk multiple Agents at once .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-none\(aq, MD5 auth and no privacy protocols .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to Agents at demo.snmplabs.com:161 and demo.snmplabs.com:1161 .IP \(bu 2 for multiple MIB subtrees and tables .IP \(bu 2 for whole MIB .IP \(bu 2 based on Twisted I/O framework .UNINDENT .sp Functionally similar to: .nf $ snmpget \-v2c \-c public demo.snmplabs.com:161 SNMPv2\-MIB::system $ snmpget \-v2c \-c public demo.snmplabs.comL1161 SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.defer import DeferredList from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, reactor, snmpEngine, hostname): (errorStatus, errorIndex, varBindTable) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBindTable[0][int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBindRow in varBindTable: for varBind in varBindRow: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) if not isEndOfMib(varBindTable[\-1]): return getbulk(reactor, snmpEngine, hostname, *varBindTable[\-1]) def failure(errorIndication): print(errorIndication) def getbulk(reactor, snmpEngine, hostname, varBinds): d = bulkCmd(snmpEngine, UsmUserData(\(aqusr\-md5\-none\(aq, \(aqauthkey1\(aq), UdpTransportTarget(hostname), ContextData(), 0, 25, varBinds) d.addCallback(success, reactor, snmpEngine, hostname).addErrback(failure) return d def getall(reactor, hostnames): snmpEngine = SnmpEngine() return DeferredList( [getbulk(reactor, snmpEngine, hostname, ObjectType(ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsystem\(aq))) for hostname in hostnames] ) react(getall, [((\(aqdemo.snmplabs.com\(aq, 161), (\(aqdemo.snmplabs.com\(aq, 1161))]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp Sending SNMP TRAP\(aqs and INFORM\(aqs is as easy with PySNMP library. The following code sends SNMP TRAP: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % ( hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def run(reactor, hostname): d = sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((hostname, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(run, [\(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp More examples on Notification Originator API usage follow. .SS Common notifications .SS SNMPv1 TRAP with defaults .sp Send SNMPv1 TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 with default Uptime .IP \(bu 2 with default Agent Address .IP \(bu 2 with Enterprise OID 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 0.0.0.0 1 0 0 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % ( hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq ) ) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def run(reactor, hostname): d = sendNotification( SnmpEngine(), CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((hostname, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) d.addCallback(success, hostname).addErrback(failure, hostname) return d react(run, [\(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv2c TRAP via Twisted inline callbacks .sp Send SNMPv2c TRAP through unified SNMPv3 message processing framework using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 with Generic Trap #1 (warmStart) and Specific Trap 0 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 1.3.6.1.2.1.1.1.0 s \(dqHello from Twisted\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.task import react, defer from pysnmp.hlapi.twisted import * @defer.inlineCallbacks def sendtrap(reactor, snmpEngine, hostname): yield sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, mpModel=0), UdpTransportTarget((hostname, 162)), ContextData(), \(aqtrap\(aq, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( ObjectType(ObjectIdentity(\(aq1.3.6.1.2.1.1.1.0\(aq), OctetString(\(aqHello from Twisted\(aq)) ) ) # Preserve SnmpEngine instance across [potentially] multiple calls to safe on initialization snmpEngine = SnmpEngine() react(sendtrap, [snmpEngine, \(aqdemo.snmplabs.com\(aq]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced Notification Originator .SS Multiple concurrent notifications .sp Send multiple SNMP notifications at once using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP and INFORM notification .IP \(bu 2 to multiple Managers .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as a MIB symbol .IP \(bu 2 include managed object information specified as var\-bind objects pair .UNINDENT .sp Here we tag each SNMP\-COMMUNITY\-MIB::snmpCommunityTable row with the same tag as SNMP\-TARGET\-MIB::snmpTargetAddrTable row what leads to excessive tables information. .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 $ snmpinform \-v2c \-c public demo.snmplabs.com 12345 1.3.6.1.6.3.1.1.5.2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from twisted.internet.defer import DeferredList from twisted.internet.task import react from pysnmp.hlapi.twisted import * def success(args, hostname): (errorStatus, errorIndex, varBinds) = args if errorStatus: print(\(aq%s: %s at %s\(aq % (hostname, errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) def failure(errorIndication, hostname): print(\(aq%s failure: %s\(aq % (hostname, errorIndication)) # noinspection PyUnusedLocal def sendone(reactor, snmpEngine, hostname, notifyType): d = sendNotification( snmpEngine, CommunityData(\(aqpublic\(aq, tag=hostname), UdpTransportTarget((hostname, 162), tagList=hostname), ContextData(), notifyType, NotificationType( ObjectIdentity(\(aq1.3.6.1.6.3.1.1.5.2\(aq) ).addVarBinds( (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, OctetString(\(aqmy system\(aq)) ) ) d.addCallback(success, hostname).addErrback(failure, hostname) return d def sendall(reactor, destinations): snmpEngine = SnmpEngine() return DeferredList( [sendone(reactor, snmpEngine, hostname, notifyType) for hostname, notifyType in destinations] ) react(sendall, [[(\(aqdemo.snmplabs.com\(aq, \(aqtrap\(aq), (\(aqdemo.snmplabs.com\(aq, \(aqinform\(aq)]]) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp More sophisticated or less popular SNMP operations can still be performed with PySNMP through its Native API to Standard SNMP Applications. .SS Native SNMP API .sp Complete implementation of all official Standard SNMP Applications. It should let you implement any SNMP operation defined in the standard at the cost of working at a somewhat low level. .sp This API also comes in several transport varieties depending on I/O framework being used. .SS Asynchronous: asyncore .sp If you find yourself unable to use particular SNMP feature with the high\-level (hlapi) API, your next step would be to use SNMPv3 engine services through one of the Standard SNMP Applications (\fI\%RFC3413\fP). .sp There\(aqre a large number of SNMPv3 Native API example scripts on this website. Most of them serve a very specific purpose like talking arbitrary SNMP version or handling particular PDU type. That dedication of features serve the purpose of simplifying example code and easing your studies. .sp Since all these examples are built on top of common PySNMP components like SNMP engine, asyncore\-based I/O dispatcher, configuration datastore, you could always combine parts of the examples for getting a new breed of SNMP application best matching your needs. .SS Command Generator Applications .SS Various SNMP versions .SS SNMPv1 .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for an OID in tuple form .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v1 \-c public \-ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here elif errorStatus and errorStatus != 2: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Set scalar value .sp Send a SNMP SET request * with SNMPv2c with community name \(aqprivate\(aq * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form and an integer\-typed value .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpset \-v2c \-c private \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.4.1 t 123 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv2c setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqprivate\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 9, 1, 4, 1), rfc1902.TimeTicks(123))], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3, auth: SHA, privacy: AES128 .sp Send a SNMP GET request * with SNMPv3 with user \(aqusr\-sha\-aes\(aq, SHA auth and AES128 privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in tuple form .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v3 \-l authPriv \-u usr\-sha\-aes \-a SHA \-A authkey1 \-x AES \-X privkey1 \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr\-sha\-aes, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-sha\-aes\(aq, \(aqauthPriv\(aq) # # 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() config.delTransport( snmpEngine, udp.domainName ).closeTransport() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Set string value .sp Send a SNMP SET request with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-sha\-none\(aq, SHA auth and no privacy protocols .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for an OID in tuple form and a string\-typed value .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpset \-v3 \-l authNoPriv \-u usr\-sha\-none \-a SHA \-A authkey1 \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.3.1 s \(aqmy new value\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr\-sha\-none, auth: SHA, priv none config.addV3User( snmpEngine, \(aqusr\-sha\-none\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-sha\-none\(aq, \(aqauthNoPriv\(aq) # # 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString(\(aqmy new value\(aq))], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Modifying values .SS SET string and integer scalars .sp Send SNMP SET request with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1 with community name \(aqprivate\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for OIDs in tuple form and an integer and string\-typed values .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpset \-v1 \-c private \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.9.1.3.1 s \(aqmy value\(aq 1.3.6.1.2.1.1.9.1.4.1 t 123 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqprivate\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here elif errorStatus and errorStatus != 2: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.SetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 9, 1, 3, 1), rfc1902.OctetString(\(aqmy value\(aq)), ((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() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Walking operations .SS Bulk walk MIB .sp Send a series of SNMP GETBULK requests * with SNMPv2c, community \(aqpublic\(aq * over IPv4/UDP * to an Agent at 104.236.166.95:161 * with values non\-repeaters = 0, max\-repetitions = 25 * for two OIDs in tuple form * stop on end\-of\-mib condition for both OIDs .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpbulkwalk \-v2c \-c public \-C n0 \-C r25 \-ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdgen from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv2c setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequesthandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # stop on error if errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) return True # signal dispatcher to continue walking # Prepare initial request to be sent cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName 0, 25, # non\-repeaters, max\-repetitions [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Fetch two subtrees in parallel .sp Send a series of SNMP GETNEXT requests with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for two OIDs in tuple form .IP \(bu 2 stop on end\-of\-mib condition for both OIDs .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpwalk \-v1 \-c public \-ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1/2c setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here if errorStatus and errorStatus != 2: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Table operations .SS Fetch scalar and table variables .sp Send a series of SNMP GETBULK requests with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-des\(aq, MD5 auth and DES privacy protocols .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 with values non\-repeaters = 1, max\-repetitions = 25 .IP \(bu 2 for two OIDs in tuple form (first OID is non\-repeating) .IP \(bu 2 stop on end\-of\-mib condition for both OIDs .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpbulkwalk \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 \-C n1 \-C r25 \-ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdgen from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq) # # 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequesthandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # stop on error if errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) return True # signal dispatcher to continue walking # Prepare initial request to be sent cmdgen.BulkCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName 0, 25, # non\-repeaters, max\-repetitions (((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)), cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Pull MIB subtree .sp Send a series of SNMP GETNEXT requests * with SNMPv3 with user \(aqusr\-none\-none\(aq, no auth and no privacy protocols * over IPv4/UDP * to an Agent at 104.236.166.95:161 * for an OID in string form * stop whenever received OID goes out of initial prefix (it may be a table) .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpwalk \-v3 \-l noAuthNoPriv \-u usr\-none\-none \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Initial OID prefix initialOID = rfc1902.ObjectName(\(aq1.3.6.1.2.1.1\(aq) # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr\-none\-none, auth: none, priv: none config.addV3User( snmpEngine, \(aqusr\-none\-none\(aq, ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-none\-none\(aq, \(aqnoAuthNoPriv\(aq) # # 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: if initialOID.isPrefixOf(oid): print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) else: return False # signal dispatcher to stop return True # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [(initialOID, None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS MIB tweaks .SS Walk Agent and resolve variables at MIB .sp Send a series of SNMP GETNEXT requests with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for two OIDs in tuple form .IP \(bu 2 stop on end\-of\-mib condition for both OIDs .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpwalk \-v1 \-c public \-ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.smi import compiler, view, rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Attach MIB compiler to SNMP Engine (MIB Builder) # This call will fail if PySMI is not present on the system compiler.addMibCompiler(snmpEngine.getMibBuilder()) # ... alternatively, this call will not complain on missing PySMI # compiler.addMibCompiler(snmpEngine.getMibBuilder(), ifAvailable=True) # Used for MIB objects resolution mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) # # # SNMPv1/2c setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here if errorStatus and errorStatus != 2: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for varBind in varBindRow: print(rfc1902.ObjectType(rfc1902.ObjectIdentity(varBind[0]), varBind[1]).resolveWithMib(mibViewController).prettyPrint()) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [rfc1902.ObjectType(rfc1902.ObjectIdentity(\(aqiso.org.dod\(aq)).resolveWithMib(mibViewController), rfc1902.ObjectType(rfc1902.ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifMIB\(aq)).resolveWithMib(mibViewController)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS SNMPv2c, custom timeout .sp Send a SNMP GET request: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 wait 3 seconds for response, retry 5 times (plus one initial attempt) .IP \(bu 2 for an OID in tuple form .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v2c \-c public \-ObentU \-r 5 \-t 1 104.236.166.95 1.3.6.1.2.1.1.1.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv2c setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq, timeout=300, # in 1/100 sec retryCount=5 ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Send packets from specific local interface .sp Send a series of SNMP GETNEXT requests with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 sending packets from primary local interface 0.0.0.0, local port 61024 .IP \(bu 2 for two OIDs in tuple form .IP \(bu 2 stop on end\-of\-mib condition for both OIDs .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpwalk \-v2c \-c public \-ObentU 104.236.166.95 1.3.6.1.2.1.1 1.3.6.1.4.1.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1/2c setup (if you use SNMPv1 or v2c) # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # UDP/IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode((\(aq0.0.0.0\(aq, 61024)) ) config.addTargetAddr( snmpEngine, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) return 1 # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 2, 1, 11), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Spoof source address .sp Send a SNMP GET request * with SNMPv2c, community \(aqpublic\(aq * over IPv4/UDP * to an Agent at 104.236.166.95:161 * from a non\-local, spoofed IP 1.2.3.4 (root and Python 3.3+ required) * for an OID in tuple form .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v2c \-c public \-ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0 .fi .sp .sp But unlike the above command, this script issues SNMP request from a non\-default, non\-local IP address. .sp It is indeed possible to originate SNMP traffic from any valid local IP addresses. It could be a secondary IP interface, for instance. Superuser privileges are only required to send spoofed packets. Alternatively, sending from local interface could also be achieved by binding to it (via openClientMode() parameter). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv1 setup # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 0) # # Setup transport endpoint and bind it with security settings yielding # a target name # # Initialize asyncore\-based UDP/IPv4 transport udpSocketTransport = udp.UdpSocketTransport().openClientMode() # Use sendmsg()/recvmsg() for socket communication (required for # IP source spoofing functionality) udpSocketTransport.enablePktInfo() # Enable IP source spoofing (requires root privileges) udpSocketTransport.enableTransparent() # Register this transport at SNMP Engine config.addTransport( snmpEngine, udp.domainName, udpSocketTransport ) # Configure destination IPv4 address as well as source IPv4 address config.addTargetAddr( snmpEngine, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq, sourceAddress=(\(aq1.2.3.4\(aq, 0) ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) # SNMPv1 response may contain noSuchName error *and* SNMPv2c exception, # so we ignore noSuchName error here elif errorStatus and errorStatus != 2: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Walk Agent over IPv6 .sp Send a series of SNMP GETNEXT requests with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-none\(aq, MD5 auth and no privacy protocols .IP \(bu 2 over IPv6/UDP .IP \(bu 2 to an Agent at [::1]:161 .IP \(bu 2 for two OIDs in tuple form .IP \(bu 2 stop on end\-of\-mib condition for both OIDs .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp6 from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr\-md5\-des, auth: MD5, priv NONE config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq) # # 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, \(aqmy\-router\(aq, udp6.domainName, (\(aq::1\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBindTable, cbCtx): if errorIndication: print(errorIndication) return if errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[\-1][int(errorIndex) \- 1][0] or \(aq?\(aq)) return # stop on error for varBindRow in varBindTable: for oid, val in varBindRow: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) return True # signal dispatcher to continue # Prepare initial request to be sent cmdgen.NextCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1), None), ((1, 3, 6, 1, 4, 1, 1), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library\-reference\fP\&. .SS Advanced topics .SS Custom ContextEngineId and ContextName .sp Send a SNMP GET request with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-md5\-none\(aq, SHA auth and no privacy protocols .IP \(bu 2 for MIB instance identified by .IP \(bu 2 contextEngineId: 0x80004fb805636c6f75644dab22cc, .IP \(bu 2 contextName: da761cfc8c94d3aceef4f60f049105ba .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for an OID in tuple form .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 \-E 80004fb805636c6f75644dab22cc \-n da761cfc8c94d3aceef4f60f049105ba \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen from pysnmp.proto import rfc1902 # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # # SNMPv3/USM setup # # user: usr\-md5\-none, auth: MD5, priv: NONE config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq) # # 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message, pass custom ContextEngineId & ContextName cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, # contextEngineId rfc1902.OctetString(hexValue=\(aq80004fb805636c6f75644dab22cc\(aq), # contextName rfc1902.OctetString(\(aqda761cfc8c94d3aceef4f60f049105ba\(aq), [((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() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Report SNMP engine processing details .sp Send SNMP GET request with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv3 with user \(aqusr\-sha\-aes\(aq, SHA auth and AES128 privacy protocols .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 for an OID in tuple form .IP \(bu 2 also registers its own execution observer to snmpEngine .UNINDENT .sp While execution, this script will report some details on request processing as seen by rfc3412.sendPdu() and rfc3412.receiveMessage() abstract interfaces. .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v3 \-l authPriv \-u usr\-sha\-aes \-a SHA \-A authkey1 \-x AES \-X privkey1 \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import cmdgen # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Execution point observer setup # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at code point\(aqs local scope # noinspection PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): print(\(aqExecution point: %s\(aq % execpoint) print(\(aq* transportDomain: %s\(aq % \(aq.\(aq.join([str(x) for x in variables[\(aqtransportDomain\(aq]])) print(\(aq* transportAddress: %s\(aq % \(aq@\(aq.join([str(x) for x in variables[\(aqtransportAddress\(aq]])) print(\(aq* securityModel: %s\(aq % variables[\(aqsecurityModel\(aq]) print(\(aq* securityName: %s\(aq % variables[\(aqsecurityName\(aq]) print(\(aq* securityLevel: %s\(aq % variables[\(aqsecurityLevel\(aq]) print(\(aq* contextEngineId: %s\(aq % (variables[\(aqcontextEngineId\(aq] and variables[\(aqcontextEngineId\(aq].prettyPrint() or \(aq\(aq,)) print(\(aq* contextName: %s\(aq % variables[\(aqcontextName\(aq].prettyPrint()) print(\(aq* PDU: %s\(aq % variables[\(aqpdu\(aq].prettyPrint()) snmpEngine.observer.registerObserver( requestObserver, \(aqrfc3412.sendPdu\(aq, \(aqrfc3412.receiveMessage:response\(aq ) # # SNMPv3/USM setup # # user: usr\-sha\-aes, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-sha\-aes\(aq, \(aqauthPriv\(aq) # # 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, \(aqmy\-router\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqmy\-creds\(aq ) # Error/response receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) # Prepare and send a request message cmdgen.GetCommandGenerator().sendVarBinds( snmpEngine, \(aqmy\-router\(aq, None, \(aq\(aq, # contextEngineId, contextName [((1, 3, 6, 1, 2, 1, 1, 1, 0), None)], cbFun ) # Run I/O dispatcher which would send pending queries and process responses snmpEngine.transportDispatcher.runDispatcher() snmpEngine.observer.unregisterObserver() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Command Responder Applications .SS Various SNMP versions .SS Multiple SNMP USM users .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES or with USM user \(aqusr\-sha\-none\(aq, auth: SHA, no privacy with USM user \(aqusr\-sha\-aes128\(aq, auth: SHA, priv AES .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 1161)) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # user: usr\-sha\-none, auth: SHA, priv NONE config.addV3User( snmpEngine, \(aqusr\-sha\-none\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq ) # user: usr\-sha\-none, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, \(aqusr\-sha\-none\(aq, \(aqauthNoPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, \(aqusr\-sha\-aes128\(aq, \(aqauthPriv\(aq, (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple SNMP communities .sp Respond to SNMP GET/SET/GETNEXT queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with SNMP community \(dqpublic\(dq (read access) or \(dqprivate\(dq (write access) .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp Allow read/write access to all objects in the same MIB subtree. .sp The following Net\-SNMP\(aqs commands will GET/SET a value at this Agent: .nf $ 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 \(dqfar away\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv1 setup # SecurityName <\-> CommunityName mapping. # Here we configure two distinct CommunityName\(aqs to control read and write # operations. config.addV1System(snmpEngine, \(aqmy\-read\-area\(aq, \(aqpublic\(aq) config.addV1System(snmpEngine, \(aqmy\-write\-area\(aq, \(aqprivate\(aq) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 1, \(aqmy\-read\-area\(aq, \(aqnoAuthNoPriv\(aq, (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 1, \(aqmy\-write\-area\(aq, \(aqnoAuthNoPriv\(aq, (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Agent\-side MIB implementations .SS Implementing scalar MIB objects .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 serving custom Managed Object Instance defined within this script .IP \(bu 2 allow read access only to the subtree where the custom MIB object resides .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp The following Net\-SNMP commands will walk this Agent: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 .1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C import sys from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv2c setup # SecurityName <\-> CommunityName mapping. config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (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( \(aqSNMPv2\-SMI\(aq, \(aqMibScalar\(aq, \(aqMibScalarInstance\(aq ) class MyStaticMibScalarInstance(MibScalarInstance): # noinspection PyUnusedLocal,PyUnusedLocal def getValue(self, name, idx): return self.getSyntax().clone( \(aqPython %s running on a %s platform\(aq % (sys.version, sys.platform) ) mibBuilder.exportSymbols( \(aq__MY_MIB\(aq, 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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Implementing conceptual table .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 define a simple SNMP Table within a newly created EXAMPLE\-MIB .IP \(bu 2 pre\-populate SNMP Table with a single row of values .IP \(bu 2 allow read access only to the subtree where example SNMP Table resides .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp The following Net\-SNMP commands will populate and walk a table: .nf $ snmpset \-v2c \-c public 127.0.0.1 1.3.6.6.1.5.2.97.98.99 s \(dqmy value\(dq $ snmpset \-v2c \-c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 4 $ snmpwalk \-v2c \-c public 127.0.0.1 1.3.6 .fi .sp .sp \&...while the following command will destroy the same row .nf $ snmpset \-v2c \-c public 127.0.0.1 1.3.6.6.1.5.4.97.98.99 i 6 $ snmpwalk \-v2c \-c public 127.0.0.1 1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv2c setup # SecurityName <\-> CommunityName mapping. config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (1, 3, 6, 6), (1, 3, 6, 6)) # Create an SNMP context snmpContext = context.SnmpContext(snmpEngine) # \-\-\- define custom SNMP Table within a newly defined EXAMPLE\-MIB \-\-\- mibBuilder = snmpContext.getMibInstrum().getMibBuilder() (MibTable, MibTableRow, MibTableColumn, MibScalarInstance) = mibBuilder.importSymbols( \(aqSNMPv2\-SMI\(aq, \(aqMibTable\(aq, \(aqMibTableRow\(aq, \(aqMibTableColumn\(aq, \(aqMibScalarInstance\(aq ) RowStatus, = mibBuilder.importSymbols(\(aqSNMPv2\-TC\(aq, \(aqRowStatus\(aq) mibBuilder.exportSymbols( \(aq__EXAMPLE\-MIB\(aq, # table object exampleTable=MibTable((1, 3, 6, 6, 1)).setMaxAccess(\(aqreadcreate\(aq), # table row object, also carries references to table indices exampleTableEntry=MibTableRow((1, 3, 6, 6, 1, 5)).setMaxAccess(\(aqreadcreate\(aq).setIndexNames((0, \(aq__EXAMPLE\-MIB\(aq, \(aqexampleTableColumn1\(aq)), # table column: string index exampleTableColumn1=MibTableColumn((1, 3, 6, 6, 1, 5, 1), v2c.OctetString()).setMaxAccess(\(aqreadcreate\(aq), # table column: string value exampleTableColumn2=MibTableColumn((1, 3, 6, 6, 1, 5, 2), v2c.OctetString()).setMaxAccess(\(aqreadcreate\(aq), # table column: integer value with default exampleTableColumn3=MibTableColumn((1, 3, 6, 6, 1, 5, 3), v2c.Integer32(123)).setMaxAccess(\(aqreadcreate\(aq), # table column: row status exampleTableStatus=MibTableColumn((1, 3, 6, 6, 1, 5, 4), RowStatus(\(aqnotExists\(aq)).setMaxAccess(\(aqreadcreate\(aq) ) # \-\-\- end of custom SNMP table definition, empty table now exists \-\-\- # \-\-\- populate custom SNMP table with one row \-\-\- (exampleTableEntry, exampleTableColumn2, exampleTableColumn3, exampleTableStatus) = mibBuilder.importSymbols( \(aq__EXAMPLE\-MIB\(aq, \(aqexampleTableEntry\(aq, \(aqexampleTableColumn2\(aq, \(aqexampleTableColumn3\(aq, \(aqexampleTableStatus\(aq ) rowInstanceId = exampleTableEntry.getInstIdFromIndices(\(aqexample record one\(aq) mibInstrumentation = snmpContext.getMibInstrum() mibInstrumentation.writeVars( ((exampleTableColumn2.name + rowInstanceId, \(aqmy string value\(aq), (exampleTableColumn3.name + rowInstanceId, 123456), (exampleTableStatus.name + rowInstanceId, \(aqcreateAndGo\(aq)) ) # \-\-\- end of SNMP table population \-\-\- # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never\-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Serve non\-default MIB tree .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM username usr\-md5\-none .IP \(bu 2 using alternative set of Managed Objects addressed by contextEngineId: 8000000001020304, contextName: my\-context .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.smi import instrum, builder from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv3/USM setup # user: usr\-md5\-none, auth: MD5, priv NONE config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq, (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=\(aq8000000001020304\(aq) ) # Create an [empty] set of Managed Objects (MibBuilder), pass it to # Management Instrumentation Controller and register at SNMP Context # under ContextName \(aqmy\-context\(aq snmpContext.registerContextName( v2c.OctetString(\(aqmy\-context\(aq), # 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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Custom MIB Controller .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM username usr\-none\-none .IP \(bu 2 using alternative set of Managed Objects addressed by contextName: my\-context .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp The following Net\-SNMP command will send GET request to this Agent: .nf $ snmpget \-v3 \-u usr\-none\-none \-l noAuthNoPriv \-n my\-context \-Ir 127.0.0.1 sysDescr.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.smi import instrum from pysnmp.proto.api import v2c # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv3/USM setup # user: usr\-none\-none, auth: NONE, priv NONE config.addV3User( snmpEngine, \(aqusr\-none\-none\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-none\-none\(aq, \(aqnoAuthNoPriv\(aq, (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\(aqs and # always echos request var\-binds in response. class EchoMibInstrumController(instrum.AbstractMibInstrumController): def readVars(self, varBinds, acInfo=(None, None)): return [(ov[0], v2c.OctetString(\(aqYou queried OID %s\(aq % ov[0])) for ov in varBinds] # Create a custom Management Instrumentation Controller and register at # SNMP Context under ContextName \(aqmy\-context\(aq snmpContext.registerContextName( v2c.OctetString(\(aqmy\-context\(aq), # 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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Serve multiple network transports .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 and over IPv6/UDP, listening at [::1]:161 .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 .1.3.6 $ snmpwalk \-v2c \-c public udp6:[::1] .1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp, udp6 # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 at 127.0.0.1:161 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # UDP over IPv6 at [::1]:161 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode((\(aq::1\(aq, 161)) ) # SNMPv2c setup # SecurityName <\-> CommunityName mapping. config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Listen on multiple network interfaces .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 and 127.0.0.2:161 interfaces .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 .1.3.6 $ snmpwalk \-v2c \-c public 127.0.0.2 .1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 at 127.0.0.1:161 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # UDP over IPv4 at 127.0.0.2:161 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode((\(aq127.0.0.2\(aq, 161)) ) # SNMPv2c setup # SecurityName <\-> CommunityName mapping. config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Running at secondary network interface .sp Listen on all local IPv4 interfaces respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 0.0.0.0:161 .IP \(bu 2 preserve local IP address when responding (Python 3.3+ required) .UNINDENT .sp The following Net\-SNMP command will walk this Agent: .nf $ snmpwalk \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 localhost .1.3.6 .fi .sp .sp In the situation when UDP responder receives a datagram targeted to a secondary (AKA virtial) IP interface or a non\-local IP interface (e.g. routed through policy routing or iptables TPROXY facility), OS stack will by default put primary local IP interface address into the IP source field of the response IP packet. Such datagram may not reach the sender as either the sender itself or a stateful firewall somewhere in between would not be able to match response to original request. .sp The following script solves this problem by preserving original request destination IP address and put it back into response IP packet\(aqs source address field. .sp To respond from a non\-local (e.g. spoofed) IP address, uncomment the \&.enableTransparent() method call and run this script as root. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Transport setup # Initialize asyncore\-based UDP/IPv4 transport udpSocketTransport = udp.UdpSocketTransport().openServerMode((\(aq0.0.0.0\(aq, 161)) # Use sendmsg()/recvmsg() for socket communication (used for preserving # original destination IP address when responding) udpSocketTransport.enablePktInfo() # Enable IP source spoofing (requires root privileges) # udpSocketTransport.enableTransparent() # Register this transport at SNMP Engine config.addTransport( snmpEngine, udp.domainName, udpSocketTransport ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never\-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.observer.unregisterObserver() snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced topics .SS Specific SNMP Engine ID .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with SNMP EngineID: 8000000004030201 .IP \(bu 2 with USM user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .UNINDENT .sp The following Net\-SNMP command will walk this Agent: .nf $ snmpwalk \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 \-e 8000000004030201 localhost .1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto import rfc1902 # Create SNMP engine snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue=\(aq8000000004030201\(aq)) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Observe SNMP engine operations .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES or .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 registers its own execution observer to snmpEngine .UNINDENT .sp The following Net\-SNMP command will walk this Agent: .nf $ snmpwalk \-v3 \-u usr\-md5\-des \-l authPriv \-A authkey1 \-X privkey1 localhost .1.3.6 .fi .sp .sp This script will report some details on request processing as seen by rfc3412.receiveMessage() and rfc3412.returnResponsePdu() abstract interfaces. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine snmpEngine = engine.SnmpEngine() # Execution point observer setup # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at code point\(aqs local scope # noinspection PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): print(\(aqExecution point: %s\(aq % execpoint) print(\(aq* transportDomain: %s\(aq % \(aq.\(aq.join([str(x) for x in variables[\(aqtransportDomain\(aq]])) print(\(aq* transportAddress: %s (local %s)\(aq % (\(aq@\(aq.join([str(x) for x in variables[\(aqtransportAddress\(aq]]), \(aq@\(aq.join([str(x) for x in variables[\(aqtransportAddress\(aq].getLocalAddress()]))) print(\(aq* securityModel: %s\(aq % variables[\(aqsecurityModel\(aq]) print(\(aq* securityName: %s\(aq % variables[\(aqsecurityName\(aq]) print(\(aq* securityLevel: %s\(aq % variables[\(aqsecurityLevel\(aq]) print(\(aq* contextEngineId: %s\(aq % variables[\(aqcontextEngineId\(aq].prettyPrint()) print(\(aq* contextName: %s\(aq % variables[\(aqcontextName\(aq].prettyPrint()) print(\(aq* PDU: %s\(aq % variables[\(aqpdu\(aq].prettyPrint()) snmpEngine.observer.registerObserver( requestObserver, \(aqrfc3412.receiveMessage:request\(aq, \(aqrfc3412.returnResponsePdu\(aq ) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Register an imaginary never\-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.observer.unregisterObserver() snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple SNMP Engines .sp Run multiple SNMP Engines each with a complete Command Responder. Bind each SNMP Engine to a dedicated network transport endpoint: .INDENT 0.0 .IP \(bu 2 IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 IPv4/UDP, listening at 127.0.0.2:161 .UNINDENT .sp Each Command Responder will respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES .IP \(bu 2 allow read access to SNMPv2\-MIB objects (1.3.6) .IP \(bu 2 allow write access to SNMPv2\-MIB objects (1.3.6.1.2.1) .UNINDENT .sp The following Net\-SNMP commands will walk the first and the second Agent respectively: .nf $ 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 .fi .sp .sp Notice differently configured snmpEngineId\(aqs in usmUserEntry columns. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.proto import rfc1902 from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp # Configuration parameters for each of SNMP Engines snmpEngineInfo = ( (\(aq0102030405060708\(aq, udp.domainName + (0,), (\(aq127.0.0.1\(aq, 161)), (\(aq0807060504030201\(aq, udp.domainName + (1,), (\(aq127.0.0.2\(aq, 161)) ) # Instantiate the single transport dispatcher object transportDispatcher = AsyncoreDispatcher() # Setup a custom data routing function to select snmpEngine by transportDomain transportDispatcher.registerRoutingCbFun(lambda td, t, d: td) # Instantiate and configure SNMP Engines for snmpEngineId, transportDomain, transportAddress in snmpEngineInfo: # Create SNMP engine with specific engineID snmpEngine = engine.SnmpEngine(rfc1902.OctetString(hexValue=snmpEngineId)) # Register SNMP Engine object with transport dispatcher. Request incoming # data from specific transport endpoint to be funneled to this SNMP Engine. snmpEngine.registerTransportDispatcher(transportDispatcher, transportDomain) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, transportDomain, udp.UdpTransport().openServerMode(transportAddress) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Detailed VACM configuration .sp Serves MIB subtrees under different conditions: .INDENT 0.0 .IP \(bu 2 Respond to SNMPv2c commands .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 Serve MIB under non\-default contextName \fIabcd\fP .IP \(bu 2 Allow access to \fISNMPv2\-MIB::system\fP subtree .IP \(bu 2 Although deny access to \fISNMPv2\-MIB::sysUpTime\fP by a bit mask .IP \(bu 2 Use partial context name matching (\fIa\fP) .UNINDENT .sp This example demonstrates detailed VACM configuration performed via low\-level VACM calls: \fIaddContext\fP, \fIaddVacmGroup\fP, \fIaddVacmAccess\fP and \fIaddVacmView\fP\&. Each function populates one of the tables defined in \fISNMP\-VIEW\-BASED\-ACM\-MIB\fP and used strictly as described in the above mentioned MIB. .sp The following Net\-SNMP\(aqs commands will GET a value at this Agent: .nf $ snmpget \-v2c \-c public 127.0.0.1 SNMPv2\-MIB::sysLocation.0 .fi .sp .sp However this command will fail: .nf $ snmpget \-v2c \-c public 127.0.0.1 SNMPv2\-MIB::sysUpTime.0 .fi .sp .sp This command will not reveal \fISNMPv2\-MIB::sysUpTime.0\fP among other objects: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 SNMPv2\-MIB::system .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncore.dgram import udp # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # Register default MIB instrumentation controller with a new SNMP context contextName = \(aqabcd\(aq snmpContext = context.SnmpContext(snmpEngine) snmpContext.registerContextName( contextName, snmpEngine.msgAndPduDsp.mibInstrumController) # Add new SNMP community name, map it to a new security name and # SNMP context securityName = \(aqmy\-area\(aq communityName = \(aqpublic\(aq config.addV1System( snmpEngine, securityName, communityName, contextEngineId=snmpContext.contextEngineId, contextName=contextName) # VACM configuration settings securityModel = 2 # SNMPv2c securityLevel = 1 # noAuthNoPriv vacmGroup = \(aqmy\-group\(aq readViewName = \(aqmy\-read\-view\(aq # We will match by context name prefix contextPrefix = contextName[:1] # Populate SNMP\-VIEW\-BASED\-ACM\-MIB::vacmContextTable config.addContext(snmpEngine, contextName) # Populate SNMP\-VIEW\-BASED\-ACM\-MIB::vacmSecurityToGroupTable config.addVacmGroup( snmpEngine, vacmGroup, securityModel, securityName) # Populate SNMP\-VIEW\-BASED\-ACM\-MIB::vacmAccessTable config.addVacmAccess( snmpEngine, vacmGroup, contextPrefix, securityModel, securityLevel, \(aqprefix\(aq, readViewName, \(aq\(aq, \(aq\(aq) # Populate SNMP\-VIEW\-BASED\-ACM\-MIB::vacmViewTreeFamilyTable # Allow the whole system subtree config.addVacmView( snmpEngine, readViewName, \(aqincluded\(aq, \(aq1.3.6.1.2.1.1.1\(aq, \(aq1.1.1.1.1.1.1.0\(aq) # ...but exclude one sub\-branch (just one scalar OID) config.addVacmView( snmpEngine, readViewName, \(aqexcluded\(aq, \(aq1.3.6.1.2.1.1.3\(aq, \(aq1.1.1.1.1.1.1.1\(aq) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) # Register an imaginary never\-ending job to keep I/O dispatcher running forever snmpEngine.transportDispatcher.jobStarted(1) # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except Exception: snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Notification Originator Applications .SS Various SNMP versions .SS SNMPv1 TRAP .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 send TRAP notification .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: .IP \(bu 2 overriding Uptime value with 12345 .IP \(bu 2 overriding Agent Address with \(aq104.236.166.95\(aq .IP \(bu 2 overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 104.236.166.95 6 432 12345 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv1 \-> 0) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (1), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 1, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # Uptime value with 12345 (v2c.ObjectIdentifier(\(aq1.3.6.1.2.1.1.3.0\(aq), v2c.TimeTicks(12345)), # trap OID: Generic Trap #6 (enterpriseSpecific) # and Specific Trap 432 (v2c.ObjectIdentifier(\(aq1.3.6.1.6.3.1.1.5.1\(aq), v2c.ObjectIdentifier(\(aq1.3.6.1.4.1.20408.4.1.1.2.0.432\(aq)), # Agent Address with \(aq127.0.0.1\(aq (v2c.ObjectIdentifier(\(aq1.3.6.1.6.3.18.1.3.0\(aq), v2c.IpAddress(\(aq127.0.0.1\(aq)), # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 (v2c.ObjectIdentifier(\(aq1.3.6.1.6.3.1.1.4.3.0\(aq), v2c.ObjectIdentifier(\(aq1.3.6.1.4.1.20408.4.1.1.2\(aq)), # managed object \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq (v2c.ObjectIdentifier(\(aq1.3.6.1.2.1.1.1.0\(aq), v2c.OctetString(\(aqmy system\(aq)) ] ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and stop snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv2c TRAP .sp Send SNMP TRAP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 = \(aqNotificator Example\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public 104.236.166.95 12345 1.3.6.1.4.1.20408.4.1.1.2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print(\(aqNotification %s, status \- %s\(aq % ( sendRequestHandle, errorIndication and errorIndication or \(aqdelivered\(aq ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ], cbFun ) print(\(aqNotification %s is scheduled to be sent\(aq % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3 TRAP, auth: MD5, privacy: DES .sp Send SNMP TRAP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with user \(aqusr\-md5\-des\(aq, auth: MD5, priv DES .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqwarmStart\(aq specified as an OID .IP \(bu 2 include managed object information 1.3.6.1.2.1.1.5.0 = \(aqsystem name\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v3 \-l authPriv \-u usr\-md5\-des \-A authkey1 \-X privkey1 \-e 8000000001020304 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance with specific (and locally unique) # SnmpEngineId \-\- it must also be known to the receiving party # and configured at its VACM users table. snmpEngine = engine.SnmpEngine( snmpEngineID=v2c.OctetString(hexValue=\(aq8000000001020304\(aq) ) # Add USM user config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (3), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ] ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3 INFORM, auth: MD5, privacy: none .sp Send SNMP INFORM notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with user \(aqusr\-md5\-none\(aq, auth: MD5, priv NONE .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to a Manager at demo.snmplabs.com:162 .IP \(bu 2 send INFORM notification .IP \(bu 2 with TRAP ID \(aqwarmStart\(aq specified as an OID .IP \(bu 2 include managed object information 1.3.6.1.2.1.1.5.0 = \(aqsystem name\(aq .UNINDENT .sp Functionally similar to: .nf $ snmpinform \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 = \(aqsystem name\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # Add USM user config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqinform\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (3), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print(\(aqNotification %s, status \- %s\(aq % ( sendRequestHandle, errorIndication and errorIndication or \(aqdelivered\(aq ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds: SNMPv2\-MIB::coldStart, ... [((1, 3, 6, 1, 6, 3, 1, 1, 5, 1), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqsystem name\(aq))], cbFun ) print(\(aqNotification %s scheduled to be sent\(aq % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library\-reference\fP\&. .SS Common notifications .SS SNMPv1 TRAP .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 send TRAP notification .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: .IP \(bu 2 overriding Uptime value with 12345 .IP \(bu 2 overriding Agent Address with \(aq104.236.166.95\(aq .IP \(bu 2 overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 .IP \(bu 2 include managed object information \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 104.236.166.95 6 432 12345 1.3.6.1.2.1.1.1.0 s \(dqmy system\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv1 \-> 0) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (1), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 1, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # Uptime value with 12345 (v2c.ObjectIdentifier(\(aq1.3.6.1.2.1.1.3.0\(aq), v2c.TimeTicks(12345)), # trap OID: Generic Trap #6 (enterpriseSpecific) # and Specific Trap 432 (v2c.ObjectIdentifier(\(aq1.3.6.1.6.3.1.1.5.1\(aq), v2c.ObjectIdentifier(\(aq1.3.6.1.4.1.20408.4.1.1.2.0.432\(aq)), # Agent Address with \(aq127.0.0.1\(aq (v2c.ObjectIdentifier(\(aq1.3.6.1.6.3.18.1.3.0\(aq), v2c.IpAddress(\(aq127.0.0.1\(aq)), # Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 (v2c.ObjectIdentifier(\(aq1.3.6.1.6.3.1.1.4.3.0\(aq), v2c.ObjectIdentifier(\(aq1.3.6.1.4.1.20408.4.1.1.2\(aq)), # managed object \(aq1.3.6.1.2.1.1.1.0\(aq = \(aqmy system\(aq (v2c.ObjectIdentifier(\(aq1.3.6.1.2.1.1.1.0\(aq), v2c.OctetString(\(aqmy system\(aq)) ] ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and stop snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv2c TRAP .sp Send SNMP TRAP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 = \(aqNotificator Example\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public 104.236.166.95 12345 1.3.6.1.4.1.20408.4.1.1.2 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print(\(aqNotification %s, status \- %s\(aq % ( sendRequestHandle, errorIndication and errorIndication or \(aqdelivered\(aq ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ], cbFun ) print(\(aqNotification %s is scheduled to be sent\(aq % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS INFORM notification .sp Send SNMP INFORM notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 = \(aqNotificator Example\(aq .UNINDENT .sp Functionally similar to: .nf $ snmpinform \-v2c \-c public 104.236.166.95 12345 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping (+ transport binding) config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqinform\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print(\(aqNotification %s, status \- %s\(aq % ( sendRequestHandle, errorIndication and errorIndication or \(aqdelivered\(aq ) ) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ], cbFun ) print(\(aqNotification %s scheduled to be sent\(aq % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Evaluating NOTIFICATION\-TYPE .sp SNMP SMI defines notifications as a TRAP or INFORM PDU containing the indication of type (snmpTrapOID) and a set of MIB variables (Managed Objects Instances) fetched from Agent\(aqs MIB at the moment of notification. .sp Consequently, sending specific NOTIFICATION\-TYPE implies including certain set of OIDs into PDU. PySNMP offers this facility through NotificationType class. .SS Sending notification with OBJECT\(aqs .sp Send SNMP TRAP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to a Manager at 104.236.166.95:162 .IP \(bu 2 with TRAP ID IF\-MIB::ifLink as MIB symbol .UNINDENT .sp The IF\-MIB::ifLink NOTIFICATION\-TYPE implies including four other var\-binds into the notification message describing the incident occurred. These var\-binds are: IF\-MIB::ifIndex.\(dqx\(dq IF\-MIB::ifAdminStatus.\(dqx\(dq IF\-MIB::ifOperStatus.\(dqx\(dq IF\-MIB::ifDescr.\(dqx\(dq .sp Where \(dqx\(dq is MIB table index (instance index). .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.3 IF\-MIB::ifIndex.\(dq1\(dq IF\-MIB::ifAdminStatus.\(dq1\(dq IF\-MIB::ifOperStatus.\(dq1\(dq IF\-MIB::ifDescr.\(dq1\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.smi import rfc1902, view # # Here we fill in some values for Managed Objects Instances (invoked # later while building TRAP message) by NOTIFICATION\-TYPE macro evaluation. # In real Agent app, these values should already be initialized during # Agent runtime. # instanceIndex = (1,) objects = { (\(aqIF\-MIB\(aq, \(aqifIndex\(aq): instanceIndex[0], (\(aqIF\-MIB\(aq, \(aqifAdminStatus\(aq): \(aqup\(aq, (\(aqIF\-MIB\(aq, \(aqifOperStatus\(aq): \(aqdown\(aq, (\(aqIF\-MIB\(aq, \(aqifDescr\(aq): \(aqeth0\(aq } # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # MIB view controller is used for MIB lookup purposes mibViewController = view.MibViewController(snmpEngine.getMibBuilder()) # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\-1\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName rfc1902.NotificationType( rfc1902.ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=instanceIndex, objects=objects ).resolveWithMib(mibViewController) ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Multiple managers operations .sp SNMPv3 framework is designed to allow Agents sending the same PDU to multiple Managers over different network transports, listening at different network addresses over different SNMP versions/credentials. .sp The following few examples use this facility. .SS Notification to multiple addresses .sp Send SNMP TRAP notifications to multiple Managers using different security settings: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to multiple Managers at 104.236.166.95:162, 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 = \(aqNotificator Example\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\-1\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # Second target config.addTargetAddr( snmpEngine, \(aqmy\-nms\-2\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # Third target config.addTargetAddr( snmpEngine, \(aqmy\-nms\-3\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ] ) print(\(aqNotifications are scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Notification to multiple SNMP managers .sp Send SNMP TRAP notifications to multiple Managers using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to multiple Managers at 104.236.166.95:162, 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 = \(aqNotificator Example\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq $ snmptrap \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\-1\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # Second target config.addTargetAddr( snmpEngine, \(aqmy\-nms\-2\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # Third target config.addTargetAddr( snmpEngine, \(aqmy\-nms\-3\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # Specify what kind of notification should be sent (TRAP or INFORM) # to what targets (chosen by tag) and with what credentials. config.addNotificationTarget( snmpEngine, \(aqmy\-notification\(aq, \(aqmy\-creds\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ] ) print(\(aqNotifications are scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Notification over multiple SNMP versions .sp Send SNMP INFORM notifications to multiple Managers using different security settings: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 AND .IP \(bu 2 SNMPv3 .IP \(bu 2 with user \(aqusr\-md5\-none\(aq, auth: MD5, priv NONE .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 to multiple Managers at 104.236.166.95:162, 104.236.166.95:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq .UNINDENT .sp Functionally similar to: .nf $ snmpinform \-v3 \-l authPriv \-u usr\-md5\-none \-A authkey1 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq $ snmpinform \-v2c \-c public 104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SNMPv2c: # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\-1\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 1) # SNMPv3: config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) config.addTargetParams(snmpEngine, \(aqmy\-creds\-2\(aq, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq) # 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, \(aqmy\-nms\-1\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\-1\(aq, tagList=\(aqall\-my\-managers\(aq ) # Second target config.addTargetAddr( snmpEngine, \(aqmy\-nms\-2\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\-2\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqinform\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2&3), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print(\(aqNotification %s, status \- %s\(aq % (sendRequestHandle, errorIndication and errorIndication or \(aqdelivered\(aq)) # Build and submit notification message to dispatcher sendRequestHandle = ntfOrg.sendVarBinds( snmpEngine, \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)) ], cbFun ) print(\(aqNotifications %s are scheduled to be sent\(aq % sendRequestHandle) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Notification over multiple network protocols .sp Send SNMP INFORM notifications to multiple Managers over different network protocols: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP and UDP/IPv6 .IP \(bu 2 send TRAP notification .IP \(bu 2 to two Managers through different network transports .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: 1.3.6.1.2.1.1.1.0 = \(aqExample Notificator\(aq 1.3.6.1.2.1.1.5.0 = \(aqNotificator Example\(aq .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public udp:104.236.166.95 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq $ snmptrap \-v2c \-c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.1.0 s \(aqExample notification\(aq 1.3.6.1.2.1.1.5.0 s \(aqNotificator Example\(aq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 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, \(aqmy\-nms\-1\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # UDP/IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6SocketTransport().openClientMode() ) config.addTargetAddr( snmpEngine, \(aqmy\-nms\-2\(aq, udp6.domainName, (\(aq::1\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (2), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, # Notification targets \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))), # additional var\-binds: ( (oid, value), ... ) ((1, 3, 6, 1, 2, 1, 1, 1, 0), v2c.OctetString(\(aqExample Notificator\(aq)), ((1, 3, 6, 1, 2, 1, 1, 5, 0), v2c.OctetString(\(aqNotificator Example\(aq)) ] ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Send packet from specific network interface/port .sp Send SNMP notification using the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to a Manager at 104.236.166.95 UDP port 162 .IP \(bu 2 from local address 0.0.0.0, UDP port 61024 .IP \(bu 2 send TRAP notification .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v1 \-c public 104.236.166.95 1.3.6.1.6.3.1.1.5.1 0.0.0.0 1 0 0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq, transportTag=\(aqall\-my\-managers\(aq) # Specify security settings per SecurityName (SNMPv1 \-> 0) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 0) # Setup transport endpoint and bind it with security settings yielding # a target name. Pay attention to the openClientMode() parameter \-\- it\(aqs # used to originate packets from particular local IP:port config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode(iface=(\(aq0.0.0.0\(aq, 61024)) ) config.addTargetAddr( snmpEngine, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq, tagList=\(aqall\-my\-managers\(aq ) # 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, \(aqmy\-notification\(aq, \(aqmy\-filter\(aq, \(aqall\-my\-managers\(aq, \(aqtrap\(aq ) # Allow NOTIFY access to Agent\(aqs MIB by this SNMP model (1), securityLevel # and SecurityName config.addContext(snmpEngine, \(aq\(aq) config.addVacmUser(snmpEngine, 1, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (), (), (1, 3, 6)) # *** SNMP engine configuration is complete by this line *** # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Build and submit notification message to dispatcher ntfOrg.sendVarBinds( snmpEngine, \(aqmy\-notification\(aq, # notification targets None, \(aq\(aq, # contextEngineId, contextName # var\-binds [ # SNMPv2\-SMI::snmpTrapOID.0 = SNMPv2\-MIB::coldStart ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))) ] ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and stop snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced topic .SS Send crafted TRAP PDU .sp Initialize TRAP PDU and pass it over to unified SNMPv3 message processing framework for further treatment. .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 initialize TRAP PDU with the following var\-binds: 1.3.6.1.2.1.1.3.0 = 123 1.3.6.1.6.3.1.1.4.1.0 = 1.3.6.1.6.3.1.1.5.1 .UNINDENT .sp Functionally similar to: .nf $ snmptrap \-v2c \-c public demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntforg from pysnmp.proto.api import v2c # Create SNMP engine instance snmpEngine = engine.SnmpEngine() # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Specify security settings per SecurityName (SNMPv2c \-> 1) config.addTargetParams(snmpEngine, \(aqmy\-creds\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 1) # Setup transport endpoint and bind it with security settings yielding # a target name config.addTransport( snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Create named target config.addTargetAddr( snmpEngine, \(aqmy\-nms\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 162), \(aqmy\-creds\(aq ) # *** SNMP engine configuration is complete by this line *** # Create SNMP v2c TRAP PDU with defaults trapPDU = v2c.TrapPDU() v2c.apiTrapPDU.setDefaults(trapPDU) # Set custom var\-binds to TRAP PDU v2c.apiTrapPDU.setVarBinds( trapPDU, [ # sysUpTime (v2c.ObjectIdentifier(\(aq1.3.6.1.2.1.1.3.0\(aq), v2c.TimeTicks(123)), # snmpTrapPDU ((1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0), v2c.ObjectIdentifier((1, 3, 6, 1, 6, 3, 1, 1, 5, 1))) ] ) # Create Notification Originator App instance. ntfOrg = ntforg.NotificationOriginator() # Error/confirmation receiver # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): print(\(aqNotification %s, status \- %s\(aq % ( sendRequestHandle, errorIndication and errorIndication or \(aqdelivered\(aq ) ) # Build and submit notification message to dispatcher ntfOrg.sendPdu( snmpEngine, # Notification targets \(aqmy\-nms\(aq, # target address None, \(aq\(aq, # contextEngineId, contextName trapPDU, cbFun ) print(\(aqNotification is scheduled to be sent\(aq) # Run I/O dispatcher which would send pending message and process response snmpEngine.transportDispatcher.runDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Notification Receiver Applications .SS Various SNMP versions .SS Serving multiple network interfaces .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 over IPv4/UDP, listening at 127.0.0.1:2162 .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 2162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple SNMP USM users .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 with USM users: .INDENT 2.0 .IP \(bu 2 \(aqusr\-md5\-des\(aq, auth: MD5, priv DES, ContextEngineId: 8000000001020304 .IP \(bu 2 \(aqusr\-md5\-none\(aq, auth: MD5, priv NONE, ContextEngineId: 8000000001020304 .IP \(bu 2 \(aqusr\-sha\-aes128\(aq, auth: SHA, priv AES, ContextEngineId: 8000000001020304 .UNINDENT .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv from pysnmp.proto.api import v2c # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # user: usr\-md5\-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq, securityEngineId=v2c.OctetString(hexValue=\(aq8000000001020304\(aq) ) # user: usr\-md5\-none, auth: MD5, priv NONE config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) # user: usr\-md5\-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, securityEngineId=v2c.OctetString(hexValue=\(aq8000000001020304\(aq) ) # user: usr\-sha\-aes128, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) # user: usr\-sha\-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq, securityEngineId=v2c.OctetString(hexValue=\(aq8000000001020304\(aq) ) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Serving multiple network interfaces .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 over IPv4/UDP, listening at 127.0.0.1:2162 .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 2162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Using multiple network transports .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 over IPv6/UDP, listening at [::1]:162 .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # UDP over IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode((\(aq::1\(aq, 162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Receive notifications noting peer address .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 .IP \(bu 2 use observer facility to pull lower\-level request details from SNMP engine .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): # Get an execution context... execContext = snmpEngine.observer.getExecutionContext( \(aqrfc3412.receiveMessage:request\(aq ) # ... and use inner SNMP engine data to figure out peer address print(\(aqNotification from %s, ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (\(aq@\(aq.join([str(x) for x in execContext[\(aqtransportAddress\(aq]]), contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Advanced topics .SS Observe SNMP engine internal operations .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 over IPv6/UDP, listening at [::1]:162 .IP \(bu 2 registers its own execution observer to snmpEngine .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity.rfc3413 import ntfrcv # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Execution point observer setup # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at code point\(aqs local scope # noinspection PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): print(\(aqExecution point: %s\(aq % execpoint) print(\(aq* transportDomain: %s\(aq % \(aq.\(aq.join([str(x) for x in variables[\(aqtransportDomain\(aq]])) print(\(aq* transportAddress: %s\(aq % \(aq@\(aq.join([str(x) for x in variables[\(aqtransportAddress\(aq]])) print(\(aq* securityModel: %s\(aq % variables[\(aqsecurityModel\(aq]) print(\(aq* securityName: %s\(aq % variables[\(aqsecurityName\(aq]) print(\(aq* securityLevel: %s\(aq % variables[\(aqsecurityLevel\(aq]) print(\(aq* contextEngineId: %s\(aq % variables[\(aqcontextEngineId\(aq].prettyPrint()) print(\(aq* contextName: %s\(aq % variables[\(aqcontextName\(aq].prettyPrint()) print(\(aq* PDU: %s\(aq % variables[\(aqpdu\(aq].prettyPrint()) snmpEngine.observer.registerObserver( requestObserver, \(aqrfc3412.receiveMessage:request\(aq, \(aqrfc3412.returnResponsePdu\(aq ) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # UDP over IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode((\(aq::1\(aq, 162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send confirmations try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.observer.unregisterObserver() snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Serve SNMP Community names defined by regexp .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with any SNMP community matching regexp \(aq.*love.*\(aq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ snmptrap \-v1 \-c rollover 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test $ snmpinform \-v2c \-c glove 127.0.0.1 123 1.3.6.1.6.3.1.1.5.1 .fi .sp .sp The Notification Receiver below taps on v1/v2c SNMP security module to deliver certains values, normally internal to SNMP Engine, up to the context of user application. .sp This script examines the value of CommunityName, as it came from peer SNMP Engine, and may modify it to match the only locally configured CommunityName \(aqpublic\(aq. This effectively makes NotificationReceiver accepting messages with CommunityName\(aqs, not explicitly configured to local SNMP Engine. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv import re # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Register a callback to be invoked at specified execution point of # SNMP Engine and passed local variables at execution point\(aqs local scope. # If at this execution point passed variables are modified, their new # values will be propagated back and used by SNMP Engine for securityName # selection. # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def requestObserver(snmpEngine, execpoint, variables, cbCtx): if re.match(\(aq.*love.*\(aq, str(variables[\(aqcommunityName\(aq])): print(\(aqRewriting communityName \e\(aq%s\e\(aq from %s into \e\(aqpublic\e\(aq\(aq % (variables[\(aqcommunityName\(aq], \(aq:\(aq.join([str(x) for x in variables[\(aqtransportInformation\(aq][1]]))) variables[\(aqcommunityName\(aq] = variables[\(aqcommunityName\(aq].clone(\(aqpublic\(aq) snmpEngine.observer.registerObserver( requestObserver, \(aqrfc2576.processIncomingMsg:writable\(aq ) # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (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 .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Proxy Forwarder Applications .SS Transport conversion .SS IPv6\-to\-IPv4 conversion .sp Act as a local SNMPv1/v2c Agent listening on a UDP/IPv6 transport, relay messages to distant SNMPv1/2c Agent over UDP/IPv4 transport: .INDENT 0.0 .IP \(bu 2 with local SNMPv2c community \(aqpublic\(aq .IP \(bu 2 local Agent listening at [::1]:161 .IP \(bu 2 remote SNMPv2c community \(aqpublic\(aq .IP \(bu 2 remote Agent listening at 104.236.166.95:161 .UNINDENT .sp This script can be queried with the following Net\-SNMP command: .nf $ snmpget \-v2c \-c public udp6:[::1]:161 sysDescr.0 .fi .sp .sp due to proxy, it is equivalent to .nf $ snmpget \-v2c \-c public 104.236.166.95:161 sysDescr.0 .fi .sp .sp Warning: for production operation you would need to modify this script so that it will re\-map possible duplicate request\-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request\-IDs to Agents. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dgram import udp, udp6 from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv6 config.addTransport( snmpEngine, udp6.domainName, udp6.Udp6Transport().openServerMode((\(aq::1\(aq, 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, \(aq1\-my\-area\(aq, \(aqpublic\(aq) # # SNMPv1/v2c setup (Manager role) # # Here we configure securityName lexicographically lesser than \(aq1\-my\-area\(aq # to let it match first in snmpCommunityTable on response processing. # config.addV1System(snmpEngine, \(aq0\-distant\-area\(aq, \(aqpublic\(aq, transportTag=\(aqremote\(aq) # # Transport target used by Manager # config.addTargetParams( snmpEngine, \(aqdistant\-agent\-auth\(aq, \(aq0\-distant\-area\(aq, \(aqnoAuthNoPriv\(aq, 1 ) config.addTargetAddr( snmpEngine, \(aqdistant\-agent\(aq, udp.domainName, (\(aq104.236.166.95\(aq, 161), \(aqdistant\-agent\-auth\(aq, retryCount=0, tagList=\(aqremote\(aq ) # Default SNMP context config.addContext(snmpEngine, \(aq\(aq) class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, \(aqdistant\-agent\(aq, contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, \(aqerror\(aq, None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu( snmpEngine, stateReference, PDU ) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library\-reference\fP\&. .SS Protocol conversion .SS SNMPv2c\-to\-SNMPv1 conversion .sp Act as a local SNMPv2c Agent, relay messages to distant SNMPv1 Agent: .INDENT 0.0 .IP \(bu 2 over IPv4/UDP .IP \(bu 2 with local SNMPv2c community public .IP \(bu 2 local Agent listening at 127.0.0.1:161 .IP \(bu 2 remote SNMPv1, community public .IP \(bu 2 remote Agent listening at 104.236.166.95:161 .UNINDENT .sp This script can be queried with the following Net\-SNMP command: .nf $ snmpbulkwalk \-v2c \-c public \-ObentU 127.0.0.1:161 system .fi .sp .sp due to proxy, it is equivalent to .nf $ snmpwalk \-v1 \-c public 104.236.166.95:161 system .fi .sp .sp Warning: for production operation you would need to modify this script so that it will re\-map possible duplicate request\-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request\-IDs to Agents. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 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, \(aqmy\-area\(aq, \(aqpublic\(aq) # # SNMPv1 setup (Manager role) # # SecurityName <\-> CommunityName <\-> Transport mapping config.addV1System(snmpEngine, \(aqdistant\-area\(aq, \(aqpublic\(aq, transportTag=\(aqdistant\(aq) # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqdistant\-agent\-auth\(aq, \(aqdistant\-area\(aq, \(aqnoAuthNoPriv\(aq, 0) config.addTargetAddr( snmpEngine, \(aqdistant\-agent\(aq, udp.domainName + (2,), (\(aq104.236.166.95\(aq, 161), \(aqdistant\-agent\-auth\(aq, retryCount=0, tagList=\(aqdistant\(aq ) # Default SNMP context config.addContext(snmpEngine, \(aq\(aq) class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, \(aqdistant\-agent\(aq, contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, \(aqerror\(aq, None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu( snmpEngine, stateReference, PDU ) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv2c\-to\-SNMPv3 conversion .sp Act as a local SNMPv1/v2c Agent, relay messages to distant SNMPv3 Agent: * over IPv4/UDP * with local SNMPv2c community \(aqpublic\(aq * local Agent listening at 127.0.0.1:161 * remote SNMPv3 user usr\-md5\-none, MD5 auth and no privacy protocols * remote Agent listening at 104.236.166.95:161 .sp This script can be queried with the following Net\-SNMP command: .nf $ snmpget \-v2c \-c public 127.0.0.1:161 1.3.6.1.2.1.1.1.0 .fi .sp .sp due to proxy, it is equivalent to .nf $ snmpget \-v3 \-l authNoPriv \-u usr\-md5\-none \-A authkey1 \-ObentU 104.236.166.95:161 1.3.6.1.2.1.1.1.0 .fi .sp .sp Warning: for production operation you would need to modify this script so that it will re\-map possible duplicate request\-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request\-IDs to Agents. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 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, \(aqmy\-area\(aq, \(aqpublic\(aq) # # SNMPv3/USM setup (Manager role) # # user: usr\-md5\-none, auth: MD5, priv NONE config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) # # Transport target used by Manager # config.addTargetParams( snmpEngine, \(aqdistant\-agent\-auth\(aq, \(aqusr\-md5\-none\(aq, \(aqauthNoPriv\(aq ) config.addTargetAddr( snmpEngine, \(aqdistant\-agent\(aq, udp.domainName + (2,), (\(aq104.236.166.95\(aq, 161), \(aqdistant\-agent\-auth\(aq, retryCount=0 ) # Default SNMP context config.addContext(snmpEngine, \(aq\(aq) class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, \(aqdistant\-agent\(aq, contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, \(aqerror\(aq, None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu( snmpEngine, stateReference, PDU ) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMPv3\-to\-SNMPv2c conversion .sp Act as a local SNMPv3 Agent, relay messages to distant SNMPv1/v2c Agent: * over IPv4/UDP * with local SNMPv3 user usr\-md5\-des, MD5 auth and DES privacy protocols * local Agent listening at 127.0.0.1:161 * remote SNMPv1, community public * remote Agent listening at 104.236.166.95:161 .sp This script can be queried with the following Net\-SNMP command: .nf $ 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 .fi .sp .sp due to proxy, it is equivalent to .nf $ snmpget \-v2c \-c public 104.236.166.95:161 1.3.6.1.2.1.1.1.0 .fi .sp .sp Warning: for production operation you would need to modify this script so that it will re\-map possible duplicate request\-ID values, coming in initial request PDUs from different Managers, into unique values to avoid sending duplicate request\-IDs to Agents. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dgram import udp from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, cmdgen, context from pysnmp.proto.api import v2c from pysnmp import error # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # # Transport setup # # Agent section # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 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, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # # SNMPv1/2c setup (Manager role) # # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # # Transport target used by Manager # # Specify security settings per SecurityName (SNMPv1 \- 0, SNMPv2c \- 1) config.addTargetParams(snmpEngine, \(aqdistant\-agent\-auth\(aq, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, 0) config.addTargetAddr( snmpEngine, \(aqdistant\-agent\(aq, udp.domainName + (2,), (\(aq104.236.166.95\(aq, 161), \(aqdistant\-agent\-auth\(aq, retryCount=0 ) # Default SNMP context config.addContext(snmpEngine, \(aq\(aq) class CommandResponder(cmdrsp.CommandResponderBase): cmdGenMap = { v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun() } pduTypes = cmdGenMap.keys() # This app will handle these PDUs # SNMP request relay def handleMgmtOperation(self, snmpEngine, stateReference, contextName, PDU, acInfo): cbCtx = stateReference, PDU contextEngineId = None # address authoritative SNMP Engine try: self.cmdGenMap[PDU.tagSet].sendPdu( snmpEngine, \(aqdistant\-agent\(aq, contextEngineId, contextName, PDU, self.handleResponsePdu, cbCtx ) except error.PySnmpError: self.handleResponsePdu( snmpEngine, stateReference, \(aqerror\(aq, None, cbCtx ) # SNMP response relay # noinspection PyUnusedLocal def handleResponsePdu(self, snmpEngine, sendRequestHandle, errorIndication, PDU, cbCtx): stateReference, reqPDU = cbCtx if errorIndication: PDU = v2c.apiPDU.getResponse(reqPDU) PDU.setErrorStatus(PDU, 5) self.sendPdu(snmpEngine, stateReference, PDU) self.releaseStateInformation(stateReference) CommandResponder(snmpEngine, context.SnmpContext(snmpEngine)) snmpEngine.transportDispatcher.jobStarted(1) # this job would never finish # Run I/O dispatcher which would receive queries and send responses try: snmpEngine.transportDispatcher.runDispatcher() except: snmpEngine.transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library\-reference\fP\&. .sp For more details on PySNMP programming model and interfaces, please refer to the documentation .SS Asynchronous: asyncio .sp Python 3.4 introduced a new module \- \fI\%asyncio\fP (former Tulip, PEP 3156) featuring infrastructure for writing single\-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources. .sp PySNMP library was originally built on top of Python\(aqs asynchronous I/O library called asyncio. The asyncio module offers similar functionality but uses much more modern and powerful language facilities. Functionally, asyncio can replace asyncio in PySNMP however its use requires understanding the concepts such as coroutines and generators. If your task is to embed SNMP stack into an existing asyncio\-based app, using PySNMP\(aqs asyncio interfaces greatly simplifies the task. .sp Older applications (Python 2.6+) can alternatively use \fI\%Trollius\fP instead of asyncio. Trollius is a backport of asyncio so it \fI\%supports\fP nearly the same API as asyncio. Full support of both modules is built into pysnmp. .sp All SNMP\-related functionality of Native PySNMP API to Standard SNMP Applications (\fI\%RFC3413\fP) remains available to asyncio\-backed applications. .sp We do not provide Command Generator and Notification Originator examples, as it is much easier to use \fI\%high\-level interfaces\fP instead. .SS Command Responder Applications .SS Various SNMP versions .SS Multiple SNMP USM users .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 .INDENT 2.0 .TP .B with USM user: .INDENT 7.0 .IP \(bu 2 \(aqusr\-md5\-des\(aq, auth: MD5, priv DES or .IP \(bu 2 \(aqusr\-sha\-none\(aq, auth: SHA, no privacy .IP \(bu 2 \(aqusr\-sha\-aes128\(aq, auth: SHA, priv AES .UNINDENT .UNINDENT .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 using asyncio network transport (available since Python 3.4) .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ 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 .fi .sp .sp Requires Python 3.4 and later! .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.entity.rfc3413 import cmdrsp, context from pysnmp.carrier.asyncio.dgram import udp import asyncio # Get the event loop for this thread loop = asyncio.get_event_loop() # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4 config.addTransport( snmpEngine, udp.domainName, udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 161)) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # user: usr\-sha\-none, auth: SHA, priv NONE config.addV3User( snmpEngine, \(aqusr\-sha\-none\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq ) # user: usr\-sha\-none, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, \(aqusr\-sha\-none\(aq, \(aqauthNoPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, \(aqusr\-sha\-aes128\(aq, \(aqauthPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) # Get default SNMP context this SNMP engine serves snmpContext = context.SnmpContext(snmpEngine) # Register SNMP Applications at the SNMP engine for particular SNMP context cmdrsp.GetCommandResponder(snmpEngine, snmpContext) cmdrsp.SetCommandResponder(snmpEngine, snmpContext) cmdrsp.NextCommandResponder(snmpEngine, snmpContext) cmdrsp.BulkCommandResponder(snmpEngine, snmpContext) # Run asyncio main loop loop.run_forever() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Notification Receiver Applications .SS Transport tweaks .SS Serving multiple network interfaces .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 over IPv4/UDP, listening at 127.0.0.1:2162 .IP \(bu 2 using Asyncio framework for network transport .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .sp Requires Python 3.4 and later! .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.entity import engine, config from pysnmp.carrier.asyncio.dgram import udp from pysnmp.entity.rfc3413 import ntfrcv import asyncio # Get the event loop for this thread loop = asyncio.get_event_loop() # Create SNMP engine with autogenernated engineID and pre\-bound # to socket transport dispatcher snmpEngine = engine.SnmpEngine() # Transport setup # UDP over IPv4, first listening interface/port config.addTransport( snmpEngine, udp.domainName + (1,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTransport().openServerMode((\(aq127.0.0.1\(aq, 2162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) print(\(aqNotification from %s, SNMP Engine %s, Context %s\(aq % (transportAddress, contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run asyncio main loop loop.run_forever() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp For more details on PySNMP programming model and interfaces, please refer to the documentation .SS Asynchronous: trollius .sp \fI\%Trollius\fP framework offers infrastructure that allows you writing single\-threaded, concurrent code using Python coroutines. .sp Trollius is a backport of \fI\%asyncio\fP to Python versions older than 3.3. Trollius supports nearly the same API as asyncio. Full support of both asyncio and trollius modules is built into pysnmp. .sp All SNMP\-related functionality of Native PySNMP API to Standard SNMP Applications (\fI\%RFC3413\fP) remains available to asyncio\-backed applications. .sp We do not provide Command Generator and Notification Originator examples, as it is much easier to use \fI\%high\-level interfaces\fP instead. As for Command Responder and Notification Receiver, those could be use in the same way as with \fI\%asyncio\fP\&. .sp For more details on PySNMP programming model and interfaces, please refer to the documentation .SS Asynchronous: Twisted .sp \fI\%Twisted\fP is event\-driven networking engine written in Python. It takes shape of a Python library which is used by many Python applications mostly for network communication purposes. .sp All SNMP\-related functionality of Native API to Standard SNMP Applications remains available to Twisted applications. .sp We do not provide Command Generator and Notification Originator examples, as it is much easier to use \fI\%high\-level interfaces\fP instead. .SS Command Responder Applications .SS Various SNMP versions .SS Multiple SNMP communities .sp Listen and respond to SNMP GET/SET/GETNEXT queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 .IP \(bu 2 with SNMP community \(dqpublic\(dq (read access) or \(dqprivate\(dq (write access) .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 using Twisted fraework for network transport .UNINDENT .sp The following Net\-SNMP commands will GET/SET a value at this Agent: .nf $ 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 \(dqfar away\(dq .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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((\(aq127.0.0.1\(aq, 161)) ) # SNMPv1 setup # SecurityName <\-> CommunityName mapping. # Here we configure two distinct CommunityName\(aqs to control read and write # operations. config.addV1System(snmpEngine, \(aqmy\-read\-area\(aq, \(aqpublic\(aq) config.addV1System(snmpEngine, \(aqmy\-write\-area\(aq, \(aqprivate\(aq) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 1, \(aqmy\-read\-area\(aq, \(aqnoAuthNoPriv\(aq, (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 1, \(aqmy\-write\-area\(aq, \(aqnoAuthNoPriv\(aq, (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() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Multiple SNMP USM users .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 .INDENT 2.0 .TP .B with USM user: .INDENT 7.0 .IP \(bu 2 \(aqusr\-md5\-des\(aq, auth: MD5, priv DES or .IP \(bu 2 \(aqusr\-sha\-none\(aq, auth: SHA, no privacy .IP \(bu 2 \(aqusr\-sha\-aes128\(aq, auth: SHA, priv AES .UNINDENT .UNINDENT .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 using Twisted framework for network transport .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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((\(aq127.0.0.1\(aq, 161)) ) # SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # user: usr\-sha\-none, auth: SHA, priv NONE config.addV3User( snmpEngine, \(aqusr\-sha\-none\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq ) # user: usr\-sha\-none, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) # Allow full MIB access for each user at VACM config.addVacmUser(snmpEngine, 3, \(aqusr\-md5\-des\(aq, \(aqauthPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, \(aqusr\-sha\-none\(aq, \(aqauthNoPriv\(aq, (1, 3, 6, 1, 2, 1), (1, 3, 6, 1, 2, 1)) config.addVacmUser(snmpEngine, 3, \(aqusr\-sha\-aes128\(aq, \(aqauthPriv\(aq, (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() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Agent\-side MIB implementations .SS Implementing scalar MIB objects .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 serving custom Managed Object Instance defined within this script .IP \(bu 2 allow read access only to the subtree where the custom MIB object resides .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 using Twisted fraework for network transport .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 .1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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((\(aq127.0.0.1\(aq, 161)) ) # SNMPv2c setup # SecurityName <\-> CommunityName mapping. config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Allow read MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (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( \(aqSNMPv2\-SMI\(aq, \(aqMibScalar\(aq, \(aqMibScalarInstance\(aq ) class MyStaticMibScalarInstance(MibScalarInstance): # noinspection PyUnusedLocal,PyUnusedLocal def getValue(self, name, idx): return self.getSyntax().clone( \(aqPython %s running on a %s platform\(aq % (sys.version, sys.platform) ) mibBuilder.exportSymbols( \(aq__MY_MIB\(aq, 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() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Listen on multiple network interfaces .sp Listen and respond to SNMP GET/SET/GETNEXT/GETBULK queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 allow access to SNMPv2\-MIB objects (1.3.6.1.2.1) .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 and 127.0.0.2:161 interfaces .IP \(bu 2 using Twisted framework for network transport .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 .1.3.6 $ snmpwalk \-v2c \-c public 127.0.0.2 .1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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((\(aq127.0.0.1\(aq, 161)) ) # UDP over IPv4 at 127.0.0.2:161 config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTwistedTransport().openServerMode((\(aq127.0.0.2\(aq, 161)) ) # SNMPv2c setup # SecurityName <\-> CommunityName mapping. config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Allow full MIB access for this user / securityModels at VACM config.addVacmUser(snmpEngine, 2, \(aqmy\-area\(aq, \(aqnoAuthNoPriv\(aq, (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() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Notification Receiver Applications .SS Various SNMP versions .SS Multiple SNMP USM users .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv3 .IP \(bu 2 .INDENT 2.0 .TP .B with USM users: .INDENT 7.0 .IP \(bu 2 \(aqusr\-md5\-des\(aq, auth: MD5, priv DES, ContextEngineId: 8000000001020304 .IP \(bu 2 \(aqusr\-md5\-none\(aq, auth: MD5, priv NONE, ContextEngineId: 8000000001020304 .IP \(bu 2 \(aqusr\-sha\-aes128\(aq, auth: SHA, priv AES, ContextEngineId: 8000000001020304 .UNINDENT .UNINDENT .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 .IP \(bu 2 using Twisted framework for network transport .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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((\(aq127.0.0.1\(aq, 162)) ) # \-\- begin of SNMPv3/USM setup # user: usr\-md5\-des, auth: MD5, priv DES config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq ) # user: usr\-md5\-des, auth: MD5, priv DES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, \(aqusr\-md5\-des\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, config.usmDESPrivProtocol, \(aqprivkey1\(aq, securityEngineId=rfc1902.OctetString(hexValue=\(aq8000000001020304\(aq) ) # user: usr\-md5\-none, auth: MD5, priv NONE config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq ) # user: usr\-md5\-none, auth: MD5, priv NONE, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, \(aqusr\-md5\-none\(aq, config.usmHMACMD5AuthProtocol, \(aqauthkey1\(aq, securityEngineId=rfc1902.OctetString(hexValue=\(aq8000000001020304\(aq) ) # user: usr\-sha\-aes128, auth: SHA, priv AES config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq ) # user: usr\-sha\-aes128, auth: SHA, priv AES, securityEngineId: 8000000001020304 # this USM entry is used for TRAP receiving purposes config.addV3User( snmpEngine, \(aqusr\-sha\-aes128\(aq, config.usmHMACSHAAuthProtocol, \(aqauthkey1\(aq, config.usmAesCfb128Protocol, \(aqprivkey1\(aq, securityEngineId=rfc1902.OctetString(hexValue=\(aq8000000001020304\(aq) ) # \-\- end of SNMPv3/USM setup # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, ContextName \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run Twisted main loop reactor.run() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Serving multiple network interfaces .sp Receive SNMP TRAP/INFORM messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 .INDENT 2.0 .TP .B listen on two local network interfaces: .INDENT 7.0 .IP \(bu 2 IPv4/UDP, listening at 127.0.0.1:162 .IP \(bu 2 IPv4/UDP, listening at 127.0.0.1:2162 .UNINDENT .UNINDENT .IP \(bu 2 using Twisted framework for network transport .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ 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 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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((\(aq127.0.0.1\(aq, 162)) ) # UDP over IPv4, second listening interface/port config.addTransport( snmpEngine, udp.domainName + (2,), udp.UdpTwistedTransport().openServerMode((\(aq127.0.0.1\(aq, 2162)) ) # SNMPv1/2c setup # SecurityName <\-> CommunityName mapping config.addV1System(snmpEngine, \(aqmy\-area\(aq, \(aqpublic\(aq) # Callback function for receiving notifications # noinspection PyUnusedLocal,PyUnusedLocal,PyUnusedLocal def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): print(\(aqNotification from ContextEngineId \(dq%s\(dq, Context \(dq%s\(dq\(aq % (contextEngineId.prettyPrint(), contextName.prettyPrint())) for name, val in varBinds: print(\(aq%s = %s\(aq % (name.prettyPrint(), val.prettyPrint())) # Register SNMP Application at the SNMP engine ntfrcv.NotificationReceiver(snmpEngine, cbFun) # Run Twisted main loop reactor.run() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .sp For more details on PySNMP programming model and interfaces, please refer to the documentation .SS Packet\-level SNMP .sp In cases where performance is your top priority and you only need to work with SNMP v1 and v2c systems and you do not mind writing much more code, then there is a low\-level API to SNMP v1/v2c PDU and PySNMP I/O engine. There\(aqs practically no SNMP engine or SMI infrastructure involved in the operations of these almost wire\-level interfaces. Although MIB services can still be used separately. .sp A packet\-level API\-based application typically manages both SNMP message building/parsing and network communication via one or more transports. It\(aqs fully up to the application to handle failures on message and transport levels. .SS Command Generator .SS Fetching variables .SS Fetch scalar MIB variables (SNMPv1) .sp Perform SNMP GET operation with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for OIDs in tuple form .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v1 \-c public \-ObentU demo.snmplabs.com 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Protocol version to use pMod = api.protoModules[api.protoVersion1] # pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.GetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, ((\(aq1.3.6.1.2.1.1.1.0\(aq, pMod.Null(\(aq\(aq)), (\(aq1.3.6.1.2.1.1.3.0\(aq, pMod.Null(\(aq\(aq))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow \- startedAt > 3: raise Exception(\(dqRequest timed out\(dq) # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, (\(aqdemo.snmplabs.com\(aq, 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, (\(aq::1\(aq, 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, \(aq/tmp/snmp\-agent\(aq # ) # transportDispatcher.jobStarted(1) # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Modifying variables .SS SET string and integer scalars (SNMPv2c) .sp Perform SNMP SET operation with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for OIDs in string form and values in form of pyasn1 objects .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpset \-v2c \-c public \-ObentU demo.snmplabs.com 1.3.6.1.2.1.1.9.1.3.1 s \(aqNew description\(aq 1.3.6.1.2.1.1.9.1.4.1 t 12 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Protocol version to use # pMod = api.protoModules[api.protoVersion1] pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.SetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, # A list of Var\-Binds to SET ((\(aq1.3.6.1.2.1.1.9.1.3.1\(aq, pMod.OctetString(\(aqNew system description\(aq)), (\(aq1.3.6.1.2.1.1.9.1.4.1\(aq, pMod.TimeTicks(12))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow \- startedAt > 3: raise Exception(\(dqRequest timed out\(dq) # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, (\(aqdemo.snmplabs.com\(aq, 161) ) transportDispatcher.jobStarted(1) # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS MIB walking operations .SS Walk Agent MIB (SNMPv1) .sp Perform SNMP GETNEXT operation with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for OID in tuple form .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpwalk \-v1 \-c public \-ObentU demo.snmplabs.com 1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Protocol version to use pMod = api.protoModules[api.protoVersion1] # pMod = api.protoModules[api.protoVersion2c] # SNMP table header headVars = [pMod.ObjectIdentifier((1, 3, 6))] # Build PDU reqPDU = pMod.GetNextRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds(reqPDU, [(x, pMod.null) for x in headVars]) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow \- startedAt > 3: raise Exception(\(dqRequest timed out\(dq) # noinspection PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU, headVars=headVars): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus and errorStatus != 2: raise Exception(errorStatus) # Format var\-binds table varBindTable = pMod.apiPDU.getVarBindTable(reqPDU, rspPDU) # Report SNMP table for tableRow in varBindTable: for name, val in tableRow: print(\(aqfrom: %s, %s = %s\(aq % ( 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(\(aqRequest timed out\(aq) startedAt = time() return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, (\(aqdemo.snmplabs.com\(aq, 161) ) transportDispatcher.jobStarted(1) transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Bulk walk Agent MIB (SNMPv2c) .sp Perform SNMP GETBULK operation with the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at demo.snmplabs.com:161 .IP \(bu 2 for OID in tuple form .IP \(bu 2 with non\-repeaters=0 and max\-repeaters=25 .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpbulkwalk \-v2c \-c public \-ObentU \-Cn0 \-Cr25 demo.snmplabs.com 1.3.6 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto.api import v2c from time import time # SNMP table header headVars = [v2c.ObjectIdentifier((1, 3, 6))] # Build PDU reqPDU = v2c.GetBulkRequestPDU() v2c.apiBulkPDU.setDefaults(reqPDU) v2c.apiBulkPDU.setNonRepeaters(reqPDU, 0) v2c.apiBulkPDU.setMaxRepetitions(reqPDU, 25) v2c.apiBulkPDU.setVarBinds(reqPDU, [(x, v2c.null) for x in headVars]) # Build message reqMsg = v2c.Message() v2c.apiMessage.setDefaults(reqMsg) v2c.apiMessage.setCommunity(reqMsg, \(aqpublic\(aq) v2c.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow \- startedAt > 3: raise Exception(\(dqRequest timed out\(dq) # noinspection PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU, headVars=headVars): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=v2c.Message()) rspPDU = v2c.apiMessage.getPDU(rspMsg) # Match response to request if v2c.apiBulkPDU.getRequestID(reqPDU) == v2c.apiBulkPDU.getRequestID(rspPDU): # Format var\-binds table varBindTable = v2c.apiBulkPDU.getVarBindTable(reqPDU, rspPDU) # Check for SNMP errors reported errorStatus = v2c.apiBulkPDU.getErrorStatus(rspPDU) if errorStatus and errorStatus != 2: errorIndex = v2c.apiBulkPDU.getErrorIndex(rspPDU) print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBindTable[int(errorIndex) \- 1] or \(aq?\(aq)) transportDispatcher.jobFinished(1) break # Report SNMP table for tableRow in varBindTable: for name, val in tableRow: print(\(aqfrom: %s, %s = %s\(aq % ( 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(\(aqRequest timed out\(aq) startedAt = time() return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, (\(aqdemo.snmplabs.com\(aq, 161) ) transportDispatcher.jobStarted(1) # Dispatcher will finish as job#1 counter reaches zero transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Transport tweaks .SS Spoof IPv4 source address .sp Send SNMP GET request from a non\-local IP address: .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to an Agent at 104.236.166.95:161 .IP \(bu 2 from a non\-local, spoofed IP 1.2.3.4 (root and Python 3.3+ required) .IP \(bu 2 for OIDs in string form .UNINDENT .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v2c \-c public \-ObentU 104.236.166.95 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 .fi .sp .sp But unlike the above command, this script issues SNMP request from a non\-default, non\-local IP address. .sp It is indeed possible to originate SNMP traffic from any valid local IP addresses. It could be a secondary IP interface, for instance. Superuser privileges are only required to send spoofed packets. Alternatively, sending from local interface could also be achieved by binding to it (via openClientMode() parameter). .sp Agent would respond to the IP address you used as a source. So this script could only get a response if that source address is somehow routed to the host this script is running on. Otherwise it just times out. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pysnmp.proto import api from pyasn1.codec.ber import encoder, decoder from time import time # Send request message to this address transportAddress = udp.UdpTransportAddress((\(aq104.236.166.95\(aq, 161)) # Send request message from this non\-local (!) IP address transportAddress.setLocalAddress((\(aq1.2.3.4\(aq, 0)) # Protocol version to use # pMod = api.protoModules[api.protoVersion1] pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.GetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, ((\(aq1.3.6.1.2.1.1.1.0\(aq, pMod.Null(\(aq\(aq)), (\(aq1.3.6.1.2.1.1.3.0\(aq, pMod.Null(\(aq\(aq))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() class StopWaiting(Exception): pass def cbTimerFun(timeNow): if timeNow \- startedAt > 3: raise StopWaiting() # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # Initialize UDP/IPv4 transport udpSocketTransport = udp.UdpSocketTransport().openClientMode() # Use sendmsg()/recvmsg() for socket communication (required for # IP source spoofing functionality) udpSocketTransport.enablePktInfo() # Enable IP source spoofing (requires root privileges) udpSocketTransport.enableTransparent() transportDispatcher.registerTransport(udp.domainName, udpSocketTransport) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, transportAddress ) # We might never receive any response as we sent request with fake source IP transportDispatcher.jobStarted(1) # Dispatcher will finish as all jobs counter reaches zero try: transportDispatcher.runDispatcher() except StopWaiting: transportDispatcher.closeDispatcher() else: raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Broadcast SNMP message (IPv4) .sp Send SNMP GET request to broadcast address and wait for respons(es): .INDENT 0.0 .IP \(bu 2 with SNMPv2c, community \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP .IP \(bu 2 to all Agents via broadcast address 255.255.255.255:161 .IP \(bu 2 for OIDs in tuple form .UNINDENT .sp Here we send out a single SNMP request and wait for potentially many SNMP responses from multiple SNMP Agents listening in local broadcast domain. Since we can\(aqt predict the exact number of Agents responding, this script just waits for arbitrary time for collecting all responses. This technology is also known as SNMP\-based discovery. .sp This script performs similar to the following Net\-SNMP command: .nf $ snmpget \-v2c \-c public \-ObentU 255.255.255.255 1.3.6.1.2.1.1.1.0 1.3.6.1.2.1.1.3.0 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api from time import time # Broadcast manager settings maxWaitForResponses = 5 maxNumberResponses = 10 # Protocol version to use # pMod = api.protoModules[api.protoVersion1] pMod = api.protoModules[api.protoVersion2c] # Build PDU reqPDU = pMod.GetRequestPDU() pMod.apiPDU.setDefaults(reqPDU) pMod.apiPDU.setVarBinds( reqPDU, ((\(aq1.3.6.1.2.1.1.1.0\(aq, pMod.Null(\(aq\(aq)), (\(aq1.3.6.1.2.1.1.3.0\(aq, pMod.Null(\(aq\(aq))) ) # Build message reqMsg = pMod.Message() pMod.apiMessage.setDefaults(reqMsg) pMod.apiMessage.setCommunity(reqMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(reqMsg, reqPDU) startedAt = time() class StopWaiting(Exception): pass def cbTimerFun(timeNow): if timeNow \- startedAt > maxWaitForResponses: raise StopWaiting() # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 udpSocketTransport = udp.UdpSocketTransport().openClientMode().enableBroadcast() transportDispatcher.registerTransport(udp.domainName, udpSocketTransport) # Pass message to dispatcher transportDispatcher.sendMessage( encoder.encode(reqMsg), udp.domainName, (\(aq255.255.255.255\(aq, 161) ) # wait for a maximum of 10 responses or time out transportDispatcher.jobStarted(1, maxNumberResponses) # Dispatcher will finish as all jobs counter reaches zero try: transportDispatcher.runDispatcher() except StopWaiting: transportDispatcher.closeDispatcher() else: raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Command Responder .SS Agent\-side MIB implementations .SS Implementing scalar MIB objects .sp Listen and respond to SNMP GET/GETNEXT queries with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1 or SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:161 .IP \(bu 2 over IPv6/UDP, listening at [::1]:161 .IP \(bu 2 serving two Managed Objects Instances (sysDescr.0 and sysUptime.0) .UNINDENT .sp Either of the following Net\-SNMP commands will walk this Agent: .nf $ snmpwalk \-v2c \-c public 127.0.0.1 .1.3.6 $ snmpwalk \-v2c \-c public udp6:[::1] .1.3.6 .fi .sp .sp The Command Receiver below uses two distinct transports for communication with Command Generators \- UDP over IPv4 and UDP over IPv6. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder, decoder from pysnmp.proto import api import time, bisect class SysDescr(object): name = (1, 3, 6, 1, 2, 1, 1, 1, 0) def __eq__(self, other): return self.name == other def __ne__(self, other): return self.name != other def __lt__(self, other): return self.name < other def __le__(self, other): return self.name <= other def __gt__(self, other): return self.name > other def __ge__(self, other): return self.name >= other def __call__(self, protoVer): return api.protoModules[protoVer].OctetString( \(aqPySNMP example command responder\(aq ) class Uptime(object): name = (1, 3, 6, 1, 2, 1, 1, 3, 0) birthday = time.time() def __eq__(self, other): return self.name == other def __ne__(self, other): return self.name != other def __lt__(self, other): return self.name < other def __le__(self, other): return self.name <= other def __gt__(self, other): return self.name > other def __ge__(self, other): return self.name >= other def __call__(self, protoVer): return api.protoModules[protoVer].TimeTicks( (time.time() \- self.birthday) * 100 ) mibInstr = ( SysDescr(), Uptime() # sorted by object name ) mibInstrIdx = {} for mibVar in mibInstr: mibInstrIdx[mibVar.name] = mibVar def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): while wholeMsg: msgVer = api.decodeMessageVersion(wholeMsg) if msgVer in api.protoModules: pMod = api.protoModules[msgVer] else: print(\(aqUnsupported SNMP version %s\(aq % 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, \(aqgenErr\(aq) pMod.apiPDU.setVarBinds(rspPDU, varBinds) # Commit possible error indices to response PDU for f, i in pendingErrors: f(rspPDU, i) transportDispatcher.sendMessage( encoder.encode(rspMsg), transportDomain, transportAddress ) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openServerMode((\(aqlocalhost\(aq, 161)) ) # UDP/IPv6 transportDispatcher.registerTransport( udp6.domainName, udp6.Udp6SocketTransport().openServerMode((\(aq::1\(aq, 161)) ) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openServerMode(\(aq/tmp/snmp\-agent\(aq) # ) transportDispatcher.jobStarted(1) try: # Dispatcher will never finish as job#1 never reaches zero transportDispatcher.runDispatcher() except: transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Notification Originator .SS Transport tweaks .SS TRAP over multiple transports .sp The following script sends two SNMP TRAP notification using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv1 .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP and IPv6/UDP .IP \(bu 2 send TRAP notification .IP \(bu 2 to a Manager at demo.snmplabs.com:162 and [::1] .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .IP \(bu 2 include managed objects information: .IP \(bu 2 with default Uptime value .IP \(bu 2 with default Agent Address with \(aq127.0.0.1\(aq .IP \(bu 2 overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2 .UNINDENT .sp The following Net\-SNMP commands will produce similar SNMP notification: .nf $ snmptrap \-v1 \-c public udp:demo.snmplabs.com 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345 $ snmptrap \-v1 \-c public udp6:[::1] 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 0 12345 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import encoder from pysnmp.proto import api # Protocol version to use pMod = api.protoModules[api.protoVersion1] # pMod = api.protoModules[api.protoVersion2c] # Build PDU trapPDU = pMod.TrapPDU() pMod.apiTrapPDU.setDefaults(trapPDU) # Traps have quite different semantics across proto versions if pMod == api.protoModules[api.protoVersion1]: pMod.apiTrapPDU.setEnterprise(trapPDU, (1, 3, 6, 1, 1, 2, 3, 4, 1)) pMod.apiTrapPDU.setGenericTrap(trapPDU, \(aqcoldStart\(aq) # Build message trapMsg = pMod.Message() pMod.apiMessage.setDefaults(trapMsg) pMod.apiMessage.setCommunity(trapMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(trapMsg, trapPDU) transportDispatcher = AsyncoreDispatcher() # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp.domainName, (\(aqdemo.snmplabs.com\(aq, 162) ) # UDP/IPv6 transportDispatcher.registerTransport( udp6.domainName, udp6.Udp6SocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp6.domainName, (\(aq::1\(aq, 162) ) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openClientMode() # ) # transportDispatcher.sendMessage( # encoder.encode(trapMsg), unix.domainName, \(aq/tmp/snmp\-manager\(aq # ) # Dispatcher will finish as all scheduled messages are sent transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS INFORM over multiple transports .sp The following script sends SNMP INFORM notification using the following options: .INDENT 0.0 .IP \(bu 2 with SNMPv2c .IP \(bu 2 with community name \(aqpublic\(aq .IP \(bu 2 over IPv4/UDP and IPv6/UDP .IP \(bu 2 send INFORM notification .IP \(bu 2 to a Manager at demo.snmplabs.com:162 and [::1]:162 .IP \(bu 2 with TRAP ID \(aqcoldStart\(aq specified as an OID .UNINDENT .sp The following Net\-SNMP command will produce similar SNMP notification: .nf $ snmpinform \-v2c \-c public udp:demo.snmplabs.com 0 1.3.6.1.6.3.1.1.5.1 $ snmpinform \-v2c \-c public udp6:[::1] 0 1.3.6.1.6.3.1.1.5.1 .fi .sp .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from time import time from pysnmp.carrier.asynsock.dispatch import AsynsockDispatcher from pysnmp.carrier.asynsock.dgram import udp, udp6 from pyasn1.codec.ber import encoder, decoder from pysnmp.proto.api import v2c as pMod # Build PDU reqPDU = pMod.InformRequestPDU() pMod.apiTrapPDU.setDefaults(reqPDU) # Build message trapMsg = pMod.Message() pMod.apiMessage.setDefaults(trapMsg) pMod.apiMessage.setCommunity(trapMsg, \(aqpublic\(aq) pMod.apiMessage.setPDU(trapMsg, reqPDU) startedAt = time() def cbTimerFun(timeNow): if timeNow \- startedAt > 3: raise Exception(\(dqRequest timed out\(dq) # noinspection PyUnusedLocal,PyUnusedLocal def cbRecvFun(transportDispatcher, transportDomain, transportAddress, wholeMsg, reqPDU=reqPDU): while wholeMsg: rspMsg, wholeMsg = decoder.decode(wholeMsg, asn1Spec=pMod.Message()) rspPDU = pMod.apiMessage.getPDU(rspMsg) # Match response to request if pMod.apiPDU.getRequestID(reqPDU) == pMod.apiPDU.getRequestID(rspPDU): # Check for SNMP errors reported errorStatus = pMod.apiPDU.getErrorStatus(rspPDU) if errorStatus: print(errorStatus.prettyPrint()) else: print(\(aqINFORM message delivered, response var\-binds follow\(aq) for oid, val in pMod.apiPDU.getVarBinds(rspPDU): print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) transportDispatcher.jobFinished(1) return wholeMsg transportDispatcher = AsynsockDispatcher() transportDispatcher.registerRecvCbFun(cbRecvFun) transportDispatcher.registerTimerCbFun(cbTimerFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openClientMode() ) transportDispatcher.sendMessage( encoder.encode(trapMsg), udp.domainName, (\(aqdemo.snmplabs.com\(aq, 162) ) transportDispatcher.jobStarted(1) # UDP/IPv6 # transportDispatcher.registerTransport( # udp6.domainName, udp6.Udp6SocketTransport().openClientMode() # ) # transportDispatcher.sendMessage( # encoder.encode(trapMsg), udp6.domainName, (\(aq::1\(aq, 162) # ) # transportDispatcher.jobStarted(1) # Dispatcher will finish as all scheduled messages are sent transportDispatcher.runDispatcher() transportDispatcher.closeDispatcher() .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Notification Receiver .SS Transport tweaks .SS Listen for notifications at IPv4 & IPv6 interfaces .sp Receive SNMP TRAP messages with the following options: .INDENT 0.0 .IP \(bu 2 SNMPv1/SNMPv2c .IP \(bu 2 with SNMP community \(dqpublic\(dq .IP \(bu 2 over IPv4/UDP, listening at 127.0.0.1:162 .IP \(bu 2 over IPv6/UDP, listening at [::1]:162 .IP \(bu 2 print received data on stdout .UNINDENT .sp Either of the following Net\-SNMP commands will send notifications to this receiver: .nf $ snmptrap \-v1 \-c public 127.0.0.1 1.3.6.1.4.1.20408.4.1.1.2 127.0.0.1 1 1 123 1.3.6.1.2.1.1.1.0 s test $ snmptrap \-v2c \-c public udp6:[::1] 123 1.3.6.1.6.3.1.1.5.1 1.3.6.1.2.1.1.5.0 s test .fi .sp .sp Notification Receiver below uses two different transports for communication with Notification Originators \- UDP over IPv4 and UDP over IPv6. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher from pysnmp.carrier.asyncore.dgram import udp, udp6, unix from pyasn1.codec.ber import decoder from pysnmp.proto import api # noinspection PyUnusedLocal def cbFun(transportDispatcher, transportDomain, transportAddress, wholeMsg): while wholeMsg: msgVer = int(api.decodeMessageVersion(wholeMsg)) if msgVer in api.protoModules: pMod = api.protoModules[msgVer] else: print(\(aqUnsupported SNMP version %s\(aq % msgVer) return reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message(), ) print(\(aqNotification message from %s:%s: \(aq % ( transportDomain, transportAddress ) ) reqPDU = pMod.apiMessage.getPDU(reqMsg) if reqPDU.isSameTypeWith(pMod.TrapPDU()): if msgVer == api.protoVersion1: print(\(aqEnterprise: %s\(aq % (pMod.apiTrapPDU.getEnterprise(reqPDU).prettyPrint())) print(\(aqAgent Address: %s\(aq % (pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint())) print(\(aqGeneric Trap: %s\(aq % (pMod.apiTrapPDU.getGenericTrap(reqPDU).prettyPrint())) print(\(aqSpecific Trap: %s\(aq % (pMod.apiTrapPDU.getSpecificTrap(reqPDU).prettyPrint())) print(\(aqUptime: %s\(aq % (pMod.apiTrapPDU.getTimeStamp(reqPDU).prettyPrint())) varBinds = pMod.apiTrapPDU.getVarBinds(reqPDU) else: varBinds = pMod.apiPDU.getVarBinds(reqPDU) print(\(aqVar\-binds:\(aq) for oid, val in varBinds: print(\(aq%s = %s\(aq % (oid.prettyPrint(), val.prettyPrint())) return wholeMsg transportDispatcher = AsyncoreDispatcher() transportDispatcher.registerRecvCbFun(cbFun) # UDP/IPv4 transportDispatcher.registerTransport( udp.domainName, udp.UdpSocketTransport().openServerMode((\(aqlocalhost\(aq, 162)) ) # UDP/IPv6 transportDispatcher.registerTransport( udp6.domainName, udp6.Udp6SocketTransport().openServerMode((\(aq::1\(aq, 162)) ) ## Local domain socket # transportDispatcher.registerTransport( # unix.domainName, unix.UnixSocketTransport().openServerMode(\(aq/tmp/snmp\-manager\(aq) # ) transportDispatcher.jobStarted(1) try: # Dispatcher will never finish as job#1 never reaches zero transportDispatcher.runDispatcher() except: transportDispatcher.closeDispatcher() raise .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Low\-level MIB access .SS Manager side .SS PDU var\-binds to MIB objects .sp This script explains how Python application could turn SNMP PDU variable\-bindings into MIB objects or the other way around. .sp The code that configures MIB compiler is similar to what happens inside the pysnmp.hlapi API. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.smi import builder, view, compiler, rfc1902 # Assemble MIB browser mibBuilder = builder.MibBuilder() mibViewController = view.MibViewController(mibBuilder) compiler.addMibCompiler(mibBuilder, sources=[\(aqfile:///usr/share/snmp/mibs\(aq, \(aqhttp://mibs.snmplabs.com/asn1/@mib@\(aq]) # Pre\-load MIB modules we expect to work with mibBuilder.loadModules(\(aqSNMPv2\-MIB\(aq, \(aqSNMP\-COMMUNITY\-MIB\(aq) # This is what we can get in TRAP PDU varBinds = [ (\(aq1.3.6.1.2.1.1.3.0\(aq, 12345), (\(aq1.3.6.1.6.3.1.1.4.1.0\(aq, \(aq1.3.6.1.6.3.1.1.5.2\(aq), (\(aq1.3.6.1.6.3.18.1.3.0\(aq, \(aq0.0.0.0\(aq), (\(aq1.3.6.1.6.3.18.1.4.0\(aq, \(aq\(aq), (\(aq1.3.6.1.6.3.1.1.4.3.0\(aq, \(aq1.3.6.1.4.1.20408.4.1.1.2\(aq), (\(aq1.3.6.1.2.1.1.1.0\(aq, \(aqmy system\(aq) ] # Run var\-binds through MIB resolver # You may want to catch and ignore resolution errors here varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController) for x in varBinds] for varBind in varBinds: print(varBind.prettyPrint()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS MIB objects to PDU var\-binds .sp This script explains how Python application (typically pysnmp\-based SNMP Manager) could turn SNMP PDU variable\-bindings into MIB objects or the other way around. .sp The code below does not explicitly add MIB compiler \- that happens behind the scenes. Examples below try to demo different kinds of MIB objects to work with. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.smi import builder, view, rfc1902, error # MIB Builder manages pysnmp MIBs mibBuilder = builder.MibBuilder() # MIB View Controller implements various queries to loaded MIBs mibView = view.MibViewController(mibBuilder) # Obtain MIB object information by MIB object name mibVar = rfc1902.ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1) # Optionally attach PySMI MIB compiler to MIB Builder that would # create pysnmp MIBs on demand from ASN.1 sources downloaded from # a web site. try: mibVar.addAsn1MibSource(\(aqhttp://mibs.snmplabs.com/asn1/@mib@\(aq) except error.SmiError: print(\(aqWARNING: not using MIB compiler (PySMI not installed)\(aq) mibVar.resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by its [sequence] OID mibVar = rfc1902.ObjectIdentity(tuple(mibVar)).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by its [string] OID mibVar = rfc1902.ObjectIdentity(str(mibVar)).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by a mix of OID/label parts mibVar = rfc1902.ObjectIdentity((1, 3, 6, 1, 2, \(aqmib\-2\(aq, 1, \(aqsysDescr\(aq)).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB object information by a label mibVar = rfc1902.ObjectIdentity(\(aqiso.org.dod.internet.mgmt.mib\-2.system.sysDescr\(aq).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain the first MIB object in given MIB module mibVar = rfc1902.ObjectIdentity(\(aqSNMPv2\-MIB\(aq).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain the last MIB object in given MIB module mibVar = rfc1902.ObjectIdentity(\(aqSNMPv2\-MIB\(aq, last=True).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Another way to obtain the first (or last) symbol in MIB module mibVar = rfc1902.ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aq\(aq).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Obtain MIB symbol from whatever MIB it is defined at (MIB should be loaded) mibVar = rfc1902.ObjectIdentity(\(aq\(aq, \(aqsysDescr\(aq, 0).resolveWithMib(mibView) print(mibVar.prettyPrint(), tuple(mibVar), str(mibVar)) # Create an OID\-value pair (called variable\-binding in SNMP) varBind = rfc1902.ObjectType( rfc1902.ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysObjectID\(aq, 0), \(aq1.3.6.1\(aq ).resolveWithMib(mibView) print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint()) # Create just OID varBind = rfc1902.ObjectType( rfc1902.ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqsysObjectID\(aq, 0) ).resolveWithMib(mibView) print(varBind[0].prettyPrint(), varBind[1].__class__.__name__, varBind[1].prettyPrint()) # Create var\-binds from MIB notification object (without OBJECTS clause) varBinds = rfc1902.NotificationType( rfc1902.ObjectIdentity(\(aqSNMPv2\-MIB\(aq, \(aqcoldStart\(aq) ).resolveWithMib(mibView) print([\(aq%s = %s(%s)\(aq % (x[0].prettyPrint(), x[1].__class__.__name__, x[1].prettyPrint()) for x in varBinds]) # Create var\-binds from MIB notification object (with OBJECTS clause) varBinds = rfc1902.NotificationType( rfc1902.ObjectIdentity(\(aqIF\-MIB\(aq, \(aqlinkUp\(aq), instanceIndex=(1,), objects={(\(aqIF\-MIB\(aq, \(aqifOperStatus\(aq): \(aqdown\(aq} ).resolveWithMib(mibView) print(varBinds.prettyPrint()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS SNMP MIB browser .sp This script explains how Python application (typically SNMP Manager) could load SNMP MIB modules into memory and introspect Managed Objects defined in MIB. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.smi import builder, view, compiler, error # Create MIB loader/builder mibBuilder = builder.MibBuilder() # Optionally attach PySMI MIB compiler (if installed) #print(\(aqAttaching MIB compiler...\(aq), #compiler.addMibCompiler(mibBuilder, sources=[\(aq/usr/share/snmp/mibs\(aq]) #print(\(aqdone\(aq) # Optionally set an alternative path to compiled MIBs print(\(aqSetting MIB sources...\(aq) mibBuilder.addMibSources(builder.DirMibSource(\(aq/opt/pysnmp_mibs\(aq)) print(mibBuilder.getMibSources()) print(\(aqdone\(aq) print(\(aqLoading MIB modules...\(aq), mibBuilder.loadModules( \(aqSNMPv2\-MIB\(aq, \(aqSNMP\-FRAMEWORK\-MIB\(aq, \(aqSNMP\-COMMUNITY\-MIB\(aq, \(aqIP\-MIB\(aq ) print(\(aqdone\(aq) print(\(aqIndexing MIB objects...\(aq), mibView = view.MibViewController(mibBuilder) print(\(aqdone\(aq) print(\(aqMIB symbol name lookup by OID: \(aq), oid, label, suffix = mibView.getNodeName((1,3,6,1,2,1,1,1)) print(oid, label, suffix) print(\(aqMIB symbol name lookup by label: \(aq), oid, label, suffix = mibView.getNodeName((1,3,6,1,2,\(aqmib\-2\(aq,1,\(aqsysDescr\(aq)) print(oid, label, suffix) print(\(aqMIB symbol name lookup by symbol description: \(aq), oid, label, suffix = mibView.getNodeName((\(aqsysDescr\(aq,)) oid, label, suffix = mibView.getNodeName((\(aqsnmpEngineID\(aq,), \(aqSNMP\-FRAMEWORK\-MIB\(aq) print(oid, label, suffix) print(\(aqMIB object value pretty print: \(aq), mibNode, = mibBuilder.importSymbols(\(aqSNMP\-FRAMEWORK\-MIB\(aq, \(aqsnmpEngineID\(aq) print(mibNode.syntax.prettyPrint()) print(\(aqMIB symbol location lookup by name: \(aq), modName, symName, suffix = mibView.getNodeLocation((\(aqsnmpCommunityEntry\(aq,)) print(symName, modName) print(\(aqMIB node lookup by location: \(aq), rowNode, = mibBuilder.importSymbols(modName, symName) print(rowNode) print(\(aqConceptual table index value to oid conversion: \(aq), oid = rowNode.getInstIdFromIndices(\(aqrouter\(aq) print(oid) print(\(aqConceptual table index oid to value conversion: \(aq), print(rowNode.getIndicesFromInstId(oid)) print(\(aqMIB tree traversal\(aq) oid, label, suffix = mibView.getFirstNodeName() while 1: try: modName, nodeDesc, suffix = mibView.getNodeLocation(oid) print(\(aq%s::%s == %s\(aq % (modName, nodeDesc, oid)) oid, label, suffix = mibView.getNextNodeName(oid) except error.NoSuchObjectError: break print(\(aqModules traversal\(aq) modName = mibView.getFirstModuleName() while 1: if modName: print(modName) try: modName = mibView.getNextModuleName(modName) except error.SmiError: break .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Agent side .SS Implementing MIB objects .sp This script explains how SNMP Agent application could model real\-world data as Managed Objects defined in MIB. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 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( \(aqSNMPv2\-SMI\(aq, \(aqMibScalarInstance\(aq ) # Managed object specification sysLocation, = mibBuilder.importSymbols(\(aqSNMPv2\-MIB\(aq, \(aqsysLocation\(aq) # Custom Managed Object class MySysLocationInstance(MibScalarInstance): # noinspection PyUnusedLocal def readGet(self, name, *args): # Just return a custom value return name, self.syntax.clone(\(aqThe Leaky Cauldron\(aq) sysLocationInstance = MySysLocationInstance( sysLocation.name, (0,), sysLocation.syntax ) # Register Managed Object with a MIB tree mibBuilder.exportSymbols( # \(aq__\(aq prefixed MIB modules take precedence on indexing \(aq__MY\-LOCATION\-MIB\(aq, sysLocationInstance=sysLocationInstance ) if __name__ == \(aq__main__\(aq: # # This is what is done internally by Agent. # from pysnmp.smi import instrum, exval mibInstrum = instrum.MibInstrumController(mibBuilder) print(\(aqRemote manager read access to MIB instrumentation (table walk)\(aq) oid, val = (), None while 1: oid, val = mibInstrum.readNextVars(((oid, val),))[0] if exval.endOfMib.isSameTypeWith(val): break print(oid, val.prettyPrint()) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .SS Agent operations on MIB .sp This script explains how SNMP Agent application manipulates its MIB possibly triggered by SNMP Manager\(aqs commands. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # SNMP agent backend e.g. Agent access to Managed Objects from pysnmp.smi import builder, instrum, exval print(\(aqLoading MIB modules...\(aq), mibBuilder = builder.MibBuilder().loadModules( \(aqSNMPv2\-MIB\(aq, \(aqSNMP\-FRAMEWORK\-MIB\(aq, \(aqSNMP\-COMMUNITY\-MIB\(aq ) print(\(aqdone\(aq) print(\(aqBuilding MIB tree...\(aq), mibInstrum = instrum.MibInstrumController(mibBuilder) print(\(aqdone\(aq) print(\(aqBuilding table entry index from human\-friendly representation...\(aq), snmpCommunityEntry, = mibBuilder.importSymbols( \(aqSNMP\-COMMUNITY\-MIB\(aq, \(aqsnmpCommunityEntry\(aq ) instanceId = snmpCommunityEntry.getInstIdFromIndices(\(aqmy\-router\(aq) print(\(aqdone\(aq) print(\(aqCreate/update SNMP\-COMMUNITY\-MIB::snmpCommunityEntry table row: \(aq) varBinds = mibInstrum.writeVars( ((snmpCommunityEntry.name + (2,) + instanceId, \(aqmycomm\(aq), (snmpCommunityEntry.name + (3,) + instanceId, \(aqmynmsname\(aq), (snmpCommunityEntry.name + (7,) + instanceId, \(aqvolatile\(aq)) ) for oid, val in varBinds: print(\(aq%s = %s\(aq % (\(aq.\(aq.join([str(x) for x in oid]), not val.isValue and \(aqN/A\(aq or val.prettyPrint())) print(\(aqdone\(aq) print(\(aqRead whole MIB (table walk)\(aq) oid, val = (), None while True: oid, val = mibInstrum.readNextVars(((oid, val),))[0] if exval.endOfMib.isSameTypeWith(val): break print(\(aq%s = %s\(aq % (\(aq.\(aq.join([str(x) for x in oid]), not val.isValue and \(aqN/A\(aq or val.prettyPrint())) print(\(aqdone\(aq) print(\(aqUnloading MIB modules...\(aq), mibBuilder.unloadModules() print(\(aqdone\(aq) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp See also: \fI\%library reference\fP\&. .SS Using these examples .sp Before doing cut&paste of the code below into your Python interpreter, make sure to install pysnmp and its dependencies by running pip or easy_install: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # pip pysnmp .ft P .fi .UNINDENT .UNINDENT .sp There\(aqs a public, multilingual SNMP Command Responder and Notification Receiver configured at \fI\%demo.snmplabs.com\fP to let you run PySNMP examples scripts in a cut&paste fashion. If you wish to use your own SNMP Agent with these scripts, make sure to either configure your local snmpd and/or snmptrapd or use a valid address and SNMP credentials of your SNMP Agent in the examples to let them work. .sp Should you want to use a MIB to make SNMP operations more human\-friendly, you are welcome to search for it and possibly download one from our \fI\%public MIB repository\fP\&. Alternatively, you can configure PySNMP to fetch and cache required MIBs from there automatically. .sp If you find your PySNMP application behaving unexpectedly, try to enable a /more or less verbose/ built\-in PySNMP debugging by adding the following snippet of code at the beginning of your application: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp import debug # use specific flags or \(aqall\(aq for full debugging debug.setLogger(debug.Debug(\(aqdsp\(aq, \(aqmsgproc\(aq, \(aqsecmod\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp Then run your app and watch stderr. The Debug initializer enables debugging for a particular PySNMP subsystem, \(aqall\(aq enables full debugging. More specific flags are: .INDENT 0.0 .IP \(bu 2 io .IP \(bu 2 dsp .IP \(bu 2 msgproc .IP \(bu 2 secmod .IP \(bu 2 mibbuild .IP \(bu 2 mibview .IP \(bu 2 mibinstrum .IP \(bu 2 acl .IP \(bu 2 proxy .IP \(bu 2 app .UNINDENT .sp For more details on PySNMP programming model and interfaces, please refer to \fI\%library documentation\fP\&. .SH DOWNLOAD .sp Best way is usually to .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # pip install pysnmp .ft P .fi .UNINDENT .UNINDENT .sp If that does not work for you for some reason, you might need to read the following page. .SS Download PySNMP .sp The PySNMP software is provided under terms and conditions of BSD\-style license, and can be freely downloaded from \fI\%PyPI\fP or GitHub (\fI\%master branch\fP). .sp Besides official releases, it\(aqs advisable to try the cutting\-edge development code that could be taken from PySNMP \fI\%source code repository\fP\&. It may be less stable in regards to general operation and changes to public interfaces, but it\(aqs first to contain fixes to recently discovered bugs. .sp The best way to obtain PySNMP and dependencies is to run: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pip install pysnmp .ft P .fi .UNINDENT .UNINDENT .sp or .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ easy_install pysnmp .ft P .fi .UNINDENT .UNINDENT .sp In case you do not have the easy_install command on your system but still would like to use the on\-line package installation method, please install \fI\%setuptools\fP package by downloading and running \fI\%ez_setup.pz\fP bootstrap: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # wget https://bootstrap.pypa.io/ez_setup.py # python ez_setup.py .ft P .fi .UNINDENT .UNINDENT .sp In case you are installing PySNMP on an off\-line system, the following packages need to be downloaded and installed for PySNMP to become operational: .INDENT 0.0 .IP \(bu 2 \fI\%PyASN1\fP, used for handling ASN.1 objects .IP \(bu 2 \fI\%PySNMP\fP, SNMP engine implementation .UNINDENT .sp Optional, but recommended: .INDENT 0.0 .IP \(bu 2 \fI\%PyCryptodomex\fP, used by SNMPv3 crypto features .IP \(bu 2 \fI\%PySMI\fP for automatic MIB download and compilation. That helps visualizing more SNMP objects .IP \(bu 2 \fI\%Ply\fP, parser generator required by PySMI .UNINDENT .sp The installation procedure for all the above packages is as follows (on UNIX\-based systems): .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ tar zxf package\-X.X.X.tar.gz $ cd package\-X.X.X # python setup.py install # cd .. # rm \-rf package\-X.X.X .ft P .fi .UNINDENT .UNINDENT .sp In case of any issues, please open a \fI\%GitHub issue\fP so we could try to help out. .SH LICENSE .SS License .sp Copyright (c) 2005\-2019, Ilya Etingof <\fI\%etingof@gmail.com\fP> All rights reserved. .sp Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: .INDENT 0.0 .INDENT 3.5 .INDENT 0.0 .IP \(bu 2 Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. .IP \(bu 2 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. .UNINDENT .UNINDENT .UNINDENT .sp THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \(dqAS IS\(dq 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. .SH FAQ .SS FAQ .sp Here we have an ever\-growing list of frequently asked questions regarding PySNMP usage issues. If you got an issue that you think is worth noting here, please open a \fI\%GitHub issue\fP\&. .sp Keep in mind that some the answers below may not be universally applicable to any PySNMP revision. .SS Getting peer address information .INDENT 0.0 .IP Q. 3 How do I find out peer transport address or security information within my receiving app (CommandResponder or Notification Receiver)? .UNINDENT .INDENT 0.0 .IP A. 3 SNMP architecture forces you to distinguish communicating entities only on the basis of their community names (SNMPv1/v2c) or ContextEngineId/ContextName pair (SNMPv3). .sp In other words, if one SNMP Manager should anyhow differ from another, then they should use distinct community names or SNMP contexts. Transport information should never be used for the identification purposes, as in some cases it proves to be unreliable (cases include NAT device or a proxy in the middle, not to mention address spoofing). .sp As practice reveals, even perfect design does not always cope well with the imperfect world. So we had to pinch a logic hole from the scope of an SNMP app down to transport layer. Now with the getTransportInfo(stateReference) method call you could get peer transport information upon receiving its SNMP message. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Callback function for receiving notifications def cbFun(snmpEngine, stateReference, contextEngineId, contextName, varBinds, cbCtx): transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(stateReference) .ft P .fi .UNINDENT .UNINDENT .SS How to implement MIB at the Agent .INDENT 0.0 .IP Q. 3 How to instantiate static MIB table at my SNMP Agent? .UNINDENT .INDENT 0.0 .IP A. 3 You need to create MibScalarInstance class instances and register them with your Agent\(aqs SNMP engine (mibBuilder, more specifically). Here\(aqs an example code for a IP\-MIB table: .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # SNMP Agent (AKA CommandResponder) is built around SNMP engine object snmpEngine = engine.SnmpEngine() # Import table columns ( ipAddressAddrType, ipAddressAddr, ipAddressIfIndex, ipAddressType, ipAddressPrefix, ipAddressOrigin, ipAddressStatus, ipAddressCreated, ipAddressLastChanged, ipAddressRowStatus, ipAddressStorageType ) = snmpEngine.msgAndPduDsp.mibInstrumController \&.mibBuilder.importSymbols( \(aqIP\-MIB\(aq, \(aqipAddressAddrType\(aq, \(aqipAddressAddr\(aq, \(aqipAddressIfIndex\(aq, \(aqipAddressType\(aq, \(aqipAddressPrefix\(aq, \(aqipAddressOrigin\(aq, \(aqipAddressStatus\(aq, \(aqipAddressCreated\(aq, \(aqipAddressLastChanged\(aq, \(aqipAddressRowStatus\(aq, \(aqipAddressStorageType\(aq ) # Import MibScalarInstance MibScalarInstance, = snmpEngine.msgAndPduDsp.mibInstrumController. mibBuilder.importSymbols(\(aqSNMPv2\-SMI\(aq, \(aqMibScalarInstance\(aq) # Create table columns instances _ipAddressAddrType = MibScalarInstance( ipAddressAddrType.name, (1, 4, 1, 2, 3, 4), ipAddressAddrType.syntax.clone(1) ) _ipAddressAddr = MibScalarInstance( ipAddressAddr.name, (1, 4, 1, 2, 3, 4), ipAddressAddr.syntax.clone(\(aq1.2.3.4\(aq) ) _ipAddressIfIndex = MibScalarInstance( ipAddressIfIndex.name, (1, 4, 1, 2, 3, 4), ipAddressIfIndex.syntax.clone(1) ) _ipAddressType = MibScalarInstance( ipAddressType.name, (1, 4, 1, 2, 3, 4), ipAddressType.syntax.clone(1) ) _ipAddressPrefix = MibScalarInstance( ipAddressPrefix.name, (1, 4, 1, 2, 3, 4), ipAddressPrefix.syntax.clone((0,0)) ) _ipAddressOrigin = MibScalarInstance( ipAddressOrigin.name, (1, 4, 1, 2, 3, 4), ipAddressOrigin.syntax.clone(1) ) _ipAddressStatus = MibScalarInstance( ipAddressStatus.name, (1, 4, 1, 2, 3, 4), ipAddressStatus.syntax.clone(1) ) _ipAddressCreated = MibScalarInstance( ipAddressCreated.name, (1, 4, 1, 2, 3, 4), ipAddressCreated.syntax.clone(800) ) _ipAddressLastChanged = MibScalarInstance( ipAddressLastChanged.name, (1, 4, 1, 2, 3, 4), ipAddressLastChanged.syntax.clone(600) ) _ipAddressRowStatus = MibScalarInstance( ipAddressRowStatus.name, (1, 4, 1, 2, 3, 4), ipAddressRowStatus.syntax.clone(1) ) _ipAddressStorageType = MibScalarInstance( ipAddressStorageType.name, (1, 4, 1, 2, 3, 4), ipAddressStorageType.syntax ) # add anonymous column instances snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.exportSymbols( \(aq_IP\-MIB\(aq, _ipAddressAddrType, _ipAddressAddr, _ipAddressIfIndex, _ipAddressType, _ipAddressPrefix, _ipAddressOrigin, _ipAddressStatus, _ipAddressCreated, _ipAddressLastChanged, _ipAddressRowStatus, _ipAddressStorageType ) # Command responder code would follow... .ft P .fi .UNINDENT .UNINDENT .sp Keep in mind that the values of this table row will not change by themselves. They basically hold a snapshot of a data set so your application may have to update them somehow. For example, an app could periodically lookup particular MibScalarInstance by OID at mibBuilder and update its \(dqsyntax\(dq attribute with a new value. .sp There are other ways for building MIB tables that represent dynamic Managed Objects. .SS Ignored SNMP packets .INDENT 0.0 .IP Q. 3 Some network devices do not respond to PySNMP\-based management requests for particular OIDs. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pysnmpget \-v2c \-c public 10.0.0.33 1.3.6.1.2.1.2.2.1.10.3 SNMPv2\-SMI::mib\-2.2.2.1.10.3 = Counter32: 1519568842 $ snmpget.py \-v2c \-c public 10.0.0.33 1.3.6.1.2.1.2.2.1.10.4 requestTimedOut Meanwhile, tcpcump shows request\-response sequence: .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 13:33:30.161843 IP 10.0.0.33.snmp > 10.0.0.1.51094: GetResponse(31) interfaces.ifTable.ifEntry.ifInOctets.3=1532504859 13:33:30.161881 IP 10.0.0.33.snmp > 10.0.0.1.51094: GetResponse(31) interfaces.ifTable.ifEntry.ifInOctets.3=1532504859 In some cases, particularily when running v1arch PySNMP code, the following exception may be thrown on response processing: .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C Traceback (most recent call last): .... File \(dqbuild/bdist.linux\-i686/egg/pyasn1/type/base.py\(dq, line 64, in __init__ File \(dqbuild/bdist.linux\-i686/egg/pyasn1/type/base.py\(dq, line 32, in _verifySubtypeSpec File \(dqbuild/bdist.linux\-i686/egg/pyasn1/type/constraint.py\(dq, line 33, in __call__ pyasn1.type.error.ValueConstraintError: ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(0, 4294967295)) failed at: ValueRangeConstraint(0, 4294967295) failed at: \-1413698940 .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP A. 3 This appears to be a [widespread] bug in BER integer encoders. It usually gets noticed on Counter values as they are constrained to be positive while wrong encoding yelds them negative. .sp Here\(aqs broken encoding: .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> decoder.decode(\(aqA\ex04\exab\exbc\exaa\ex84\(aq, asn1Spec=rfc1155.Counter()) Traceback (most recent call last): \&... pyasn1.type.error.ValueConstraintError: ConstraintsIntersection(ConstraintsIntersection(), ValueRangeConstraint(0, 4294967295)) failed at: ValueRangeConstraint(0, 4294967295) failed at: \-1413698940 .ft P .fi .UNINDENT .UNINDENT .sp And here\(aqs a good one: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> decoder.decode(\(aqA\ex05\ex00\exab\exbc\exaa\ex84\(aq, >>> asn1Spec=rfc1155.Counter()) (Counter(\(aq2881268356\(aq), \(aq\(aq) Notice the third octet \-\- positive values must have its highest bit set to zero. Here\(aqs an example hack that converts negated values into their positive complimentaries for Counter type. .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.proto import rfc1155, rfc1902, api from pyasn1.codec.ber import encoder, decoder # \-\-\- hack Counter type def counterCloneHack(self, *args): if args and args[0] < 0: args = (0xffffffff+args[0]\-1,) + args[1:] return self.__class__(*args) rfc1155.Counter.clone = counterCloneHack rfc1902.Counter32.clone = counterCloneHack Execute this hack before any SNMP message processing occures in your app. The bad news is that if this BER encoding bug also affects Integer values, in that case it is theoretically impossible to fix because, unlike Counter, Integer values may legally be negative so they could not unconditionally be converted into positives. Therefore the best solutoin would be to get vendors fixing their BER encoders. .ft P .fi .UNINDENT .UNINDENT .SS Listening on multiple network interfaces .INDENT 0.0 .IP Q. 3 I need my receiving entity (CommandResponder or Notification Receiver) to listen for SNMP messages on multiple network interfaces. How do I do that with pysnmp? .UNINDENT .INDENT 0.0 .IP A. 3 Simply register multiple network transports with your SNMP engine. Each transport would be bound to an individual local transport endpoint (for instance, IP address & UDP port pair). .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C # Security setup would follow ... # Setup first transport endpoint config.addSocketTransport( snmpEngine, udp.domainName + (1,), udp.UdpSocketTransport().openServerMode((\(aq127.0.0.1\(aq, 162)) ) # Setup second transport endpoint config.addSocketTransport( snmpEngine, udp.domainName + (2,), udp.UdpSocketTransport().openServerMode((\(aq192.168.1.1\(aq, 162)) ) # Receiver callback function implementation and Dispatcher invocation # would follow ... Notice extended transport domain specification (udp.domainName) in the code above. There we register each transport endpoint under distinct OID, however always within the canonical transport domain OID. .ft P .fi .UNINDENT .UNINDENT .SS Garbaged SNMP values (apps) .INDENT 0.0 .IP Q. 3 When my PySNMP application prints out fetched values, some of them come out as a garbage on my screan. Here\(aqs my code: .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for varBind in varBinds: print(\(aq = \(aq.join([ str(x) for x in varBind ]) and the result is: .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C 1.3.6.1.4.1.161.19.3.2.1.63.0 = 50000 1.3.6.1.4.1.161.19.3.2.1.4.0 = \(aq\ex01\ex02\ex03\ex04\(aq The IpAddress type seems to be the only one with this problem. .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP A. 3 Always use prettyPrint() method for all pyasn1\-based objects \-\- it automatically converts ASN1 types to human\-friendly form. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C > > > from pysnmp.proto import rfc1902 > > > a = rfc1902.IpAddress(\(aq1.2.3.4\(aq) > > > str(a) \(aq\ex01\ex02\ex03\ex04\(aq > > > a IpAddress(\(aq1.2.3.4\(aq) > > > a.prettyPrint() \(aq1.2.3.4\(aq > > > rfc1902.IpAddress.prettyPrint(a) \(aq1.2.3.4\(aq .ft P .fi .UNINDENT .UNINDENT .sp See \fI\%pyasn1 docs\fP for more information on pyasn1 data model. .SS Garbaged SNMP values (tools) .INDENT 0.0 .IP Q. 3 When fetching data with snmp*.py command\-line tools, some values do not print out nicely: .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ snmpget.py \-v2c \-c public 127.0.0.1 .1.3.6.1.4.1.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 SNMPv2\-SMI::enterprises.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 = OctetString: ˇČ where Net\-SNMP gives nicely formatted human\-readable string: .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ snmpget \-v2c \-c public 127.0.0.1 .1.3.6.1.4.1.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 SNMPv2\-SMI::enterprises.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 = Hex\-STRING: 00 17 B7 22 08 C8 What can be done to PySNMP to make it returning HEX data in human\-readable? .ft P .fi .UNINDENT .UNINDENT .INDENT 0.0 .IP A. 3 The difference is that Net\-SNMP prints values into hex by\-default, whereas pysnmp does not do that. You can force snmpget.py to work similarily with the \-OT command line parameter. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ snmpget.py \-OT \-v2c \-c public 127.0.0.1 .1.3.6.1.4.1.14988.1.1.1.2.1.1.0.23. 183.34.8.200.3 SNMPv2\-SMI::enterprises.14988.1.1.1.2.1.1.0.23.183.34.8.200.3 = OctetString: 00 17 b7 22 08 c8 .ft P .fi .UNINDENT .UNINDENT .sp Another matter is MIB lookup \- when snmp*.py tool can use a MIB to figure out what are the display conventions for particular value type, it will reformat the value in a human\-readable form. .sp To let MIB lookup work, please pass appropriate MIB name to snmp*.py tool through command line: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ snmpwalk.py \-m IP\-MIB,IF\-MIB \-v2c \-c public 127.0.0.1 .1.3.6.1.4.1 .ft P .fi .UNINDENT .UNINDENT .SS Dealing with the \(dqOID not increasing\(dq error .INDENT 0.0 .IP Q. 3 I\(aqm walking a particular Agent with the \fInextCmd()\fP or \fIbulkCmd()\fP functions. It works for some OIDs, but invariably fails at certain OID with the \fIOID not increasing\fP error. What does it mean and how do I fix that? .UNINDENT .INDENT 0.0 .IP A. 3 The Agent you are talking to seems to be broken. The \fIOID not increasing\fP message means that in the course of fetching OIDs from the Agent, Manager receives an OID that is not greater than those passed in request. Due to the nature of GETNEXT/GETBULK algorithm, passing the same or lesser OID to Manager would result in fetching the same set of OIDs over and over again effectively creating an infinite loop between Manager and Agent so they may never reach the end of MIB. To prevent this the Manager tries to intervene and prevent such loop from happening. .sp If you have to work with a broken Agent and can terminate the GETNEXT/GETBULK command at some point, you can pass the \fIignoreNonIncreasingOid=True\fP keyword parameter to the \fInextCmd()\fP or \fIbulkCmd()\fP to disable OID verification at the Manager side. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aq1.3.6\(aq)), ignoreNonIncreasingOid=True): if errorIndication: print(errorIndication) break elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) break else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind]) .ft P .fi .UNINDENT .UNINDENT .SS How to pass MIB to the Manager .INDENT 0.0 .IP Q. 3 How to make use of random MIBs at my Manager application? .UNINDENT .INDENT 0.0 .IP A. 3 Starting from PySNMP 4.3.x, plain\-text (ASN.1) MIBs can be automatically parsed into PySNMP form by the \fI\%PySMI\fP tool. PySNMP will call PySMI automatically, parsed PySNMP MIB will be cached in $HOME/.pysnmp/mibs/ (default location). .sp MIB compiler could be configured to search for plain\-text MIBs at multiple local and remote locations. As for remote MIB repos, you are welcome to use our collection of ASN.1 MIB files at \fI\%http://mibs.snmplabs.com/asn1/\fP as shown below. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( getCmd(SnmpEngine(), CommunityData(\(aqpublic\(aq), UdpTransportTarget((\(aqdemo.snmplabs.com\(aq, 161)), ContextData(), ObjectType(ObjectIdentity(\(aqIF\-MIB\(aq, \(aqifInOctets\(aq, 1).addAsn1MibSource(\(aqfile:///usr/share/snmp\(aq, \(aqhttp://mibs.snmplabs.com/asn1/@mib@\(aq))) ) if errorIndication: print(errorIndication) elif errorStatus: print(\(aq%s at %s\(aq % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) \- 1][0] or \(aq?\(aq)) else: for varBind in varBinds: print(\(aq = \(aq.join([x.prettyPrint() for x in varBind])) .ft P .fi .UNINDENT .UNINDENT .sp \fBDownload\fP script. .sp Alternatively, you can invoke the \fI\%mibdump.py\fP (shipped with PySMI) by hand and this way compile plain\-text MIB into PySNMP format. Once the compiled MIBs are stored in a directory, add the directory to your MibBuilder\(aqs MibSources. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C builder = engine.getMibBuilder() # Make ./mibs available to all OIDs that are created # e.g. with \(dqMIB\-NAME\-MIB::identifier\(dq builder.addMibSources(builder_module.DirMibSource( os.path.join( HERE, \(aqmibs\(aq) )) .ft P .fi .UNINDENT .UNINDENT .SS My py2exe app can\(aqt find MIBs .INDENT 0.0 .IP Q. 3 I packed my pysnmp\-based application with py2exe. When I run my app, it throws a traceback like this: .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C .ft P .fi .UNINDENT .UNINDENT .sp File \(dqpysnmpentityrfc3413onelinercmdgen.pyc\(dq, line 116, in __init__ File \(dqpysnmpentityengine.pyc\(dq, line 16, in __init__ File \(dqpysnmpprotorfc3412.pyc\(dq, line 16, in __init__ File \(dqpysnmpsmibuilder.pyc\(dq, line 143, in __init__ File \(dqpysnmpsmibuilder.pyc\(dq, line 35, in init File \(dqpysnmpsmibuilder.pyc\(dq, line 80, in _init ImportError: No module named mibs.instances .INDENT 0.0 .INDENT 3.5 PySNMP claims itself to be py2exe\-friendly. How to make it working? .UNINDENT .UNINDENT .INDENT 0.0 .IP A. 3 You have to list pysnmp MIB directories explicitly at your app\(aqs setup.py so that py2exe would include them into the binary. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from distutils.core import setup import sys options = {} if \(dqpy2exe\(dq in sys.argv: import py2exe # fix executables options[\(aqconsole\(aq] = [\(aqmyapp.py\(aq] # add files not found my modulefinder options[\(aqoptions\(aq] = { \(aqpy2exe\(aq: { \(aqincludes\(aq: [ \(aqpysnmp.smi.mibs.*\(aq, \(aqpysnmp.smi.mibs.instances.*\(aq ] } } setup(**options) .ft P .fi .UNINDENT .UNINDENT .SS Resolve response values at MIB .INDENT 0.0 .IP Q. 3 My CommandGenerator app reports OIDs and values in form of PyASN1 objects. How do I convert them into human\-readable, symbolic names and values? .UNINDENT .INDENT 0.0 .IP A. 3 The most easy to use interface to MIB lookup feature is supported by PySNMP 4.2.3 and later. Just pass the .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C lookupNames=True, lookupValues=True .ft P .fi .UNINDENT .UNINDENT .sp parameters to getCmd(), setCmd(), nextCmd(), bulkCmd() methods of oneliner CommandGenerator. Then the OIDs in response variable\-binding list will get replaced by similarily looking MibVariable instances, their prettyPrint() methods return MIB symbols instead of OIDs. .sp Response values will still be PyASN1 objects but some may be replaced by TEXTUAL\-CONVENTION decorators what make their prettyPrint() methods returning even more human\-friendly output. .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C >>> from pysnmp.entity.rfc3413.oneliner import cmdgen >>> >>> cmdGen = cmdgen.CommandGenerator() >>> >>> errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( \&... cmdgen.CommunityData(\(aqpublic\(aq), \&... cmdgen.UdpTransportTarget((\(aqlocalhost\(aq, 161)), \&... \(aq1.3.6.1.2.1.1.1.0\(aq, \&... lookupNames=True, lookupValues=True \&... ) >>> >>> name, value = varBinds[0] >>> name MibVariable(ObjectName(1.3.6.1.2.1.1.1.0)) >>> value DisplayString(\(aqLinux saturn 2.6.38.1 Sat Apr 9 23:39:07 CDT 2012 i686\(aq) >>> name.prettyPrint() \(aqSNMPv2\-MIB::sysDescr.\(dq0\(dq\(aq >>> value.prettyPrint() \(aqLinux cray 2.6.37.6\-smp #2 SMP Sat Apr 9 23:39:07 CDT 2011 i686\(aq >>> .ft P .fi .UNINDENT .UNINDENT .sp If you are using older PySNMP versions it\(aqs strongly recommended to upgrade to the latest one. .SS SNMP data constraints verification error .INDENT 0.0 .IP Q. 3 Will PySNMP Manager verify the values it sends to and receives from a distant Agent against local MIB constraints? .UNINDENT .INDENT 0.0 .IP A. 3 Yes, it can do that. The Manager will verify the values you pass to SET request against a MIB if: .sp The values are not already PyASN1 objects but some basic Python types (like integer or string). You tell PySNMP engine to load appropriate MIB where it could lookup the constraints (via the use of MibVariable) So, the following code fragment makes PySNMP engine loading SNMPv2\-MIB and verifying that the \(aqnew system name\(aq value satisfies sysName constraints (if any). .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd( cmdgen.CommunityData(\(aqpublic\(aq), cmdgen.UdpTransportTarget((\(aqlocalhost\(aq, 161)), ( cmdgen.MibVariable(\(aqSNMPv2\-MIB\(aq, \(aqsysName\(aq, 0), \(aqnew system name\(aq ) ) .ft P .fi .UNINDENT .UNINDENT .sp To verify the response values, you should pass at least lookupValues flag to CommandGenerator *cmd() method you use. In the following example PySNMP will make sure that Agent\-supplied value for SNMPv2\-MIB::sysName Managed Object satisfies MIB constraints (if any). .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(\(aqpublic\(aq), cmdgen.UdpTransportTarget((\(aqlocalhost\(aq, 161)), cmdgen.MibVariable(\(aqSNMPv2\-MIB\(aq, \(aqsysName\(aq, 0), lookupValues=True ) .ft P .fi .UNINDENT .UNINDENT .sp In case of constraint violation, a PySNMP exception will be raised. .SS Walking whole MIB .INDENT 0.0 .IP Q. 3 The nextCmd() and bulkCmd() methods of CommandGenerator app (oneliner version) stop working once returned OIDs went out of scope of request OIDs. .sp In other words, if I request 1.3.6.1, I would get everything under the 1.3.6.1 prefix, but not 1.3.6.2. Is there any way to make it walking the whole MIB? .UNINDENT .INDENT 0.0 .IP A. 3 Yes, just pass the lexicographicMode=True parameter to CommandGenerator nextCmd() and bulkCmd() methods (introduced in PySNMP 4.2.3+) or set CommandGenerator.lexicographicMode=True option before calling nextCmd() and bulkCmd() methods. .UNINDENT .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd( ...., ...., ...., lexicographicMode=True ) .ft P .fi .UNINDENT .UNINDENT .SH FURTHER DEVELOPMENT .sp We fanatically document all fixes, changes and new features in changelog. There you could also download the latest unreleased pysnmp tarball containing the latest fixes and improvements. .SS Changelog .SS Revision 4.4.12, released 2019\-09\-24 .INDENT 0.0 .IP \(bu 2 Fixed broken SNMPv3 \fImsgFlag\fP initialization on authoritative SNMP engine ID discovery. This bug causes secure communication with peer SNMP engines to stall at SNMP engine ID discovery procedure. .UNINDENT .SS Revision 4.4.11, released 2019\-08\-10 .INDENT 0.0 .IP \(bu 2 Added SNMPv3 USM master and localized keys support to LCD configuration .IP \(bu 2 Improved initial and runtime USM debugging .IP \(bu 2 Fixed a bug in USM configuration which did not allow the same user names to be added under different security names .UNINDENT .SS Revision 4.4.10, released 2019\-07\-29 .INDENT 0.0 .IP \(bu 2 Reworked VACM access control function. Most important changes include: .INDENT 2.0 .IP \(bu 2 Added subtree match negation support (vacmViewTreeFamilyType) .IP \(bu 2 Added subtree family mask support (vacmViewTreeFamilyMask) .IP \(bu 2 Added prefix content name matching support (vacmAccessContextMatch) .IP \(bu 2 Added key VACM tables caching for better \fIisAccessAllowed\fP lookup performance .UNINDENT .sp One potential incompatibility may be caused by the \fIaddContext()\fP call which now needs to be made explicitly during low\-level VACM configuration rather than be a side effect of \fIaddVacmAccess()\fP call. .IP \(bu 2 Rebased MIB importing code onto \fIimportlib\fP because \fIimp\fP is long deprecated .IP \(bu 2 Received MIB objects resolution made more forgiving to errors, added optional \fIignoreErrors\fP parameter to \fIObjectType.resolveWithMib()\fP to control that behaviour. .IP \(bu 2 Fixed asyncore main loop to respect non\-default timer resolution .IP \(bu 2 Fixed \fI\&.setTimerResolution()\fP behaviour of abstract main loop dispatcher to update call intervals of the existing periodic dispatcher jobs .IP \(bu 2 Fixed \fIvar\-bindings\fP initialization to prevent pyasn1 encoder failures with newer pyasn1 versions where \fISequenceOf\fP type looses its default initializer. .IP \(bu 2 Fixed crash on uninitialized component serialization left out in SNMP v1 TRAP PDU to SNMPv2/3 TRAP PDU proxy translation routine. .UNINDENT .SS Revision 4.4.9, released 2019\-02\-09 .INDENT 0.0 .IP \(bu 2 Made MIB loader ignoring file and directory access errors .IP \(bu 2 Added missing SNMP PDU error classes and their handling in Command Responder .IP \(bu 2 Fixed crash on MIB load failure in case of directory access error .IP \(bu 2 Fixed socket transparency option (IPV6_TRANSPARENT) to make IPv6 transparent operation functional .UNINDENT .SS Revision 4.4.8, released 2018\-12\-30 .INDENT 0.0 .IP \(bu 2 Fixed Pythonized MIB load (in the source form) \- made sure to turn it into a code object prior to its execution .UNINDENT .SS Revision 4.4.7, released 2018\-12\-29 .INDENT 0.0 .IP \(bu 2 Copyright notice extended to the year 2019 .IP \(bu 2 Exposed ASN.1 \fINull\fP type through \fIrfc1902\fP module for convenience. .IP \(bu 2 Use \fIcompile()\fP before \fIexec\fP\(aqing MIB modules to attach filename to the stack frames (ultimately shown in traceback/debugger) .IP \(bu 2 Fixed hlapi/v3arch transport target caching to ensure transport targets are different even if just timeout/retries options differ .IP \(bu 2 Fixed hlapi LCD configurator to include \fIcontextName\fP\&. Prior to this fix sending SNMPv3 TRAP with non\-default \fIcontextName\fP would fail. .IP \(bu 2 Fixed possible duplicate key occurrence in the \fIOrderedDict\fP following a race condition .IP \(bu 2 Fixed undefined name references in \fIinet_pton\fP/\fIinet_ntop\fP substitute routines for IPv6 in \fITRANSPORT\-ADDRESS\-MIB.py\fP .UNINDENT .SS Revision 4.4.6, released 2018\-09\-13 .INDENT 0.0 .IP \(bu 2 Improved package build and dependency tracking .IP \(bu 2 Fixed missing LICENSE from the tarball distribution .IP \(bu 2 Fixed \fICommandGeneratorLcdConfigurator.unconfigure()\fP to fully clean up internal caches, otherwise repetitive attempts to configure the target would fail. .IP \(bu 2 Fix to tolerate possible duplicate enumerations in \fIBits\fP and \fIInteger\fP SMI types. .IP \(bu 2 Fix to tolerate non\-initialised entries in SNMP community table. Once a bad entry sneaked into the SNMP community table, all the subsequent SNMP v1/v2c operations failed. The fix ignores incomplete SNMP community table entries in the course of building indices. .UNINDENT .SS Revision 4.4.5, released 2018\-08\-05 .INDENT 0.0 .IP \(bu 2 Added PySnmpError.cause attribute holding parent exception tuple .IP \(bu 2 Fixed broken InetAddressType rendering caused by a pyasn1 regression .IP \(bu 2 Fixed typo in RFC1158 module .IP \(bu 2 Fixed possible infinite loop in GETBULK response PDU builder .IP \(bu 2 Fixed memory leak in the \fIconfig.delContext()\fP VACM management harness .IP \(bu 2 Fixed \fIBits\fP class initialization when enumeration values are given .IP \(bu 2 Fixed crash caused by incoming SNMPv3 message requesting SNMPv1/v2c security model .IP \(bu 2 Fixed out\-of\-scope OIDs leaking at the end of SNMP table at hlapi \fInextCmd\fP and \fIbulkCmd\fP calls when \fIlexicographicMode = False\fP .UNINDENT .SS Revision 4.4.4, released 2018\-01\-03 .INDENT 0.0 .IP \(bu 2 Copyright notice extended to the year 2018 .IP \(bu 2 Fixed short local key expansion at 3DES key localization implementation. .UNINDENT .SS Revision 4.4.3, released 2017\-12\-22 .INDENT 0.0 .IP \(bu 2 Migrated references from SourceForge .IP \(bu 2 Added missing SHA2 support for Blumenthal key localization .IP \(bu 2 Fixed named bits handling at rfc1902.Bits .IP \(bu 2 Fixed missing SmiError exception class at pysnmp.proto.rfc1155 .IP \(bu 2 Fixed SNMP v1\->v2c PDU proxy \-\- error\-status & error\-index fields from v1 PDU get copied over to v2c PDU in addition to the exception sentinels being set .UNINDENT .SS Revision 4.4.2, released 2017\-11\-11 .INDENT 0.0 .IP \(bu 2 The pysnmp version being used gets exposed to the MIB modules via the \fIMibBuilder\fP instance .IP \(bu 2 The .setObjects() method of the SMI types now accepts \fIappend=False\fP parameter to let the caller adding more than 255 elements over the course of multiple calls .IP \(bu 2 Added support for some more missing fields of SMIv2 MACRO types .IP \(bu 2 Example scripts rearranged in a way that IPv6 requirement is clearly encoded in the script\(aqs name .IP \(bu 2 Fixed SNMPv2\-SMI.NotificationType to expose .set/getReference() instead of .set/getRevision() which should not be there in the first place .IP \(bu 2 Fixed non\-implied\-OID encoding in SNMP table indices .IP \(bu 2 Fixed inconsistent SNMPv3 discovery and retrying algorithm .UNINDENT .SS Revision 4.4.1, released 2017\-10\-23 .INDENT 0.0 .IP \(bu 2 HMAC\-SHA\-2 Authentication Protocols support added (RFC\-7860) .IP \(bu 2 The pycryptodome dependency replaced with pycryptodomex as it is recommended by the upstream to avoid unwanted interference with PyCrypto package should it also be installed .IP \(bu 2 Sphinx theme changed to Alabaster in the documentation .IP \(bu 2 Minor adjustments towards pyasn1 0.4.x compatibility .IP \(bu 2 Fixed ObjectIdentifier\-into\-ObjectIdentity casting at rfc1902.ObjectType MIB resolution harness .IP \(bu 2 Fixed NetworkAddress object handling in SNMP table indices .IP \(bu 2 Fixed MIB lookup by module:object.indices MIB object with InetAddressIPv{4,6} objects being in the index .IP \(bu 2 Fixed non\-translated PDU being retries at CommandGenerator what leads to wrong PDU version being sent and even a crash on incompatible PDU/SNMP message combination .UNINDENT .SS Revision 4.3.10, released 2017\-10\-06 .INDENT 0.0 .IP \(bu 2 Refactored partial SNMP message decoding to make it less dependent on unpublished pyasn1 API features. .IP \(bu 2 Fix to MibTableRow.setFromName() to keep the input parameter type when it propagates to the return value. Before this fix ObjectIdentity.prettyPrint() may crash when rendering malformed SNMP table indices. .IP \(bu 2 Fixed NotificationReceiver to include SNMPv1 TRAP Message community string into SNMPv2c/v3 TRAP PDU .IP \(bu 2 Fixed multiple bugs in SNMP table indices rendering, especially the InetAddressIPv6 type which was severely broken. .IP \(bu 2 Fixed crashing Bits.prettyPrint() implementation .IP \(bu 2 Fixed crashing Bits.clone()/subtype() implementation .IP \(bu 2 Fixed leaking exceptions bubbling up from the asyncio and Twisted adapters .UNINDENT .SS Revision 4.3.9, released 2017\-07\-26 .INDENT 0.0 .IP \(bu 2 Deprecated UsmUserData initializaton parameters removed .IP \(bu 2 Adapted to pyasn1 API changes introduced by release 0.3.1 .IP \(bu 2 Fix to a crash happening on inbound SNMP message having non\-initialized fields .IP \(bu 2 Fix to (persistent SNMP engine ID) file writing on Windows .UNINDENT .SS Revision 4.3.8, released 2017\-06\-15 .INDENT 0.0 .IP \(bu 2 Security fix to the bug introduced in 4.3.6: msgAuthoritativeEngineTime stopped changing over time and was returning the same timestamp (process start time). This fix makes it growing as it should. .UNINDENT .SS Revision 4.3.7, released 2017\-05\-29 .INDENT 0.0 .IP \(bu 2 Fixed import error in legacy NotificationOriginator implementation .UNINDENT .SS Revision 4.3.6, released 2017\-05\-28 .INDENT 0.0 .IP \(bu 2 More instrumentation hooks added addressing security failures auditing needs. .IP \(bu 2 SNMP table indices correlation implemented within SMI framework. The opaque InetAddress type implemented. INET\-ADDRESS\-MIB included into the distribution. .IP \(bu 2 SNMP table indices resolution logic made more robust against malformed indices. .IP \(bu 2 Fixes to \fIlexicographicMode\fP option documentation to make it unambiguous. .IP \(bu 2 The \fIErrorIndication\fP object is now derived from \fIException\fP so that it could be raised in exceptions. .IP \(bu 2 The \fIerrorIndication\fP values produced by various parts of SNMP engine unified to be \fIErrorIndication\fP instances. This fixes an issue with Twisted. .IP \(bu 2 Embedded MIB modules rebuilt with the latest pysmi adding previously missing attributes like \fIstatus\fP, \fIdescription\fP etc. .IP \(bu 2 Fixed potential SNMP engine crash on handling incoming message at unsupported security level .UNINDENT .SS Revision 4.3.5, released 2017\-03\-24 .INDENT 0.0 .IP \(bu 2 The getNext() and getBulk() calls of Twisted interface. now support ignoreNonIncreasingOid option. .IP \(bu 2 TextualConvention is now a new\-style class. .IP \(bu 2 Fix to accidentally reset error\-status when building confirmed class SNMPv1 PDU. .IP \(bu 2 Fix to possible infinite recursion in TextualConvention.prettyIn(). .IP \(bu 2 Fixed crash when attempting to report unsupported request/notification PDU back to sender. .UNINDENT .SS Revision 4.3.4, released 2017\-03\-01 .INDENT 0.0 .IP \(bu 2 Fix to low\-level SNMP API example to accommodate changed pyasn1 SEQUENCE supporting iterator protocol. .IP \(bu 2 The pyasn1 version dependency bumped (0.2.3), SEQUENCE/SEQUENCE OF API calls adjusted to accommodate changed pyasn1 API (in part of .setComponentBy*() kw flags). .IP \(bu 2 Fixed crash on SNMP engine\(aqs invalid message counter increment. .UNINDENT .SS Revision 4.3.3, released 2017\-02\-04 .INDENT 0.0 .IP \(bu 2 Switched from now unmaintained PyCrypto to PyCryptodome. .IP \(bu 2 Switched to new\-style classes. .IP \(bu 2 NotificationType now allows additional var\-binds specified as MIB objects. A side effect of this change is that additional var\-binds can only be added prior to .resolveMibObjects() is run. .IP \(bu 2 Non\-standard (but apparently used by many vendors) Reeder AES192/256 key localization algorithm implemented and set as default for usmAesCfb192Protocol and usmAesCfb256Protocol identifiers. Original and more standard implementation can still be used with the usmAesBlumenthalCfb192Protocol and usmAesBlumenthalCfb192Protocol IDs respectively. .IP \(bu 2 TextualConvention.prettyOut() improved to produce prettier and more SMI\-compliant output. .IP \(bu 2 TextualConvention.prettyIn() implemented to handle DISPLAY\-HINT based value parsing. .IP \(bu 2 Fix to NotificationType to make additional var\-binds overriding MIB objects implicitly included through NOTIFICATION\-TYPE OBJECTS. .IP \(bu 2 Fix to SNMP engine boots counter persistence on Python 3. .IP \(bu 2 Fix to Pythonized MIBs loading when only .pyc files are present (e.g. py2exe/cx_freeze environments). .IP \(bu 2 Fix broken 3DES key localization and encryption procedures. .IP \(bu 2 Updated IP address for demo.snmplabs.com in examples. .IP \(bu 2 Missing index added to bundled RFC1213::atEntry MIB table. .IP \(bu 2 Twisted integration made Python3 compatible. .IP \(bu 2 Accommodated ASN.1 SEQUENCE iteration rules change in upcoming pyasn1 version. .IP \(bu 2 Author\(aqs email changed, copyright extended to 2017. .UNINDENT .SS Revision 4.3.2, released 2016\-02\-12 .INDENT 0.0 .IP \(bu 2 Copyright notice added to non\-trivial source code files. .IP \(bu 2 SNMP table row consistency check added. This change may break valid SNMP SET operations on tables if RowStatus column is not passed at the very end of var\-binds. .IP \(bu 2 All SNMP counters now incremented via \(aq+= 1\(aq rather than \(aqx = x + 1\(aq to simplify their tracking by third\-party code. .IP \(bu 2 Notification originator examples re\-pointed to Notification Receiver at demo.snmplabs.com. .IP \(bu 2 Two more execution observer points added: rfc2576.processIncomingMsg and rfc3414.processIncomingMsg to give an insignt on security modules internals. .IP \(bu 2 TEXTUAL\-CONVENTION\(aqs DISPLAY\-HINT text formatting reworked for better performance and encoding accurancy of \(aqa\(aq and \(aqt\(aq formats. .IP \(bu 2 WARNING: security fix to USM \- extra user entry clone removed on incoming message processing. It made USM accepting SNMPv3 TRAPs from unknown SNMP engine IDs. .IP \(bu 2 Fix to snmpInvalidMsgs and snmpUnknownSecurityModels MIB symbols import at SNMPv3 MP model. .IP \(bu 2 Fix to NotificationOriginator to cope with unspecified user callable. .IP \(bu 2 Fix to OctetString.prettyOut() to pretty\-print Python 3 bytes without \(aqb\(aq qualifier. .IP \(bu 2 Fix to better pysmi import errors handling. .IP \(bu 2 Fix to missing next() in Python 2.5 at pysnmp.hlapi .UNINDENT .SS Revision 4.3.1, released 2015\-11\-12 .INDENT 0.0 .IP \(bu 2 Added recursive resolution of ObjectIdentifier values at ObjectType by converting it to ObjectIdentity. .IP \(bu 2 A bunch of convenience shortcuts to rfc1902.ObjectIdentity added from rfc1902.ObjectType and rfc1902.NotificationType (.addAsn1MibSource(), .addMibSource(), .loadMibs()) .IP \(bu 2 When pretty printing indices at rfc1902.ObjectType, quote only strings. .IP \(bu 2 SNMP overview and PySNMP hlapi tutorial added to documentation. .IP \(bu 2 Fix to __doc__ use in setup.py to make \-O0 installation mode working. .IP \(bu 2 Fix to ObjectIdentity\->ObjectIdentifier attributes handover .IP \(bu 2 Fixed crash at oneliner compatibility code on EOM response. .IP \(bu 2 Fixed crash in hlapi.transport module. .IP \(bu 2 Fixed OID resolution issues that roots at node 0 and 2. .IP \(bu 2 Fix to MIB builder to fail gracefully on corrupted MIB package encounter. .IP \(bu 2 Fix to docs distribution \-\- now the are Sphinx\-buildable out\-of\-the\-box. .IP \(bu 2 Source code re\-linted .UNINDENT .SS Revision 4.3.0, released 2015\-09\-28 .INDENT 0.0 .IP \(bu 2 Critical error fixed in key localization procedure for AES192/AES256/3DES cyphers. Previous versions might never worked properly in this respect. .IP \(bu 2 Initial PySMI integration. Original ASN.1 MIBs could now be parsed, stored at a local pysnmp MIBs repository and loaded into SNMP Engine. Relevant example scripts added. Obsolete libsmi\-based scripts removed. .IP \(bu 2 Major rewrite of native SNMPv3 CommandGenerator and NotificationOriginator applications towards the following goals: .INDENT 2.0 .IP \(bu 2 avoid binding to specific SNMP engine instance to promote single SNMP app instance using many SNMP engine instances .IP \(bu 2 support two APIs for working with request data: one operates on the whole PDU object while the other on PDU contents .IP \(bu 2 keep callback context data in stack rather than in stateful application cache .IP \(bu 2 newly introduced sendVarBinds() method offers a more functional and logical signatures. .IP \(bu 2 Promote the use of dedicated classes for dealing with OID\-value pairs. Instances of those classes resemble OBJECT\-IDENTITY, OBJECT\-TYPE and NOTIFICATION\-TYPE MIB structures. .IP \(bu 2 Oneliner API reworked to become more generic: its LCD configuration shortcuts and and var\-bindings processing code split off SNMP apps classes to stand\-alone objects. The whole API also moved up in package naming hierarchy and becomes \(aqpysnmp.hlapi.asyncore\(aq (hlapi is apparently an African fish). Old oneliner API remains fully operational at its original location. .IP \(bu 2 Synchronous oneliner apps redesigned to offer Python generator\-based API along with a more comprehensive set of accepted parameters. .IP \(bu 2 Asyncore\-based asynchronous apps reworked to become functions. .IP \(bu 2 Twisted API moved entirely into high\-level domain to be aligned with other high\-level APIs. This WILL BREAK backward compatibility for those apps that use Twisted API. .IP \(bu 2 Keep backward compatibility for all existing major/documented interfaces .UNINDENT .IP \(bu 2 Sphinx documentation added to source code and example scripts. Library documentation converted from .html into RsT markup. .IP \(bu 2 Execution Observer facility implemented to give app an inside view of SNMP engine inner workings. This is thought to be a generic framework for viewing (and modifying) various internal states of pysnmp engine. Previously introduced non\-standard APIs (like getting peer\(aqs transport endpoint which is not suggested in RFCs) will be gradually migrated to this new framework. .IP \(bu 2 Initial support for the asyncio & Trollius frameworks and coroutines\-based SNMP Applications interfaces added. Both IPv4 and IPv6 datagram transports are currently supported. .IP \(bu 2 Original asynsock transport and AsyncsockDispatcher renamed into asyncore and AsyncoreDispatcher respectively to provide better hint to fellow devs on the underlying transport being used. Backward compatibility preserved. .IP \(bu 2 The asyncore\-based transport subsystem extended to support POSIX sendmsg()/recvmsg() based socket communication what could be used, among other things, in the context of a transparent SNMP proxy application. Technically, the following features were brought into pysnmp with this update: .INDENT 2.0 .IP \(bu 2 Sending SNMP packets from a non\-local IP address .IP \(bu 2 Receiving IP packets for non\-local IP addresses .IP \(bu 2 Responding to SNMP requests from exactly the same IP address the query was sent to. This proves to be useful when listening on both primary and secondary IP interfaces. .UNINDENT .IP \(bu 2 Internal oneliner apps configuration cache moved from respective apps objects to [a singular] snmpEngine \(dquser context\(dq object. That would allow for better cache reuse and allow for a single app working with many snmpEngine instances. .IP \(bu 2 Oneliner GETBULK Command Generator now strips possible excessive OIDs off the bottom of returned var\-binds table. .IP \(bu 2 Constraints assignment shortcut added to some base rfc1902 types (Integer, Integer32, OctetString, Bits). That formally constitutes ASN.1 sub\-typing. .IP \(bu 2 Built\-in debugging is now based on Python logging module. .IP \(bu 2 Examples on a single Transport Dispatcher use with multiple SnmpEngine instances applicatons added. .IP \(bu 2 Example script on transport timeout & retries manipulation added. .IP \(bu 2 Example script explaining incoming message\(aqs communityName re\-mapping added. .IP \(bu 2 Broadcast socket option can now be enabled with the .enableBroadcast() call for any datagram\-based transport (namely, UDP and UDP6). .IP \(bu 2 AbstractTransportDispatcher\(aqs jobStarted() and jobFinished() methods now accept optional \(aqcount\(aq parameter which is a way for an app to indicate how many responses are expected or have been processed in bulk. .IP \(bu 2 Example script on SNMP Agents UDP broadcast\-based discovery added. .IP \(bu 2 Oneliner transport object now supports setLocalAddress() method to force socket binding to specified local interface. .IP \(bu 2 New public DgramSocketTransport.getLocalAddress() returns local endpoint address underlying BSD socket is currently bound to. .IP \(bu 2 Passing request details to access control callback at CommandResponder reworked towards more robust and simple design with the execution observer facility. .IP \(bu 2 All MIBs rebuilt with pysmi. .IP \(bu 2 MIB instrumentation example improved to cover table index building facility. .IP \(bu 2 Handle the case of null writer at Debug printer. .IP \(bu 2 Do not cache snmpEngineId & snmpAdminString at CommandGenerator to let it be reused with many different snmpEngines. .IP \(bu 2 TRAP PDU agent address evaluation at proto.api made lazy to improve startup time. .IP \(bu 2 Multiple fixes to verify pyasn1 decoder.decode() return to withstand broken SNMP messages or its components. .IP \(bu 2 First attempt made to make some of SNMP Engine settings persistent across reboots. .IP \(bu 2 Make config.delTransport() returning detached transport object. Asyncio examples now use this facility to explicitly shutdown transport object. .IP \(bu 2 Parts of SMIv1 remnant MIBs (RFC1213\-MIB, RFC1158\-MIB) added to provide complete compatibility with SMIv1. Symbols defined in these MIBs only present in SMIv1 so they can\(aqt be substituted with their SMIv2 analogues. .IP \(bu 2 MibBuilder.addMibSources() convenience method added. .IP \(bu 2 The smi.MibBuilder() will now raise more specific exceptions (MibLoadError, MibNotFoundError) on MIB loading problems rather than more generic SmiError. .IP \(bu 2 The oneliner\(aqs MibVariable MIB lookup subsystem redesigned for more generality to mimic OBJECT\-TYPE macro capabilities related to SNMP PDU handling. The two new classed are ObjectIdentity and ObjectType. The ObjectIdentity class additionally supports just a MIB module name initializer in which case if resolves into either first or last symbol in given MIB. Another option is just a MIB symbol initializer without specifying MIB module. This new subsystem is moved from the scope of oneliner to more common pysnmp.smi.rfc1903 scope to more naturally invoke it from whatever part of pysnmp requires MIB services. .IP \(bu 2 MibBuilder now prepends the contents of environment variables it recognizes (PYSNMP_MIB_DIR, PYSNMP_MIB_DIRS, PYSNMP_MIB_PKGS) rather than using them instead of its default core MIBs. .IP \(bu 2 Removed RowStatus default value as it may collide with possible subclass constraints. .IP \(bu 2 A few additional MIB tree management methods added to MibViewController to better address ordered nature of MIB tree nodes (namely, getFirst*, getLast* family of methods). .IP \(bu 2 Wheel distribution format now supported. .IP \(bu 2 Fix to authoritative engine side snmpEngineID discovery procedure: respond with notInTimeWindows rather then with unsupportedSecurityLevel at time synchronization phase. .IP \(bu 2 Fix to rfc1902.Bits type to make it accepting hex and binary initializers, cope with missing bits identifieirs at prettyPrint(). .IP \(bu 2 Memory leak fixed in CommandForwarder examples. .IP \(bu 2 Fix to BULK CommandGenerator to use the same nonRepeaters OIDs across multiple GETBULK iterations so returned table for nonRepeaters columns would hold the same var\-bind. .IP \(bu 2 Fix to CommandGenerator to make sendRequestHandle persistent across multiple iterations of GETNEXT/GETBULK queries. .IP \(bu 2 Fix to sendNotification() error handling at NotificationOriginator. .IP \(bu 2 Fix to preserve possible \(aqfixed length\(aq setting atrfc1902.OctetString on clone()\(aqing and subtype()\(aqing. .IP \(bu 2 Fix to rfc1902.OctetString & Bits to base them on OctetString class to make the \(aqfixed length\(aq property working. .IP \(bu 2 Fix to .clone() method of rfc1902.Bits class to make its signature matching the rest of classes. This may broke code which used to pass namedValue parameter positionally rather than binding it by name. .IP \(bu 2 Fix to PDU translation service (proto.proxy.rfc2576) to make it initializing errorIndex & errorStatus components of the resulting PDU. .IP \(bu 2 Fix to MsgAndPduDispatcher.sendPdu() to clean up request queue on pysnmp\-level processing failure. .IP \(bu 2 Fix to SNMPv1/v2c message processing subsystem to make it serving unique PDU request\-id\(aqs in both outgoing and incoming confirmed and response PDU types. Duplicate request\-id\(aqs in unrelated PDUs may cause cache errors otherwise. .IP \(bu 2 Fix to licensing terms of multiple twisted backend modules to make the whole pysnmp package licensed under BSD 2\-Clause license. This change has been explicitly permitted by the original modules authors. .IP \(bu 2 Fix to asyncore\-based transport not to use asyncore\(aqs cheap inheritance from socket object what caused warnings. .IP \(bu 2 Fix at NotificationOriginator to make is using MibInstrumentationController when expanding Notification OBJECTS into Managed Objects Instances. .IP \(bu 2 Missing wrongLength and wrongEncoding SMI errors added. .IP \(bu 2 Fix to file descriptor leak at MibBuilder. .IP \(bu 2 Fix to rfc2576.v2ToV1() to ignore impossible errorStatus. .IP \(bu 2 Fix to rfc2576.v1ToV2() to reset ErrorStatus==noSuchName on proxying. .IP \(bu 2 Fix to smi.builder to explicitly fail on any MIB file access error (but ENOENT) and raise IOError uniformly on any directory/egg access failure. .IP \(bu 2 Fix to infinite loop at config.delV3User(). .UNINDENT .SS Revision 4.2.5, released 2013\-10\-02 .INDENT 0.0 .IP \(bu 2 License updated to vanilla BSD 2\-Clause to ease package use (\fI\%http://opensource.org/licenses/BSD\-2\-Clause\fP). .IP \(bu 2 A dozen of lightweight Twisted\-based example scripts replaced more complex example implementations used previously. .IP \(bu 2 SNMP Proxy example apps separated into a larger set of more specialized ones. .IP \(bu 2 Most of Command Generator examples re\-pointed to a live SNMP Agent at demo.snmplabs.com to ease experimentation and adoption. .IP \(bu 2 Multithreaded oneliner CommandGenerator example added. .IP \(bu 2 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. .IP \(bu 2 Standard SNMP Apps and built\-in proxy now ignores malformed errorIndex value. .IP \(bu 2 Built\-in logging now includes timestamps. .IP \(bu 2 Multi\-lingual capabilities of all CommandGenerator & NotificationOriginator apps re\-worked and improved. For instance it is now it\(aqs possible to run getBulk() against a SNMPv1 Agent invoking built\-in SNMP Proxy behind the scene. .IP \(bu 2 The $PYSNMP_MIB_DIR & $PYSNMP_MIB_DIRS & $PYSNMP_MIB_PKGS path separator made platform\-specific. .IP \(bu 2 Change to rfc2576.v1tov2() logic: errorStatus = noSuchName is now translated into rfc1905.noSuchObject exception value for \fIall\fP 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\(aqt easily stop doing that. .IP \(bu 2 Exception re\-raising improved at MibInstrumController.flipFlopFsm() and asynsock/twisted dispatchers so that original traceback is preserved. .IP \(bu 2 A single instance of transport dispatcher can now serve multiple receivers (identified by IDs) chosen by a public data routing method. .IP \(bu 2 SnmpEngine.[un]registerTransportDispatcher() methods now accept optional receiver ID token to be used by transport dispatcher\(aqs data router. This allows for multiple SNMP engines registration with a single transport dispatcher. .IP \(bu 2 Distribute is gone, switched to setuptools completely. .IP \(bu 2 The snmpCommunityTable row selection improved to follow RFC2576, clause 5.2.1. .IP \(bu 2 Asyncore\-based dispatcher attempts to use poll() whenever available on the platform. It would help handling a really large number (>1024) of file descriptors. .IP \(bu 2 AsynCommandGenerator.makeReadVarBinds() generalized into a new makeVarBinds() method which replaces somewhat redundant code at setCmd() and AsynNotificationOriginator.sendNotification(). .IP \(bu 2 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. .IP \(bu 2 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\(aqs wrappers. .IP \(bu 2 The contextEngineId parameter of config.addV3User() and auth.UsmUserData() renamed into securityEngineId as it\(aqs semantically correct .IP \(bu 2 Oneliner UsmUserData() and CommunityData() classes now support clone()\(aqing to facilitate authentication data management in user applications. .IP \(bu 2 Oneliner transport target classes now support the getTransportInfo() method that returns network addresses used on protocol level. .IP \(bu 2 Oneliner CommandGenerator.getNext() & .getBulk() methods now support the maxCalls kwarg to limit the maximum number of iterations to perform. .IP \(bu 2 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(). .IP \(bu 2 The SnmpV3MessageProcessingModel.getPeerEngineInfo() method is implemented to communicate discovered peer SNMP engine information to SNMP apps what can be used for fine usmUserTable configuration. .IP \(bu 2 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. .IP \(bu 2 MIB builder traceback formatting and reporting improved. .IP \(bu 2 SNMP Engine object now has a snmpEngineID attribute exposed. .IP \(bu 2 Fix to inet_ntop()/inet_pton() support on Windows at TRANSPORT\-ADDRESS\-MIB. .IP \(bu 2 Fix to usmUserSecurityName table column implementation \-\- automatic value generation from index value removed. .IP \(bu 2 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 \fInot\fP match tagged snmpTargetAddrTable entries and vice versa. .IP \(bu 2 Fix to Twisted\-based NotificationOriginator to make it serving INFORMs again. .IP \(bu 2 Fix to rfc2576.v1tov2() logic: errorStatus = noSuchName is now translated into rfc1905.noSuchObject exception value for \fIall\fP var\-bindings. Although this is not mentioned in RFC, it looks as a more consistent approach. .IP \(bu 2 Fix of rounding error to base I/O dispatcher\(aqs next timer call calculation. .IP \(bu 2 Explicit twisted dispatcher\(aqs timer resolution (of 1 sec) removed to make use of global default of 0.5 sec. .IP \(bu 2 Fix to twisted/udp non\-default local endpoint binding features. Common socket (\(aqhost\(aq, port) notation is now supported. .IP \(bu 2 Fix to Twisted\-based transport to make it closing UDP port / UNIX pipe on shutdown. .IP \(bu 2 Fix to Twisted\-based dispatcher not to close transport on unregistration at dispatcher as transports can potentially be reused elsewhere. .IP \(bu 2 Fix to asyncore\-based transport to work only with AsynsockDispatcher\(aqs socket map and not to touch default asyncore\(aqs one. The latter have caused dispatcher/transport restarting issues. .IP \(bu 2 The delV3User() function improved to drop all rows from USM table that were cloned from the target one. .IP \(bu 2 Fix to exceptions handling at MsgAndPduDispatcher.sendPdu() to avoid sendPduHandle miss (followed by system crash) on cache expiration run. .IP \(bu 2 Break cyclic references at CommandResponder and NotificationReceiver apps through close() method. .IP \(bu 2 Fix to octet string typing at 3DES codec (used to throw an exception). .IP \(bu 2 Fix to SnmpAdminString, SnmpTagList, SnmpTagValue types to make them supporting UTF\-8 initializers. .IP \(bu 2 Fix to v1/v2c message processing module which used to refer to a bogus stateReference in some cases what causes SNMP engine crashes. .IP \(bu 2 Fix to IPv6 transport to zero ZoneID, FlowID and ScopeID components sometimes coming along with incoming packet. .IP \(bu 2 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. .IP \(bu 2 Asyncsock sockets now configured with SO_REUSEADDR option to fix possible Windows error 10048. .IP \(bu 2 Gracefully handle malformed SnmpEngineID at USM coming from SNMPv3 header. .IP \(bu 2 Typos fixed in error\-status constants at CommandResponder .IP \(bu 2 Missing import added to oneliner auth module. .IP \(bu 2 Cosmetic changes to v3arch example scripts. .UNINDENT .SS Revision 4.2.4, released 2013\-01\-30 .INDENT 0.0 .IP \(bu 2 SNMPv3 high\-level and native API examples reworked and extended to cover many use cases. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 The missing functionality of passing lookupNames & lookupValues params to Notification Originator is now implemented. It may make sense for INFORMs. .IP \(bu 2 The missing functionality of passing contextName to oneliner version of NotificationOriginator.sendNotification is now implemented. .IP \(bu 2 Oneliner example apps now include cases where non\-default SNMP ContextEngineId/ContextName/SecurityEngineId is used. .IP \(bu 2 The contextName parameter of SnmpContext.getMibInstrum made optional. .IP \(bu 2 AbstractMibInstrumController class added as a base class for all possible kinds of Management Instrumentation controllers. .IP \(bu 2 Report package version on debugging code initialization. .IP \(bu 2 MibInstrumController.getMibBuilder() added. .IP \(bu 2 I/O sockets buffer sizes made configurable, minimum default is now forced to be no less than 2**17 (to fit two huge datagrams). .IP \(bu 2 Catch possible exceptions on pyasn1 encoder invocation. .IP \(bu 2 VACM modules converted from a function into an object to let it keep state (caches) in the future. .IP \(bu 2 Unnecessary MibSource explicit initialization calls removed at MibBuilder. .IP \(bu 2 Example configuration for Net\-SNMP\(aqs snmptrapd added. .IP \(bu 2 Cast additionalVarBinds into ObjectIdentifier type at NotificationOriginator.sendNotification() .IP \(bu 2 Standard SNMPv3 Apps hardened to catch protocol\-related exceptions and report them as errorIndication\(aqs. .IP \(bu 2 Catch and mute possible failure of getsockname(), that seems to happen on Windows only so far. .IP \(bu 2 Memory leak fixed at oneliner cache of already configured targets. .IP \(bu 2 Fixes to at AsynNotificationOriginator.sendNotification() to make a) the notificationType param mandatory b)t e varBinds param really optional .IP \(bu 2 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. .IP \(bu 2 Fix to MibVariable handling of the MIB, initializers. .IP \(bu 2 Fix to outgoing queue processing order at socket transport. Now it\(aqs a FIFO discipline rather than LIFO. .IP \(bu 2 Fix to NotificationOriginator\(aqs additionalVarBinds parameter \- it is not mandatory anymore with the oneliner API. Also additionalVarBinds defaulted value changed from None to () meaning no var\-binds. .IP \(bu 2 Attempt to convert Windows style EOL into UNIX ones in MIB source modules appeared to be unnecessary and even destructive to modules data in some cases. So the conversion code removed altogether. .IP \(bu 2 Fix to isAccessAllowed() error handling at NotificationOriginator. System used to crash on access denied condition. .IP \(bu 2 Fix to NotificationOriginator to make it use system uptime and trap OID values from SNMP engine\(aqs instrumentation rather then from SNMP context. .IP \(bu 2 Fix a couple of bugs at MibTable* logic involved for table instances creation. .IP \(bu 2 Fix to Management Instrumentation code to handle cases of non\-initialized or not\-compliant\-to\-constraints Managed Objects Instances. .IP \(bu 2 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). .UNINDENT .SS Revision 4.2.3, released 2012\-09\-06 .INDENT 0.0 .IP \(bu 2 SECURITY FIX: USM subsystem did not verify securityLevel of a request to an authoritative SNMP engine against auth/priv protocols configured for the user in question. That allowed unauthenticated/unciphered access to pysnmp\-based Agent even if USM user is configured to provide one. .IP \(bu 2 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. .IP \(bu 2 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). .IP \(bu 2 Oneliner CommandGenerator\(aqs class attributes lexicographicMode, maxRows and ignoreNonIncreasingOid moved to optional keyword args of nextGen() and bulkGen() methods. .IP \(bu 2 IPv6/UDP and Local Domain Socket transport interfaces added to the oneliner API. .IP \(bu 2 Mib Instrumentation subsystem re\-worked to replace excessive MibNode\(aqs smiCreate()/smiWrite()/smiDestroy() methods with MibScalarInstance\(aqs getValue()/setValue() .IP \(bu 2 MibTree.readTest[Get]Next() reworked to be called uniformely so user could tap on these methods at any level of the MIB tree. .IP \(bu 2 MibTableColumn.getNextNodeWithValue() unpublished API method obsoleted and removed for clarity. .IP \(bu 2 Hex dumps of binary parts of the protocol added to ease system operations analysis. .IP \(bu 2 SnmpEngineId autogeneration does not call DNS resolver but uses local hostname not to depend upon local IP availability and performance. .IP \(bu 2 Example apps reworked, additional SNMPv3 auth/priv protocols and transports added. .IP \(bu 2 Package version is now available as __init__.__version__ and it is in\-sync with distutils. .IP \(bu 2 Package meta\-information updated. .IP \(bu 2 The __init__.py\(aqs made non\-empty (rumors are that they may be optimized out by package managers). .IP \(bu 2 Multiple fixes to UNIX domain socket transport to make it fully operational again. .IP \(bu 2 Use sysUpTime value whenever it is included in Notification PDU, otheriwese resort to SNMP engine uptime reading. .IP \(bu 2 SNMPv2c Message is now defined in rfc1901.py what matches standard definition. .IP \(bu 2 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. .IP \(bu 2 The obsolete and unpublished MibInstrumController.readVarsFast() method removed for API clarity. .IP \(bu 2 MibBuilder now distinguishes case of MIB modules filenames even if underlying OS does not. .IP \(bu 2 LCD configuration caching is implemented at pysnmp.entity.rfc3413.config that improves performance of repetitive calls by 10% and might hugely improve NotificationOriginator\(aqs performance when working on a large number of targets. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 The Next & BulkCommandGenerator\(aqs 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. .IP \(bu 2 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. .IP \(bu 2 Auth & target configuration container classes moved to their separate modules at oneliner API. .IP \(bu 2 The notificationType parameter of AsynNotificationOriginator.sendNotification made defaulted to reflect its optional nature. .IP \(bu 2 Oneliner UsmUserData, UdpTransportTarget, Udp6TransportTarget instances are not hashable anymore as they are intended to act more like a data structure than object. .IP \(bu 2 Built\-in debugger now supports negating debugging categories. .IP \(bu 2 An async/getgen.py example script added. .IP \(bu 2 Fix to MIB data reading routine to make it working with possible Windows end\-of\-line\(aqs. .IP \(bu 2 Fix to CommandGenerator\(aqs SNMPv3 engine autodiscovery algorithm when retryCount is administratively set to 0. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 Fix to internal MessageProcessing and SecurityModel timers so they become dependant on system timer resolution. .IP \(bu 2 Fix to v1.PDUAPI.setDefaults() method that used to set wrongly typed time\-stamp component. .IP \(bu 2 Fix to IPv6 address handling to prevent system from crashing whilst running Python3. .IP \(bu 2 Fix to SNMPv2 exception objects translation into SNMPv1 PDU and NEXT OIDs calculation. .IP \(bu 2 Fix to MibTree class to properly report noSuchObject & noSuchInstance SNMP special values. .IP \(bu 2 Fix to libsmi2pysnmp tool to make it working again in Python < 2.7 .IP \(bu 2 Fix to exception handling at decodeMessageVersion() caller to prevent ASN.1 parsing errors crashing the whole app. .IP \(bu 2 Fix to GenericTrap type processing at rfc2576:v1Tov2c() which used to crash the whole SNMP engine. .IP \(bu 2 Fix to [possibly uninizilaized] pyasn1 objects printouts at MibInstrumController.__indexMib() .IP \(bu 2 Fix to maxSizeResponseScopedPDU calculation at rfc3414/service.py. .IP \(bu 2 Dedicated \(aqwithmib\(aq example set is obsolete and removed. .IP \(bu 2 Another SNMP proxy example app added (1to3.py). .IP \(bu 2 Fix to MIB modules loading code to make it using __import__() properly. This also makes pysnmp working again with Python 3.3rc0. .IP \(bu 2 Typo fix to snmpInASNParseErrs MIB instance object. .IP \(bu 2 Typo fix to errind.EngineIdMismatch class and its instance. .UNINDENT .SS Revision 4.2.2, released 2012\-04\-21 .INDENT 0.0 .IP \(bu 2 Oneliner CommandGenerator can now limit the number of SNMP table rows returned by nextCmd()/bulkCmd() methods. .IP \(bu 2 Oneliner CommunityData configuration object can now be initialized with community name only, security name will be chosen automatically. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 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. .IP \(bu 2 SMIv1 MIB modules (including RFC1155 and RFC1213) were moved to pysnmp\-mibs as pysnmp is SMIv2\-based. .IP \(bu 2 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. .IP \(bu 2 When running on Python3, SMI will re\-raise exceptions with the original traceback for easier diagnostics. .IP \(bu 2 Out of PYTHONPATH MIB paths now supported. .IP \(bu 2 Added pyasn1 decoder failures diagnistics in debug mode. .IP \(bu 2 Fix to non\-MT\-safe class attributes at SNMPv3 MP & SEC modules. .IP \(bu 2 Fix to ContextName handling in bytes form whilst running Python3. Data mismatch error would return otherwise. .IP \(bu 2 Fix to SNMPv3 MP peer engine ID discovery not to learn and use user\-specified ContextEngineId. .IP \(bu 2 Fix to socket.error processing at Py3 on Windows. .IP \(bu 2 Fix to oneliner GETNEXT/GETBULK implementation to properly support ignoreNonIncreasingOIDs option. .IP \(bu 2 Fix to setEndOfMibError()/setNoSuchInstanceError() at v1 PDU not to loose errorIndex. .IP \(bu 2 Fix to api.v2c.getVarBindTable() to ignore possible non\-rectangular GETBULK response tables. .IP \(bu 2 Fix to oneliner getnext/getbulk response table rectangulation procedure to gracefully handle an empty column condition. .IP \(bu 2 Fix to legacy MibBuilder.getMibPath() to prevent it from missing \&.egg\-based components in path. .IP \(bu 2 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. .IP \(bu 2 Fix to UDP6 transport handling at rfc2576 security module. .IP \(bu 2 Fix to SnmpEngineID value autogeneration (used to fail on Mac). .IP \(bu 2 SNMPv2\-SMI.ObjectType.__repr__() fixed to do a repr() on its components. .IP \(bu 2 All SNMPv2\-SMI.MibNode\-based objects, once exported to a mibBuilder, will carry an embedded label symbol. .IP \(bu 2 Exlicit repr() calls replaced with \(aq%r\(aq .IP \(bu 2 Fix to error processing at GETNEXT & GETBULK apps response handlers. .IP \(bu 2 Fix to libsmi2pysnmp to make it supporting long (256+) list of function params. .IP \(bu 2 Fix to libsmi2pysnmp to support inheritance of MIB types. .UNINDENT .SS Revision 4.2.1, released 2011\-11\-07 .INDENT 0.0 .IP \(bu 2 Support string OIDs at one\-liner API. .IP \(bu 2 Code quality of libsmi2pysnmp tool improved, MIBs re\-built. .IP \(bu 2 SNMP\-PROXY\-MIB & SNMP\-USER\-BASED\-SM\-3DES\-MIB added .IP \(bu 2 v1arch bulkgen.py example added .IP \(bu 2 Major overhawl for Python 2.4 \-\- 3.2 compatibility: .INDENT 2.0 .IP \(bu 2 get rid of old\-style types .IP \(bu 2 drop string module usage .IP \(bu 2 switch to rich comparation .IP \(bu 2 drop explicit long integer type use .IP \(bu 2 map()/filter() replaced with list comprehension .IP \(bu 2 apply() replaced with var\-args .IP \(bu 2 dictionary operations made 2K/3K compatible .IP \(bu 2 division operator made 2K/3K compatible .IP \(bu 2 sorting function now operates on key .IP \(bu 2 iterators returned by some funcs in py3k converted to lists .IP \(bu 2 exception syntax made 2K/3K compatible .IP \(bu 2 tuple function arguments resolved to scalars to become py3k compatible .IP \(bu 2 BER octetstream is now of type bytes (Py3k) or still string (Py2k) .UNINDENT .UNINDENT .SS Revision 4.1.16d, released 2011\-09\-22 .INDENT 0.0 .IP \(bu 2 Fix to SNMPv1 Trap PDU agentAddress setter shortcut method. .UNINDENT .SS Revision 4.1.16c, released 2011\-08\-14 .INDENT 0.0 .IP \(bu 2 Missing module import fixed in privacy subsystem .UNINDENT .SS Revision 4.1.16b, released 2011\-08\-13 .INDENT 0.0 .IP \(bu 2 Oneliner CommandGenerator can now optionally ignore non\-increasing OIDs. .IP \(bu 2 Default CommandResponder now skips non\-compliant (Counter64) values when responding to a v1 Manager. .IP \(bu 2 Fix to state information handling at CommandResponder app. .IP \(bu 2 Fix to Twisted reactor shutdown condition. .IP \(bu 2 Fix to distutils dependencies syntax. .UNINDENT .SS Revision 4.1.16a, released 2011\-03\-17 .INDENT 0.0 .IP \(bu 2 Extended Security Options (3DESEDE, AES192, AES256) privacy protocols implemented. .IP \(bu 2 The error\-indication codes moved from literals to objects for reliability and clarity .IP \(bu 2 Fix to v1.TrapPDUAPI.getVarBinds() to address PDU component at the right position. .IP \(bu 2 Fix to rfc1902.Bits initialization from named bits sequence. .IP \(bu 2 Fix to MIB builder by\-extension module filtering code to cope with .pyw files. .IP \(bu 2 Internal caches structure improved. .IP \(bu 2 Sync versions of oneliner apps split off async implementation for clarity. .IP \(bu 2 Randomize initial in various numeric sequences. .IP \(bu 2 MsgAndPduDsp expectResponse parameters passing reworked. .IP \(bu 2 GetNext/GetBulk response processing logic moved to getNextVarBinds() .IP \(bu 2 Changes towards performance improvement: .INDENT 2.0 .IP \(bu 2 all dict.has_key() & dict.get() invocations replaced with modern syntax (this breaks compatibility with Python 2.1 and older). .IP \(bu 2 introduce the MibInstrumControlle.readVarsFast() method (which skips the \(dqtesting\(dq phase of MIB value readin) for dealing with internal configuration (LCD). .IP \(bu 2 default debug.logger is now just a zero value instead of an object what saves big on frequent calls .IP \(bu 2 SNMPv2\-SMI columnar indices <\-> index values conversion code optimized. .IP \(bu 2 pre\-compute and re\-use some of ASN.1 structures. .IP \(bu 2 avoid setting PDU defaults to save on unnecessary initialization. .IP \(bu 2 skip ASN.1 types verification where possible. .IP \(bu 2 at oneliner Command Generator, avoid looking up pure OID arguments at MIB as it\(aqs pointless but takes time. .IP \(bu 2 cache MIB columnar objects instance ID <\-> symbolic index representation mapping .UNINDENT .UNINDENT .SS Revision 4.1.15a, released 2010\-12\-13 .INDENT 0.0 .IP \(bu 2 SNMP Proxy example added. .IP \(bu 2 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. .IP \(bu 2 CommandResponder API now supports async mode of operation. .IP \(bu 2 SNMP exception values now exported from rfc1905 module, and made pretty printable. .IP \(bu 2 Lexicographic walking mode is now supported at oneliner CommandGenerator. .IP \(bu 2 ContextEngineId&ContextName parameters passing implemented at v3arch oneliner API. .IP \(bu 2 Multiple instances of the same transport domain now supported. .IP \(bu 2 Initial snmpEngineId value generation improved not to accidentally collide within an administrative domain. .IP \(bu 2 MibTableColumn instances now build value\-to\-column\-instance map to speedup by\-value search. .IP \(bu 2 SNMPv2\-CONF::AgentCapabilities macro implemented. .IP \(bu 2 The libsmi2pysnmp tool handles some more MACROs. .IP \(bu 2 Void access control module implemented to let apps disabling [default] VACM. .IP \(bu 2 Allow standard SNMP apps to choose access control method to use. .IP \(bu 2 Twisted\-based CommandResponder example added. .IP \(bu 2 Fix/rework of Twisted GETNEXT/BULK CommandGenerator callback API to make it simpler and uniform with other CommandGenerators .IP \(bu 2 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. .IP \(bu 2 Fix to $SMIPATH initialization at build\-pysnmp\-mib. .IP \(bu 2 Fix to maxSizeResponseScopedPDU calculation. .IP \(bu 2 Fix to Next/Bulk CommandGenerators to catch a non\-increasing OID error condition (what prevents looping). .IP \(bu 2 Fix to Opaque value tagging at rfc1155.Opaque type. .IP \(bu 2 Fix to handle (fail gracefully) zero\-length user password. .IP \(bu 2 Fix to SNMP error propagation at Twisted driver (SF tracker ID #3054505). .IP \(bu 2 Fix to Agent\-role snmpEngineId discovery procedure that allows authenticated ReportPDU generation. .IP \(bu 2 Fix to SNMPv1 PDU handling at CommandResponder & NotificationReceiver apps. .IP \(bu 2 Fix to CommandResponder app to skip Counter64 SMI values when responding to SNMPv1 Manager. .IP \(bu 2 Fix to protocol translator code (rfc2576) to handle Counter64 type in v2c\-to\-v1 PDU translation. .IP \(bu 2 Fix to non\-response var\-binds translation in rfc2576.v2ToV1(). .IP \(bu 2 Fix to wrong exceptions used in pysnmp/entity modules. .IP \(bu 2 Fix to noauth/nopriv security module so that it would not crash SNMP engine if called accidentally. .IP \(bu 2 Fix to CommandResponder not to return out\-of\-range errorIndex along with genErr .IP \(bu 2 Fix to GETBULK CommandResponder to do a by\-column MIB walk, not by\-raw. .IP \(bu 2 Fix to getVarBindTable() API function logic. .IP \(bu 2 Fix to example Manager scripts to use errorIndex when available. .IP \(bu 2 Fix to dummy encryptData()/decryptData() API .IP \(bu 2 Fix to oneliner GETBULK table collection code to make it stripping uneven rows off table tail. .UNINDENT .SS Revision 4.1.14a, released 2010\-07\-15 .INDENT 0.0 .IP \(bu 2 Fix to maxSizeResponseScopedPDU calculation at USM security module: now more precise and robust against screwed values on input. .IP \(bu 2 Fix to MIB loading logic that used to load same\-name modules at disticts search paths on each loadModules() call. .IP \(bu 2 Fix to AsynsockDispatcher.runDispatcher() to make use of optional non\-default select() timeout value. .IP \(bu 2 AbstractTransportDispatcher now allows user application registering multiple timer callbacks each with dedicated call period. .IP \(bu 2 Asynsock mainloop default idle period reduced to 0.5 sec for better timer resolution. .IP \(bu 2 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. .IP \(bu 2 Fix to contextName processing at config.addV1System \-\- typo rendered passed contextName not committed into LCD. .IP \(bu 2 Fix to unknown ContextName exception handling at CommandResponder App. .IP \(bu 2 config.addVacmUser() now accepts an optional contextName what makes it usable for configuring multiple contextName\-bound bases of Managed Objects to SnmpEngine. .IP \(bu 2 MP pending states cache management re\-worked so that SNMP engine will now handle an unlimited number of pending request/responses. .IP \(bu 2 Fix to SNMP discovery procedure: include ContentName in SNMP discovery messaging. .IP \(bu 2 Many fixes to AES crypto code that makes it actually working. .IP \(bu 2 Fix to SNMPv2\-SMI createUndo operations. .IP \(bu 2 Fix to INFORM sending error handling at oneliner. .IP \(bu 2 Fix to mismatched response PDU handling at CommandGenerator application. .IP \(bu 2 Debug category \(aqapp\(aq (for Application) added to facilitate Standard SNMP Applications debugging. .IP \(bu 2 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. .IP \(bu 2 Debugging printout now escapes non\-printable characters. .UNINDENT .SS Revision 4.1.13a, released 2010\-02\-09 .INDENT 0.0 .IP \(bu 2 UDP over IPv6 transport implemented. .IP \(bu 2 Fix to MIB tree walking code that used to fail on table columns where indices have identical leading parts. .IP \(bu 2 SNMPv1/v2c snmpCommunityTransportTag\-based imcoming message filtering implemented (rfc2576). .UNINDENT .SS Revision 4.1.12a, released 2009\-12\-03 .INDENT 0.0 .IP \(bu 2 API versioning retired (pysnmp.v4 \-> pysnmp). .IP \(bu 2 MIB loading mechanics re\-designed to allow ZIP import. .IP \(bu 2 MIB loader supports code objects (py[co]) .IP \(bu 2 Installer now uses setuptools for package management whenever available. .IP \(bu 2 The libsmi2pysnmp tool improved to build constraints of more than 256 items (Python has a limit on the number of function params). .IP \(bu 2 Missing SNMPTrap PDU API implemented at proto.api.v2c, RFC2576 proxy code reworked. .IP \(bu 2 Fix to sysUpTime OID at SNMPv2 TRAP PDU. .UNINDENT .SS Revision 4.1.11a, released 2009\-08\-21 .INDENT 0.0 .IP \(bu 2 Twisted integration implemented. .IP \(bu 2 Attempt to use hashlib whenever available. .IP \(bu 2 Fix to oneliner Manager code on < Python 2.4. .IP \(bu 2 Let NotificationReceiver and CommandResponder Apps browsing request details (transport information at the moment) at SNMP engine. .IP \(bu 2 Fix to config.addV1System() to allow multiple systems to co\-exist in LCD. .IP \(bu 2 Fix to wrongly succeeding user\-parameters\-by\-community\-name searching code in rfc2576 processIncomingMsg() method. .IP \(bu 2 Do sanity checking on PYSNMP_MODULE_ID, Groups and Notifications in libsmi2pysnmp (SF bug #2122489). .IP \(bu 2 Fix to oneliner Notification Originator that sometimes used to send multiple requests at once. .IP \(bu 2 Oneliners LCD names generation code reworked to avoid accidental clashes. .IP \(bu 2 Fix and re\-work of sysUpTime value management in LCD. .IP \(bu 2 Fix to pending inform request data caching in mpmod/rfc2576.py \-\- previous code led to cache data corruption on multple outstanding requests. .IP \(bu 2 In SMI configuration wrapper functions, catch access to non\-configured entries and raise an exception. .IP \(bu 2 Allow multuple callback timer functions in all transport dispatchers. .IP \(bu 2 Fix to libsmi2pysnmp code to preserve more underscored object names and to guess the right type between indistinguishable ObjectGroup & NotificationGroup .IP \(bu 2 Fix to MibScalarInstance value setting logic \- previous code failed when modifying the same OID multiple times within a single SET operation. .IP \(bu 2 Minor usability improvements to tools/build\-pysnmp\-mib. .IP \(bu 2 Made MIB objects unexport feature operational. .UNINDENT .SS Revision 4.1.10a, released 2008\-05\-25 .INDENT 0.0 .IP \(bu 2 Internal MIB indexing method __indexMib() unmangled to facilitate setting up mutex there for sharing MIB stuff between threads. .IP \(bu 2 Fixed broken IpAddress value handling in SET operation. .IP \(bu 2 Broken MibBuilder.unloadModules() method now works. .IP \(bu 2 Use getLabel() SMI object method when building MIB tree (in builder.py) in addition to direct attribute access for clearer object protocol. .IP \(bu 2 The MIB building tools updated to match significantly improved smidump tool (libsmi version > 0.4.5). .IP \(bu 2 Made libsmi2pysnmp tool optionally building MIB text fields into pysnmp MIB code (enabled by default) and MibBuilder conditionally loading them up (disabled by default). .IP \(bu 2 SnmpEngine and MsgAndPduDispatcher constructors now optionally take msgAndPduDspr and mibInstrumController class instances respectively to facilitate these objects sharing within a process. .IP \(bu 2 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. .IP \(bu 2 Built\-in MIBs re\-generated to include text fields. .UNINDENT .SS Revision 4.1.9a, released 2007\-11\-28 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 At onliner CommandGenerator, close transport on destruction to prevent socket leak. Implicit async transports registration at default asyncore\(aqs socket map has been disabled to avoid side effects. .IP \(bu 2 Fix to rfc2576.v1ToV2c() PDU converter to perform noSuchName error code translation. .IP \(bu 2 Fixes to Notification PDU conversion code at rfc2576 in part of snmpTrapOID handling. .IP \(bu 2 Fix to nonRepeaters object use as sequence slicer (must be int) at cmdrsp.CommandResponderApplication .IP \(bu 2 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. .IP \(bu 2 Fix to response timeout roundup bug at CommandGenerator and NotificationOriginator code. .IP \(bu 2 Oneline configuration classes made hashable to prevent memory leaks when committing them into CommandGenerator/NotificationOriginator internal repository. .IP \(bu 2 Security information is now released properly in all MP modules. This might fix a significant memory leak. .IP \(bu 2 Typo fix to rfc3411 confirmed class PDU members. .UNINDENT .SS Revision 4.1.8a, released 2007\-08\-14 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 SMI/dispatcher timeout conversion multiplier is actually 100 (1/100 sec) rather than 1/1000. This fix affects timeouts specified through SMI. .IP \(bu 2 __repr__() implemented for UdpTransportTarget, CommunityData, UsmUserData in oneliner module. .IP \(bu 2 Automatically initialize table index values on table management operations (SF bug ID #1671989). .IP \(bu 2 Fix to carrier code: ignore BADFD socket error as it may happen upon FD closure on n\-1 select() event. .IP \(bu 2 Fix to MibBuilder.setMibPath() to preserve previously loaded modules intact. Otherwise loadModules() called after setMibPath() might fail with \(aqMIB file not found in search path\(aq exception. .IP \(bu 2 Fix to oneliner classes that now invoke unconfiguration methods on destruction. This might have caused memory leaks. .IP \(bu 2 Automatically initialize SNMP\-USER\-BASED\-SM\-MIB::UsmUserSecurityName columnar object instance on creation, as stated in DESCRIPTION (SF tracker ID #1620392). .IP \(bu 2 Fix to USM timeframe arithmetics (SF bug #1649032). .IP \(bu 2 VACM shortcuts merged into universal add/delVacmUser() to let notifications and requests to co\-exist for the same user. .IP \(bu 2 At oneliners, build LCD tables keys from a hashed mix of input parameters to make sure these automatic entries won\(aqt interfere or exceed constraints on keys values. .IP \(bu 2 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. .IP \(bu 2 Allow plain Python values in setCmd() and sendNotification() methods in CommandGenerator and NotificationOriginator applications respectively. .IP \(bu 2 Multi\-target oneliner API\-based example script added. .IP \(bu 2 Ignore more socket errors in datagram\-type async socket code. .IP \(bu 2 AES cipher now supported (rfc3826). .IP \(bu 2 Fix to messed up tagIDs of noSuchInstance and noSuchObject types. .IP \(bu 2 SET Command Responder fixed to obscure access to non\-existing variables by returning notWritable error (SF bug #1764839). .IP \(bu 2 AsynsockDispatcher.setSocketMap() method added to facilitate pysnmp transport integration into third\-party asyncore\-based applications. .IP \(bu 2 Fix to errorIndex generation at CommandResponder application, the value should be a one\-based. .UNINDENT .SS Revision 4.1.7a, released 2007\-02\-19 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 Low\-level debugging facility implemented. .IP \(bu 2 Support UdpTransportTarget timeout and retries parameters in oneliner API. .IP \(bu 2 Fix to snmpTrapOID construction at ...proxy.rfc2576.v1ToV2() function. .IP \(bu 2 Fix to MibViewController.getNodeName() to take MIB module name into account (SF bug #1505847). .IP \(bu 2 Do explicit check for Counter32,Unsigned32,TimeTicks,Counter64 value types in MibTableRow index conversion and in TextualConvention.prettyPrint() methods (SF bug #1506341). Handle Bits in indices as RFC2578 suggests. .IP \(bu 2 Apply read\-create column status to libsmi2pysnmp\-generated code whenever MIB text specifies that (SF bug #1508955). .IP \(bu 2 Honor and apply DISPLAY\-HINT specification when building TextualConvention class at libsmi2pysnmp. .IP \(bu 2 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. .IP \(bu 2 The libsmi2pysnmp now supports future libsmi bugfix that would generate \(dqranges\(dq subtree along with the legacy and ambiguous \(dqrange\(dq one. .IP \(bu 2 SMI support for fixed\-length string indices implemented (SF bug #1584799, #1653908). .IP \(bu 2 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). .IP \(bu 2 MIB table row destruction now works (SF bug #1555010). .IP \(bu 2 LCD unconfiguration functions for oneliners implemented (SF bug #1635270). .IP \(bu 2 unloadModules() and unexportSymbols() implemented at MibBuilder .IP \(bu 2 Notification type PDU proxy code fixed to produce symmetrical conversion. .IP \(bu 2 Various SNMP engine\-internal caches expiration implemented. .IP \(bu 2 SMI\-level access control now takes effect only if AC object is passed to MIB instrumentation API. .IP \(bu 2 LCD management code now uses generic MIB instrumentation features. .IP \(bu 2 Fix to oneliner manager code to have individual UdpSocketTransport instance per each SnmpEngine. Multithreaded apps might fail otherwise. (SF bug ID #1586420). .IP \(bu 2 Exclude the PYSNMP_MODULE_ID symbol from MIB view index, as it may get resolved into OID label instead of actual MIB object name. .IP \(bu 2 Memory leak fixed in indices.OidOrderedDict implementation. .IP \(bu 2 Fix to VACM shortcuts to let notifications and requests to co\-exist for the same user otherwise. .IP \(bu 2 Fix to ...oneliner.cmdgen.UsmUserData to support non\-default ciphers. .IP \(bu 2 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). .IP \(bu 2 Fix to notification objects resolution code at NotificationOriginator.sendNotification() .IP \(bu 2 Do not raise securityLevel for USM error reports that lacks user information, as these reports could never be ciphered (SF bug #1624720). .IP \(bu 2 Non\-default BULK PDU params now actually applied. .IP \(bu 2 SnmpEngineID default value generation algorithmic function changed to allow multiple SNMP engines running on the same host. .IP \(bu 2 Documentation updated. .IP \(bu 2 A handful of minor fixes applied (SourceForge tracker IDs #1537592, #1537600, #1537659, #1548208, #1560939, #1563715, #1575697, #1599220, #1615077, #1615365, #1616579). .UNINDENT .SS Revision 4.1.6a, released 2006\-05\-25 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 pysnmpUsmSecretAuthKey and pysnmpUsmSecretPrivKey length increased up to 256 octets. There seems no limit on this in RFC, though. .IP \(bu 2 A workaround for probably broken Agents: SNMPv3 Manager code defaults ContextEngineId to SecurityEngineId whenever ContextEngineId is not reported by authoritative SNMP engine on discovery. .IP \(bu 2 Use empty PDU in engine\-discovery report at mpmod/rfc3412.py. .IP \(bu 2 MibBuilder.loadModules() now fails on missing MIB files. .IP \(bu 2 MibBuilder.exportSymbols() now accepts unnamed objects (likely Managed Objects Instances) .IP \(bu 2 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. .IP \(bu 2 Fix to AsynNotificationOriginator.asyncSendNotification() callback formal parameters .IP \(bu 2 Initial VACM configuration implemented according to rfc3415 Appendix 1 .IP \(bu 2 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. .IP \(bu 2 Types/Notifications/Groups exportSymbols() call chunking implemented in tools/libsmi2pysnmp .IP \(bu 2 Initial values specified to pyasn1 types to comply with latest pyasn1 API. .IP \(bu 2 Documentation improved .IP \(bu 2 Minor fixes towards Python 1.5 compatibility .UNINDENT .SS Revision 4.1.5a, released 2005\-11\-04 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 Multi\-lingual SNMP Trap/Inform Applications completed; examples added .IP \(bu 2 SMI model re\-designed to make a clear separation between Managed Objects and their specification (AKA Agent and Manager side) .IP \(bu 2 SNMP SET Application support completed .IP \(bu 2 Minor, though backward incompatible, changes to one\-liner API .IP \(bu 2 Many bugfixes .UNINDENT .SS Revision 4.1.4a, released 2005\-08\-16 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 SHA\-based authentication fixed and privacy implemented .IP \(bu 2 \&...oneliner.cmdgen.UsmUserData constructor now takes authProtocol and privProtocol parameters in a backward incompatible manner. .UNINDENT .SS Revision 4.1.3a, released 2005\-07\-28 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 rfc3413 applications API changes (related to callback function behaviour). .IP \(bu 2 TransportDispatcher now provides \(dqjobs\(dq interface to clients for better control of dispatcher\(aqs execution. .IP \(bu 2 Many minor fixes. .UNINDENT .SS Revision 4.1.2a, released 2005\-07\-12 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 Top\-level application classes renamed into longer, self descripting names for clarity. .IP \(bu 2 CommandResponder & NotificationOriginator applications now uses stand\-alone SnmpContext for application registration. .IP \(bu 2 Many minor fixes (inspired by testing on WinXP) .UNINDENT .SS Revision 4.1.1a, released 2005\-06\-29 .INDENT 0.0 .IP \(bu 2 UNSTABLE ALPHA RELEASE. .IP \(bu 2 SNMPv3 code first published .IP \(bu 2 SNMP engine and applications implemented on library level .IP \(bu 2 Major re\-design towards SNMPv3\-style API. .UNINDENT .SS Revision 4.0.2a, released 2005\-03\-01 .INDENT 0.0 .IP \(bu 2 Adopted to slightly changed asyncore API (as shipped with python 2,4) .UNINDENT .SS Revision 4.0.1a, released 2004\-11\-18 .INDENT 0.0 .IP \(bu 2 Minor bug/typo fixes, mostly in example/ scripts. .UNINDENT .SS Revision 4.0.0a, released 2004\-11\-15 .INDENT 0.0 .IP \(bu 2 UNSTABLE EARLY ALPHA RELEASE. .IP \(bu 2 Major re\-design and re\-implementation. .IP \(bu 2 Rudimental API versioning implemented to let incompatible package branches to co\-exist within the same Python installation. .IP \(bu 2 SMI framework designed and implemented. This framework provides 1) various access to MIB data 2) a way to implement custom MIB instrumentation objects. There\(aqs also a tool for building SMI classes from libsmi(3) output (smidump \-f python). .IP \(bu 2 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. .IP \(bu 2 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). .IP \(bu 2 Asn1Item constraints machinery re\-implemented based on Mike C. Fletcher\(aqs design and code. Now various constrains are implemented as stand\-alone objects serving interested Asn1Object derivatives through some abstract protocol (that\(aqs probably the Decorator design pattern). .IP \(bu 2 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. .UNINDENT .sp Our development plans and new features we consider for eventual implementation are collected in the following section. .SS Further development .sp Although PySNMP is already a mature software and it is being used at many places, the ultimate goal of the project is to implement most of the useful features that SNMP standards can offer. What follows is a list of most prominent missing features that PySNMP developers are planning to put their hands on in the future. .SS PySNMP library .INDENT 0.0 .IP 1. 3 Built\-in MIB parser. PySNMP uses a data model of its own to work with information contained in MIB files. To convert ASN.1\-based MIB texts into Python modules, an off\-line, third\-party tool is employed. As it turns out, this approach has two major drawback: one is that PySNMP users may need to pre\-process MIB texts to use them with their PySNMP\-based applications. Another is that LibSMI\(aqs Python driver seems to miss some information carried by MIBs. Thus the solution would be to write another MIB parser and code generator which would produce PySNMP compliant Python code right from MIB text files all by itself. .sp \fBDone:\fP see \fI\%PySMI project\fP in conjuction with the latest PySNMP codebase. .IP 2. 3 Reverse MIB index. The variable\-bindings received by the system whilst in Manager role could be post\-processed using the information kept in MIB files to include human\-friendly OIDs names, tables indices and values representation. However, there is currently no provisioning in the PySNMP system for locating and loading up MIB files containing additional information on arbitrary OIDs. So the idea is to maintain an OID\-to\-MIB index to let PySNMP load relevant MIB automatically on demand. .IP 3. 3 Stream sockets support. Currently, PySNMP transport subsystem only supports datagram\-type network sockets. That covers UDP\-over\-IPv4 and UDP\-over\-IPv6. However, SNMP engine can potentially run over stream\-oriented protocols what would let it support TCP\-over\-IPv4, TCP\-over\-IPv6 and SSL/TSL transports. Neither of these is currently implemented with PySNMP. .IP 4. 3 AgentX implementation. We anticipate many uses of this. For instance, having AgentX protocol support in pure\-Python would let us write AgentX modules in pure\-Python and attach them to high\-performance Net\-SNMP Agent. Or we could build and maintain a fully\-featured, stand\-alone PySNMP\-based Agent so that users would write their own AgentX extensions what would comprise a complete SNMP Agent solution at lesser effort. .IP 5. 3 A DBMS\-based SMI. Currently implemented SMI takes shape of live Python objects that let user hook up his own handler on any existing Managed Object Instance. That\(aqs flexible and working approach in many cases, however sometimes, for instance when Management Instrumentation is inherently DBMS\-based, it may be more efficient to move the entire SMI/MIB subsystem into a database. PySNMP engine would talk to it through its simple and well defined SMI API. .UNINDENT .SS Stand\-alone PySNMP\-based tools .INDENT 0.0 .IP 1. 3 SNMP Proxy Forwarder. That would be a stand\-alone, application\-level proxy service supporting all SNMP versions, multiple network transports, Command and Notification SNMP message types. Its anticipated features include extensive configuration facilities, fine\-graned access control and logging. .sp \fBDone:\fP see \fI\%SNMP Proxy Forwarder\fP\&. .IP 2. 3 SNMP Trap Receiver. We see this application as a simple yet flexible SNMP TRAP collector. It would listen on network sockets of different types receiving SNMP TRAP/INFORM notifications over any SNMP version and putting all the details into a database and possibly triggering external events. .IP 3. 3 Database backend for SNMP Simulator. We have already built a tool for simulating SNMP Agents based on a snapshot of their Management Instrumentation state. Current implementation uses a plain\-text file for keeping and possibly managing the snapshot. Many users of the Simulator software requested a value variation feature to be supported so that simulated Agents would look live, not static. We consider this variation and also dependencies features would be best implemented as a relational database application. So we are planning to put some more efforts into the Simulator project as time permits. .sp \fBDone:\fP since \fI\%snmpsim\-0.2.4\fP .UNINDENT .sp If you need some particular feature \- please, \fI\%open a feature request\fP . Once we see a greater demand in particular area, we would re\-arrange our development resources to meet it sooner. .sp You could greater speed up the development of particular feature by sponsoring it. Please get back to us to discuss details. .sp Contributions to the PySNMP source code is greatly appreciated as well. We require contributed code to run with Python 2.4 through the latest Python version (which is 3.7 at the time of this writing). Contributed code will be redistributed under the terms of the same \fI\%license\fP as PySNMP is. .SH CONTACT .sp In case of questions or troubles using PySNMP, please open up an \fI\%issue\fP at GitHub or ask at \fI\%Stack Overflow\fP . .SH OLD SITE ARCHIVE .SS Old site archive .sp Starting from PySNMP 4.3.0, we redesigned all documentation and web\-site. For previous versions of those please follow these links for \fI\%old examples\fP and \fI\%old documentation\fP \&. .SH AUTHOR Ilya Etingof .SH COPYRIGHT 2005-2023, Ilya Etingof .\" Generated by docutils manpage writer. .