pysnmp

26
HOME QUICK START DOCUMENTATION EXAMPLES DOWNLOAD Obsolete Documentation Examples Download License Obsolete 6 » Home Obsolete » Documentation PySNMP tutorial by Ilya Etingof, 2007-2012 Table of contents 1. Network management basics 1.1 SNMP management architecture 1.2 The history of SNMP 2. Programming with PySNMP 2.1 One-line Applications 2.1.1 Synchronous Applications 2.1.1.1 Command Generator 2.1.1.2 Notification Originator 2.1.2 Asynchronous Applications 2.1.2.1 Asynchronous Command Generator 2.1.2.2 Asynchronous Notification Originator 2.1.3 Security configuration 2.1.3.1 User-Based Security Model configuration 2.1.3.2 Community-Based Security Model configu 2.1.4 Transport configuration 2.1.4.1 UDP Transport Target 2.2 Managed Objects names and values 2.3 MIB services 2.3.1 Data model for Managed Objects 2.3.2 MIB builder 2.3.3 MIB view controller 2.3.4 Implementing Managed Objects Instances 2.3.4.1 Associated value gatewaying 2.3.4.2 Tapping on Management Instrumentation Appendixies ASN.1 standard The following materials cover an obsolete version of PySNMP. Unless you are existing software based on this PySNMP version, you should use the latest s Applicable to PySNMP 4.1.9a through 4.2.2. 1. Network management basics As networks become more complex, in terms of device population, topology been getting more and more important for network administrators to have s convenient way for controlling all pieces of the whole network. PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/ 1 de 26 19-03-2014 14:53

Transcript of pysnmp

Page 1: pysnmp

HOME QUICK START DOCUMENTATION EXAMPLES DOWNLOAD

ObsoleteDocumentationExamplesDownloadLicenseObsolete

6

» Home >» Obsolete » Documentation

PySNMP tutorial

by Ilya Etingof, 2007-2012

Table of contents

1. Network management basics1.1 SNMP management architecture1.2 The history of SNMP

2. Programming with PySNMP2.1 One-line Applications

2.1.1 Synchronous Applications2.1.1.1 Command Generator2.1.1.2 Notification Originator

2.1.2 Asynchronous Applications2.1.2.1 Asynchronous Command Generator2.1.2.2 Asynchronous Notification Originator

2.1.3 Security configuration2.1.3.1 User-Based Security Model configuration2.1.3.2 Community-Based Security Model configuration

2.1.4 Transport configuration2.1.4.1 UDP Transport Target

2.2 Managed Objects names and values2.3 MIB services

2.3.1 Data model for Managed Objects2.3.2 MIB builder2.3.3 MIB view controller2.3.4 Implementing Managed Objects Instances

2.3.4.1 Associated value gatewaying2.3.4.2 Tapping on Management Instrumentation API

AppendixiesASN.1 standard

The following materials cover an obsolete version of PySNMP. Unless you are maintainiexisting software based on this PySNMP version, you should use the latest stable releaseApplicable to PySNMP 4.1.9a through 4.2.2.

1. Network management basics

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

1 de 26 19-03-2014 14:53

Page 2: pysnmp

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

For any information to be exchanged between entities, some agreement on information format andtransmission procedure needs to be settled beforehand. This is what is conventionally called aProtocol.

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

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

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

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

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

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

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

1.1 SNMP management architecture

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

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

SNMP protocol supportAccess to managed device's internals

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

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

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

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

2 de 26 19-03-2014 14:53

Page 3: pysnmp

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

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

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

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

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

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

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

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

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

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

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

1.2 The history of SNMP

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

In effort to fix security issues of SNMPv1 and to make protocol faster for operations on largenumber of Managed Objects, SNMP Working Group at IETF came up with SNMPv2. This new protocoloffers bulk transfers of Managed Objects information (by means of new, GETBULK messagepayload), improved security and re-worked SMI. But its new party-based security system turned outto be too complicated. In the end, security part of SNMPv2 has been dropped in favor ofcommunity-based authentication system used in SNMPv1. The result of this compromise is knownas SNMPv2c (where "c" stands for community) and is still widely supported without being a

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

3 de 26 19-03-2014 14:53

Page 4: pysnmp

standard ( RFC1902, RFC1903, RFC1904, RFC1905, RFC1906, RFC1907, RFC1908 ).

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

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

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

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

2. Programming with PySNMP

PySNMP stands for a pure-Python SNMP implementation. This software deals with the darkestcorners of SNMP specifications all in Python programming language.

This paper is dedicated to PySNMP revisions from 4.1.x and up. Previous PySNMP versions do notfollow the architecture and interfaces described in this tutorial.

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

The most ancient and low-level is SNMPv1/v2c protocol scope. Here programmer is supposedto build/parse SNMP messages and their payload -- Protocol Data Unit (PDU), handleprotocol-level errors, transport issues and so on.

Although considered rather complex to deal with, this API probably gives best performance,memory footprint and flexibility, unless MIB access and/or SNMPv3 support is needed.

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

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

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

The Applications API further simplifies Programmer's job by hiding LCD management issues(contrary to SNMPv3 engine level). This API could be exploited in a one-liner fashion, for

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

4 de 26 19-03-2014 14:53

Page 5: pysnmp

quick and simple prototyping.

The following figure draws major components of PySNMP system along with standard Applications.

PySNMP architecture

These standard SNMP applications, such as GET/SET command generators and responders or TRAPnotificators and receivers, translate into a set of classes designed by the Visitor pattern. Applicationclasses implement concrete SNMP operations in terms of specific PDU handling, while SNMP Engineclass acts as a Visitor. A single SNMP Engine can serve many Applications of different types at thesame time.

One of the design choices of SNMPv3 standard is to use a set of dedicated Managed Objects forSNMP engine internal purposes. One reason for that design involves making SNMP engine remotelyconfigurable via SNMP. These internally used Managed Objects are collectively called LocalConfiguration Datastore (LCD). In PySNMP, all SNMP engine configuration and statistics is kept inLCD. LCD Configurator is a wrapper aimed at simplifying LCD operations. Technically, LCDConfigurator is a set of functions whose names clearly reflect their semantics.

SNMP Engine, on the above figure, is a Composite class holding references to all components ofSNMP system. Typical user application has a single instance of SNMP Engine class possibly sharedby many SNMP Applications of all kinds.

Transport subsystem is used for sending SNMP messages to and accepting them from network. TheI/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 butothers are also possible. Dispatcher/Transport classes are designed after the Visitor pattern --Transport instances are Dispatcher visitors. Transport Dispatcher interfaces are mostly used byMessage And PDU Dispatcher. However, when using the SNMPv1/v2c-native API (the lowest-levelone), these interfaces would be invoked directly.

The rest of components are not normally accessed directly. They're mentioned here for clarificationpurposes.

Message And PDU Dispatcher is a heart of SNMP system. Its main responsibilities includedispatching PDUs from SNMP Applications through various subsystems all the way down toTransport Dispatcher, and passing SNMP messages coming from network up to SNMP Applications. Itmaintains logical connection with Management Instrumentation Controller which carries outoperations on Managed Objects, here for the purpose of LCD access.

Message Processing Modules handle message-level protocol operations for present and possiblyfuture versions of SNMP protocol. Most importantly, these include message parsing/building andpossibly invoking security services whenever required. All MP Modules share standard API used byMessage And PDU Dispatcher.

Message Security Modules perform message authentication and/or encryption. As of this writing,User-Based (for v3) and Community (for v1/2c) modules are implemented in PySNMP. All SecurityModules share standard API used by Message Processing subsystem.

Access Control subsystem uses LCD information to authorize remote access to Managed Objects.This is used when serving Agent Applications or Trap receiver in Manager Applications.

2.1 One-line Applications

As of this writing, one-line Applications currently cover Manager-side operations. Agent and Proxyroles could be implemented on top of native Applications API.

There're two kinds of APIs to one-line Applications: synchronous and asynchronous. Both areimplemented within the pysnmp.entity.rfc3413.oneliner.cmdgen module.

2.1.1 Synchronous One-line Applications

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

5 de 26 19-03-2014 14:53

Page 6: pysnmp

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

All Command Generator Applications are implemented within a single class:

class CommandGenerator([snmpEngine])

Create a SNMP Command Generator object.

Methods of the CommandGenerator class instances implement specific request types.

getCmd( authData, transportTarget, *varNames )

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

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

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

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

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

The varBinds is a tuple of Managed Objects. Those found in response are bound by positionto Managed Object names passed in request.

The following code performs SNMP GET operation over SNMPv1:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen>>> errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(... cmdgen.CommunityData('my-agent', 'public', 0),... cmdgen.UdpTransportTarget(('localhost', 161)),... (1,3,6,1,2,1,1,1,0),... (1,3,6,1,2,1,1,2,0)... )>>> print(errorIndication)None>>> print(errorStatus)0>>> print(varBinds)[(ObjectName(1.3.6.1.2.1.1.1.0), OctetString('Linux saturn 2.6.37.6-smp #2 SMP Sat Apr 9 23:39:07 CDT 2011 i686')), (ObjectName(1.3.6.1.2.1.1.2.0), ObjectIdentifier(1.3.6.1.4.1.8072.3.2.10))]

setCmd( authData, transportTarget, *varBinds )

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

The authData and transportTarget parameters have he same semantics as in getCmdmethod.

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

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

6 de 26 19-03-2014 14:53

Page 7: pysnmp

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

The following code performs SNMP SET operation over SNMPv2c:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen>>> from pysnmp.proto import rfc1902>>> errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().setCmd(... cmdgen.CommunityData('my-agent', 'public', 1),... cmdgen.UdpTransportTarget(('localhost', 161)),... ((1,3,6,1,2,1,1,1,0), rfc1902.OctetString('my system description'))... )>>> print(errorIndication)None>>> print(errorStatus)17>>> print(errorStatus.prettyPrint())notWritable(17)

nextCmd( authData, transportTarget, *varNames )

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

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

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

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

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

It's also possible to modify the above behaviour so that the varBindTable returned wouldcontain *all* Managed Objects from those passed in request up till the end of the list ofavailable Managed Objects at the Agent. This option is enabled by setting thelexicographicMode attribute of the CommandGenerator class instance to True.

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

The following code performs SNMP GETNEXT operation against a MIB subtree over SNMPv3:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen>>> errorIndication, errorStatus, errorIndex, varBindTable = cmdgen.CommandGenerator().nextCmd(... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),... cmdgen.UdpTransportTarget(('localhost', 161)),... (1,3,6,1,2,1,1)... )>>> print(errorIndication)None>>> print(errorStatus)0

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

7 de 26 19-03-2014 14:53

Page 8: pysnmp

>>> for varBindTableRow in varBindTable:... print(varBindTableRow)...[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux saturn 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))][(ObjectName('1.3.6.1.2.1.1.2.0'), ObjectIdentifier('1.3.6.1.4.1.8072.3.2.10'))][ skipped ][(ObjectName('1.3.6.1.2.1.1.9.1.4.9'), TimeTicks('17'))]>>>

bulkCmd( authData, transportTarget, nonRepeaters, maxRepetitions, *varNames )

Perform SNMP GETBULK request and return a response or error indication. The GETBULKrequest type has the same semantics as GETNEXT one except that the latter queries a bulk ofManaged Objects at once.

The authData, transportTarget, *varNames input parameters to the bulkCmd methodare the same as to nextCmd.

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

The maxRepetitions parameter indicates for how many instances of Managed Objects in therest of *varNames, besides first nonRepeaters ones, should be queried with singlerequest.

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

The errorIndication, errorStatus, errorIndex and varBindTable parameters have thesame meaning as in getCmd method.

The following code performs SNMP GETBULK operation against a MIB subtree over SNMPv3:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen>>> errorIndication, errorStatus, errorIndex, varBindTable = cmdgen.CommandGenerator().bulkCmd(... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),... cmdgen.UdpTransportTarget(('localhost', 161)),... 0, 25, # nonRepeaters, maxRepetitions... (1,3,6,1,2,1,1)... )>>> print(errorIndication)None>>> print(errorStatus)0>>> for varBindTableRow in varBindTable:... print(varBindTableRow)...[(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux saturn 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))][(ObjectName('1.3.6.1.2.1.1.2.0'), ObjectIdentifier('1.3.6.1.4.1.8072.3.2.10'))][ skipped ][(ObjectName('1.3.6.1.2.1.1.9.1.4.9'), TimeTicks('17'))]>>>

Notification Originator Applications are implemented within a single class:

class NotificationOriginator([snmpContext])

Create a SNMP Notification Originator object.

The following method of NotificationOriginator class instance implements specific notifications

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

8 de 26 19-03-2014 14:53

Page 9: pysnmp

types.

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

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

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

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

Be advised, that when using confirmed notification, Notification Receiver must knowContextEngineID of Notification Originator to be able to process and acknowledge confirmednotification.

The notificationType parameter indicates the kind of event to notify Manager about in formof SMI NOTIFICATION-TYPE object name. For instance, (('SNMPv2-MIB', 'coldStart'),) or(1,3,6,1,6,3,1,1,5,1) is a value of coldStart notification type as defined in SNMPv2-MIBmodule.

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

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

The following code sends SNMP TRAP over SNMPv3:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen, ntforg>>> from pysnmp.proto.api import v2c>>> errorIndication = ntforg.NotificationOriginator().sendNotification(... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),... cmdgen.UdpTransportTarget(('localhost', 162)),... 'trap',... (('SNMPv2-MIB', 'coldStart'),),... ((1,3,6,1,2,1,1,3,0), v2c.TimeTicks(44100)))>>> print(errorIndication)None>>> print(errorStatus)0

2.1.2 Asynchronous One-line Applications

Asynchronous API to one-line Applications is actually a foundation for Synchronous version, sothey're very similar. This Asynchronous API is useful for purposes such as running multiple, possiblydifferent, SNMP Applications at the same time or handling other activities inside user's programwhile SNMP Application is waiting for input/output.

All Command Generator Applications are implemented within a single class:

class AsynCommandGenerator([snmpEngine])

Create an asynchronous SNMP Command Generator object.

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

asyncGetCmd( authData, transportTarget, varNames, (cbFun, cbCtx) )

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

9 de 26 19-03-2014 14:53

Page 10: pysnmp

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

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

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

Where sendRequestHandle is an integer value used for matching response torequest. Its counterpart is returned on request submission by the asyncGetCmdmethod.

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

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

If cbFun has no more requests pending and want to complete, it must return a truevalue. Otherwise, it returns false.

The authData, transportTarget and varNames parameters have the same meaning as ingetCmd method.

The asyncGetCmd method returns unique sendRequestHandle integer value used formatching subsequent response to this request.

asyncSetCmd( authData, transportTarget, varBinds, (cbFun, cbCtx) )

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

The authData and transportTarget parameters have the same meaning as inCommandGenerator.getCmd method.

The cbFun and cbCtx parameters have the same meaning as inAsynCommandGenerator.asyncGetCmd method.

The varBinds parameter has the same meaning as in CommandGenerator.setCmd methodexcept that here it is passed in as a tuple.

asyncNextCmd( authData, transportTarget, varNames, (cbFun, cbCtx) )

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

The authData and transportTarget parameters have the same meaning as inCommandGenerator.nextCmd method.

The cbFun and cbCtx parameters have the same meaning as inAsynCommandGenerator.asyncGetCmd method.

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

asyncBulkCmd( authData, transportTarget, nonRepeaters, maxRepetitions, varNames,(cbFun, cbCtx) )

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

The authData, transportTarget, nonRepeaters and maxRepetitions parameters havethe same meaning as in CommandGenerator.nextCmd method.

The cbFun and cbCtx parameters have the same meaning as inAsynCommandGenerator.asyncGetCmd method.

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

10 de 26 19-03-2014 14:53

Page 11: pysnmp

The varNames parameter has the same meaning as in CommandGenerator.bulkCmd methodexcept that here it is passed in as a tuple.

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

asynCommandGenerator.snmpEngine.transportDispatcher.runDispatcher ()

Where asynCommandGenerator is AsynCommandGenerator class instance.

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

The following code performs SNMP GET operation asynchronously through SNMPv3:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen>>>>>> def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx):... print('sendRequestHandle = %d' % sendRequestHandle)... print('errorIndication = %s' % errorIndication)... print('errorStatus = %s' % errorStatus)... print('varBinds = %s' % (varBinds,))... print('cbCtx = %s' % cbCtx)...>>> asynCommandGenerator = cmdgen.AsynCommandGenerator()>>> # This is a non-blocking call>>> sendRequestHandle = asynCommandGenerator.asyncGetCmd(... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'), ... cmdgen.UdpTransportTarget(('localhost', 161)), ... ((1,3,6,1,2,1,1,1,0),), ... (cbFun, None))>>> print(sendRequestHandle)1>>> asynCommandGenerator.snmpEngine.transportDispatcher.runDispatcher()sendRequestHandle = 1errorIndication = NoneerrorStatus = 0varBinds = [(ObjectName('1.3.6.1.2.1.1.1.0'), OctetString("'Linux saturn 2.6.21 #2 Mon Mar 19 17:07:18 MSD 2006 i686'"))]cbCtx = None>>>

The AsynNotificationOriginator class implements specific notification types.

class AsynNotificationOriginator([snmpContext])

Create an asynchronous SNMP Notification Originator object.

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

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

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

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

cbFun( sendRequestHandle, errorIndication, cbCtx )

Where the sendRequestHandle, errorIndication and cbCtx parameters have the

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

11 de 26 19-03-2014 14:53

Page 12: pysnmp

same meaning as in callback function in AsynCommandGenerator.asynGetCmdmethod.

The cbCtx parameter has the same meaning as in AsynCommandGenerator.asyncGetCmdmethod.

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

The asyncSendNotification method returns unique sendRequestHandle integer valueused for matching subsequent delivery confirmation response to arbitrary notification.

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

asynNotificationOriginator.snmpEngine.transportDispatcher.runDispatcher ()

Where asynNotificationOriginator is AsynNotificationOriginator class instance.

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

The following code sends SNMP INFORM notification asynchronously through SNMPv3:

>>> from pysnmp.entity.rfc3413.oneliner import cmdgen, ntforg>>> from pysnmp.proto.api import v2c>>>>>> def cbFun(sendRequestHandle, errorIndication, cbCtx):... print('sendRequestHandle = %d' % sendRequestHandle)... print('errorIndication = %s' % errorIndication)... print('cbCtx = %s' % (cbCtx,))...>>> asynNotificationOriginator = ntforg.AsynNotificationOriginator()>>> # This is a non-blocking call>>> sendRequestHandle = asynNotificationOriginator.asyncSendNotification(... cmdgen.UsmUserData('my-user', 'my-authkey', 'my-privkey'),... cmdgen.UdpTransportTarget(('localhost', 162)),... 'inform',... ('SNMPv2-MIB', 'coldStart'),... ((1,3,6,1,2,1,1,1,0), v2c.TimeTicks(44100)),... (cbFun, None))>>> print(sendRequestHandle)1>>> asynNotificationOriginator.snmpEngine.transportDispatcher.runDispatcher()sendRequestHandle = 1errorIndication = NonecbCtx = None>>>

2.1.3 Security configuration

Calls to one-line Applications API require Security Parameters and Transport configuration objects asinput parameters. These classes serve as convenience shortcuts to SNMP engine configurationfacilities and for keeping persistent authentication/transport configuration between SNMP enginecalls.

Security Parameters object is Security Model specific. UsmUserData class serves SNMPv3User-Based Security Model configuration, while CommunityData class is used forCommunity-Based Security Model of SNMPv1/SNMPv2c.

class UsmUserData( securityName, authKey='', privKey='',

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

12 de 26 19-03-2014 14:53

Page 13: pysnmp

authProtocol=usmNoAuthProtocol, privProtocol=usmNoPrivProtocol )

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

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

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

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

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

usmHMACMD5AuthProtocol -- MD5-based authentication protocolusmHMACSHAAuthProtocol -- SHA-based authentication protocolusmNoAuthProtocol -- no authentication to use

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

usmDESPrivProtocol -- DES-based encryption protocolusmAesCfb128Protocol -- AES128-based encryption protocol (RFC3826)usm3DESEDEPrivProtocol -- triple DES-based encryption protocol (ExtendedSecurity Options)usmAesCfb192Protocol -- AES192-based encryption protocol (Extended SecurityOptions)usmAesCfb256Protocol -- AES256-based encryption protocol (Extended SecurityOptions)usmNoPrivProtocol -- no encryption to use

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

class CommunityData( securityName, communityName, mpModel=1 )

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

Mandatory securityName parameter is Community-Based Security Model username passedin as a string. For most purposes this can be an arbitrary string.

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

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

2.1.4 Transport configuration

Transport configuration object is Transport domain specific. UdpTransportTarget class representsan Agent accessible through UDP domain transport.

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

Create an object representing a single Agent accessible through UDP socket.

Mandatory transportAddr parameter indicates destination Agent address in form of tuple ofFQDN, port where FQDN is a string and port is an integer.

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

13 de 26 19-03-2014 14:53

Page 14: pysnmp

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

2.2 Managed Objects names and values

At the protocol level, each Managed Object instance is represented by a pair of Name and Valuecollectively called a Variable-Binding.

In PySNMP programming context, at the high-level API, each Managed Object is represented by atuple of two class instances -- one represents Managed Object Instance Name, and another -- itsvalue.

Managed Object Name is an instance of ObjectName class, which is derived from PyASN1ObjectIdentifier. In most cases, PySNMP APIs will automatically create an instance ofObjectIdentifier class from its initialization value. Therefore it's allowed to use a plain tuple ofintegers as a Managed Object Name.

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

class Integer( value )

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

class Integer32( value )

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

class OctetIdentifier( value )

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

class OctetString( value )

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

class IpAddress( value )

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

class Counter32( value )

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

class Gauge32( value )

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

class Unsigned32( value )

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

14 de 26 19-03-2014 14:53

Page 15: pysnmp

class TimeTicks( value )

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

class Opaque( value )

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

class Counter64( value )

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

class Bits( value )

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

It's PySNMP design decision to always use SMIv2 definitions for Managed Objects at the high-levelAPI regardless of SNMP protocol version being used. For instance, an SNMPv3 Manager will alwaysreport SMIv2 types even when talking to SNMPv1 Agent (which is SMIv1-compliant).

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

2.3 MIB services

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

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

2.3.1 Data model for Managed Objects

In PySNMP, Managed Objects take shape of Python class instances that implement various SMIv2items. Collections of Managed Objects, or MIBs, translate, in a one-to-one fashion, into Pythonmodules.

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

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

class MibScalar( name, syntax )

Create a definition of scalar Managed Object with name name and associated value of typesyntax.

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

The syntax parameter represents Managed Object's value type.

The MibScalar class implements the following methods:

getName()getSyntax()

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

15 de 26 19-03-2014 14:53

Page 16: pysnmp

getMaxAccess()getUnits()getStatus()getDescription()

Each of these methods return certain property of Managed Object.

class MibScalarInstance( name, syntax )

Create an instance of scalar Managed Object or Conceptual Table element with name nameand associated value syntax.

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

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

class MibTableColumn( name, syntax )

Create a definition of Conceptual Table Column with name name and associated value of typesyntax.

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

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

The MibTableColumn class implements the following methods:

setProtoInstance( instanceClass )

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

class MibTableRow( name )

Create a definition of Conceptual Table Row with name name.

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

The MibTableRow class implements the following methods:

getInstIdFromIndices( *indices )

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

Types of *indices must coerce into Table Index syntax.

getIndicesFromInstId( instanceId )

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

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

class MibTable( name )

Create a definition of Conceptual Table with name name.

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

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

16 de 26 19-03-2014 14:53

Page 17: pysnmp

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

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

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

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

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

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

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

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

2.3.2 MIB builder

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

class MibBuilder()

Create MIB modules loader/evaluator/indexer.

loadModules( *modNames )

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

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

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

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

unloadModules( *modNames )

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

Missing *modNames implies all currently loaded modules.

importSymbols( modName, *symNames )

Return a tuple of Managed Objects looked up by their MIB names *symNames. Managed

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

17 de 26 19-03-2014 14:53

Page 18: pysnmp

Objects returned in tuple are position-bound to *symNames parameters.

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

exportSymbols( modName, *anonymousSyms, **namedSyms )

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

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

unexportSymbols( modName, *symNames )

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

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

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

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

2.3.3 MIB view controller

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

class MibViewController(mibBuilder)

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

The mibBuilder argument is an instance of MibBuilder class.

The MibViewController class implements the following methods:

getNodeName(name)

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

(1, 3, 6, 1)('iso', 'org', 'dod', 'internet')('iso', 2, 'dod', 1)

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

18 de 26 19-03-2014 14:53

Page 19: pysnmp

pysnmp.proto.rfc1902.ObjectIdentifier("1.3.6.1")

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

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

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

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

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

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

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

getNextNodeName( name, modName='' )

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

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

getFirstNodeName(modName='')

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

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

getNodeLocation(name)

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

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

>>> from pysnmp.smi import builder, view>>>>>> mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB')>>> mibViewController = view.MibViewController(mibBuilder)>>>

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

19 de 26 19-03-2014 14:53

Page 20: pysnmp

>>> modName, symName, suffix = mibViewController.getNodeLocation((1,3,6,1,2,1,1,1,123))>>> print(modName)SNMPv2-MIB>>> print(symName)sysDescr>>> print(suffix)(123,)

2.3.4 Implementing Managed Objects Instances

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

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

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

Conceptual Tables additionaly support:

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

PySNMP Managed Objects Instances are implemented by the MibScalarInstance objects while avalue associated with Managed Object Instance is represented by its syntax initializationparameter.

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

2.3.4.1 Associated value gatewaying

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

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

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

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

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

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

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

20 de 26 19-03-2014 14:53

Page 21: pysnmp

)

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

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

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

2.3.4.2 Tapping on Management Instrumentation API

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

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

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

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

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

readTest( *args )

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

readGet( *args )

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

readTestNext( *args )

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

21 de 26 19-03-2014 14:53

Page 22: pysnmp

readGetNext( *args )

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

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

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

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

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

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

writeTest( name, value, *args )

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

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

writeCommit( *args )

The writeCommit method is invoked by SNMP engine by way of request processing inattempt to apply pending value, previously passed to Managed Object Instance throughwriteTest method. Custom implementation may attempt to apply pending value to athird-party system.

writeCleanup( *args )

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

writeUndo( *args )

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

22 de 26 19-03-2014 14:53

Page 23: pysnmp

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

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

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

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

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

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

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

createTest( name, value, *args )

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

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

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

createCommit( *args )

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

createCleanup( *args )

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

23 de 26 19-03-2014 14:53

Page 24: pysnmp

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

createUndo( *args )

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

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

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

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

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

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

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

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

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

Appendixies

ASN.1 standard

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

24 de 26 19-03-2014 14:53

Page 25: pysnmp

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

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

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

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

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

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

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

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

Object Identifier

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

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

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

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

ASN.1 data encoding

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

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

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

25 de 26 19-03-2014 14:53

Page 26: pysnmp

Need help? Try PySNMP mailing lists or report to library maintainers.

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

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

Disclaimer: this document is a work-in-progress. It is neither complete nor accurate. Take it with agrain of salt!

PySNMP Documentation http://pysnmp.sourceforge.net/docs/4.x/

26 de 26 19-03-2014 14:53