PySNMP tutorial
by Ilya Etingof, 2007-2012
Table of contents
Applicable to PySNMP 4.2.3 and later.
1. Network management basics
As networks become more complex, in terms of device population,
topology and distances, it has been getting more and more important
for network administrators to have some easy and convenient way for
controlling all pieces of the whole network.
Basic features of a network management system include device information
retrieval and device remote control. Former often takes shape of gathering
device operation statistics, while latter can be seen in device remote
configuration facilities.
For any information to be exchanged between entities, some agreement on
information format and transmission procedure needs to be settled beforehand.
This is what is conventionally called a Protocol.
Large networks nowdays, may host thousands of different devices.
To benefit network manager's interoperability and simplicity, any
device on the network should carry out most common and important management
operations in a well known, unified way. Therefore, an important feature
of a network management system would be a Convention on
management information naming and presentation.
Sometimes, management operations should be performed on large number of
managed devices. For a network manager to complete such a management round
in a reasonably short period of time, an important feature of a network
management software would be Performance.
Some of network devices may run on severely limited resources what invokes
another property of a proper network management facility:
Low resource consumption.
In practice, the latter requirement translates into low CPU cycles and
memory footprint for management software aboard device being managed.
As networking becomes a more crucial part of our daily lives, security
issues have become more apparent. As a side note, even Internet
technologies, having military roots, did not pay much attention to security
initially. So, the last key feature of network management appears to be
Security.
Data passed back and forth through the course of management operations should
be at least authentic and sometimes hidden from possible observers.
All these problems were approached many times through about three decades
of networking history. Some solutions collapsed over time for one reason or
another, while others, such as Simple Network Management Protocol (SNMP),
evolve into an industry standard.
1.1 SNMP management architecture
The SNMP management model includes three distinct entities -- Agent, Manager
and Proxy talking to each other over network.
Agent entity is basically a software running somewhere in a networked device
and having the following distinguishing properties:
- SNMP protocol support
- Access to managed device's internals
The latter feature is a source of management information for Agent, as well
as a target for remote control operations.
Modern SNMP standards suggest splitting Agent functionality on two parts.
Such Agents may run SNMP for local processes called Subagents, which
interface with managed devices internals. Communication between Master
Agent and its Subagents is performed using a simplified version
of original SNMP protocol, known as AgentX, which is
designed to run only within a single host.
Manager entity is usually an application used by humans (or daemons) for
performing various network management tasks, such as device statistics
retrieval or remote control.
Sometimes, Agents and Managers may run peer-to-peer within a single entity
that is called Proxy. Proxies can often be seen in application-level
firewalling or may serve as SNMP protocol translators between otherwise
SNMP version-incompatible Managers and Agents.
For Manager to request Agent for an operation on a particular part of
managed device, some convention on device's components naming is needed.
Once some components are identified, Manager and Agent would have to agree
upon possible components' states and their semantics.
SNMP approach to both problems is to represent each component of a device
as a named object, similar to named variables seen in programming
languages, and state of a component maps to a value associated with this
imaginary variable. These are called Managed Objects in SNMP.
For representing a group of similar components of a device, such as network
interfaces, Managed Objects can be organized into a so-called
conceptual table.
Manager talks to Agent by sending it messages of several types. Message
type implies certain action to be taken. For example, GET
message instructs Agent to report back values of Managed Objects whose names
are indicated in message.
There's also a way for Agent to notify Manager of an event occurred to Agent.
This is done through so-called Trap messages. Trap message also
carries Managed Objects and possibly Values, but besides that it has an
ID of event in form of integer number or a Managed Object.
For naming Managed Objects, SNMP uses the concept of
Object Identifier. As an example of Managed Object,
.iso.org.dod.internet.mgmt.mib-2.system.sysName.0 represents
human-readable name of a device where Agent is running.
Managed Objects values are always instances of
ASN.1 types (such as Integer) or SNMP-specific subtypes
(such as IpAddress). As in programming languages, type has an effect of
restricting possible set of states Managed Object may ever enter.
Whenever SNMP entities talk to each other, they refer to Managed Objects whose
semantics (and value type) must be known in advance by both parties. SNMP Agent
may be seen as a primary source of information on Managed Objects, as they are
implemented by Agent. In this model, Manager should have a map of Managed
Objects contained within each Agent to talk to.
SNMP standard introduces a set of ASN.1 language constructs (such as ASN.1
subtypes and MACROs) which is called Structure of Management Information
(SMI). Collections of related Managed Objects described in terms of
SMI comprise Management Information Base (MIB) modules.
Commonly used Managed Objects form core MIBs that become part of SNMP standard.
The rest of MIBs are normally created by vendors who build SNMP Agents into
their products.
More often then not, Manager implementations could parse MIB files and
use Managed Objects information for names resolution, value type determination,
pretty printing and so on. This feature is known as MIB parser support.
1.2 The history of SNMP
First SNMP version dates back to 1988 when a set of IETF RFC's
were first published (
RFC1065,
RFC1066,
RFC1067
). These documents describe protocol operations
(in terms of message syntax and semantics), SMI and a few core MIBs.
The first version appears to be lightweight and easy to implement.
Although, its poor security became notorious over years (Security? Not My
Problem!), because cleartext password used for authentication (AKA
Community String) is extremely easy to eavesdrop and replay,
even after almost 20 years, slightly refined standard
(
RFC1155,
RFC1157,
RFC1212
) still seems to be the most frequent encounter in modern SNMP devices.
In effort to fix security issues of SNMPv1 and to make protocol faster for
operations on large number of Managed Objects, SNMP Working Group at IETF
came up with SNMPv2. This new protocol offers bulk transfers of Managed
Objects information (by means of new, GETBULK message payload), improved
security and re-worked SMI. But its new party-based security system turned
out to be too complicated. In the end, security part of SNMPv2 has been dropped
in favor of community-based authentication system used in SNMPv1. The result
of this compromise is known as SNMPv2c (where "c" stands for community) and
is still widely supported without being a standard (
RFC1902,
RFC1903,
RFC1904,
RFC1905,
RFC1906,
RFC1907,
RFC1908
).
The other compromise targeted at offering greater security than SNMPv1,
without falling into complexities of SNMPv2, has been attempted by
replacing SNMPv2 party-based security system with newly developed
user-based security model. This variant of protocol is known as SNMPv2u.
Although neither widely implemented nor standardized, User Based Security
Model (USM) of SNMPv2u got eventually adopted
as one of possibly many SNMPv3 security models.
As of this writing, SNMPv3 is current standard for SNMP. Although it's based
heavily on previous SNMP specifications, SNMPv3 offers many innovations but
also brings significant complexity. Additions to version 3 are mostly about
protocol operations. SMI part of standard is inherited intact from SNMPv2.
SNMPv3 system is designed as a framework that consists of a core, known
as Message and PDU Dispatcher, and several abstract
subsystems: Message Processing Subsystem
(MP), responsible for SNMP message handling,
Transport Dispatcher, used for carrying over messages,
and Security Subsystem, which deals with message
authentication and encryption issues. The framework defines
subsystems interfaces to let feature-specific modules to be plugged into
SNMPv3 core thus forming particular feature-set of SNMP system. Typical use
of this modularity feature could be seen in multiprotocol systems -- legacy
SNMP protocols are implemented as version-specific MP and security modules.
Native SNMPv3 functionality relies upon v3 message processing and User-Based
Security modules.
Besides highly detailed SNMP system specification, SNMPv3 standard also
defines a typical set of SNMP applications and their behavior. These
applications are Manager, Agent and Proxy (
RFC3411,
RFC3412,
RFC3413,
RFC3414,
RFC3415,
RFC3416,
RFC3417,
RFC3418
).
2. Programming with PySNMP
PySNMP is a pure-Python SNMP engine implementation. This software deals with
the darkest corners of SNMP specifications all in Python programming language.
This paper is dedicated to PySNMP revisions 4.2.3 and up. Since PySNMP API's
evolve over time, older revisions may provide slightly different interfaces
than those described in this tutorial. Please refer to release-specific
documentation for a more precise information.
From Programmer's point of view, the layout of PySNMP software reflects SNMP
protocol evolution. It has been written from ground up, from trivial SNMPv1 up
to fully featured SNMPv3. Therefore, several levels of API to SNMP
functionality are available:
-
The most ancient and low-level is SNMPv1/v2c protocol scope. Here
programmer is supposed to build/parse SNMP messages and their
payload -- Protocol Data Unit (PDU),
handle protocol-level errors, transport issues and so on.
Although considered rather complex to deal with, this API probably gives best
performance, memory footprint and flexibility, unless MIB access and/or
SNMPv3 support is needed.
-
Parts of SNMPv3 standard is expressed in terms of some abstract API to
SNMP engine and its components. PySNMP implementation adopts this abstract API
to a great extent, so it's available at Programmer's disposal. As a side
effect, SNMP RFCs could be referenced for API semantics when programming
PySNMP at this level.
This API is much more higher-level than previous; here Programmer would
have to manage two major issues: setting up Local Configuration Datastore
(LCD) of SNMP engine and build/parse PDUs. PySNMP system is
shipped multi-lingual, thus at this level all SNMPv1, SNMPv2c and SNMPv3
features are available.
-
At last, the highest-level API to SNMP functionality is available through the
use of standard SNMPv3 applications. These applications cover the most
frequent needs. That's why this API is expected to be the first to
start with.
The Applications API further simplifies Programmer's job by hiding
LCD management issues (contrary to SNMPv3 engine level). This API could be
exploited in a oneliner fashion, for quick and simple prototyping.
As for its internal structure, PySNMP consists of a handful of large,
dedicated components. They normally take shape of classes which turn
into linked objects at runtime. So here are the main components:
-
SNMP Engine is an object holding references to all other components of
the SNMP system. Typical user application has a single instance of SNMP
Engine class possibly shared by many SNMP Applications of all kinds.
As the other linked-in components tend to buildup various
configuration and housekeeping information in runtime, SNMP Engine object
appears to be expensive to configure to a usable state.
-
Transport subsystem is used for sending SNMP messages to and accepting them
from network. The I/O subsystem consists of an abstract Dispatcher and one
or more abstract Transport classes. Concrete Dispatcher implementation
is I/O method-specific, consider BSD sockets for example. Concrete Transport
classes are transport domain-specific. SNMP frequently uses UDP Transport
but others are also possible. Transport Dispatcher interfaces are mostly
used by Message And PDU Dispatcher. However, when using the SNMPv1/v2c-native
API (the lowest-level one), these interfaces would be invoked directly.
-
Message And PDU Dispatcher is a heart of SNMP system. Its main responsibilities
include dispatching PDUs from SNMP Applications through various subsystems
all the way down to Transport Dispatcher, and passing SNMP messages coming
from network up to SNMP Applications. It maintains logical connection with
Management Instrumentation Controller which carries out operations on Managed
Objects, here for the purpose of LCD access.
-
Message Processing Modules handle message-level protocol operations for present
and possibly future versions of SNMP protocol. Most importantly, these include
message parsing/building and possibly invoking security services whenever
required. All MP Modules share standard API used by Message And PDU Dispatcher.
-
Message Security Modules perform message authentication and/or encryption.
As of this writing, User-Based (for v3) and Community (for v1/2c) modules
are implemented in PySNMP. All Security Modules share standard API used by
Message Processing subsystem.
-
Access Control subsystem uses LCD information to authorize remote access to
Managed Objects. This is used when serving Agent Applications or Trap
receiver in Manager Applications.
-
A collection of dedicated Managed Objects Instances are used by PySNMP
for its internal purposes. They are collectively called Local
Configuration Datastore (LCD). In PySNMP, all SNMP engine configuration
and statistics is kept in LCD. LCD Configurator is a wrapper aimed at
simplifying LCD operations.
In most cases user is expected to only deal with the top-leve oneliner
API to all these PySNMP components. However implementing SNMP Agents,
Proxies and some other fine features of Managers require using the
Standard Applications API. In those cases general understanding of SNMP
operations and SNMP Engine components would be helpful.
2.1 One-line Applications
As of this writing, oneliner Applications support generating Manager-side
GET/SET/GETNEXT/GETBULK and issuing Agent-side TRAP/INFORM messages.
Agent and Manager side responders are more complex and rarely used to fit
them into the concise oneliner API so these should be implemented on top of
standard SNMP Applications API.
There're two kinds of APIs to oneline Applications: synchronous and
asynchronous. They are very similar in terms of their API and behaviour,
both are implemented by the
pysnmp.entity.rfc3413.oneliner.cmdgen module. The
asynchronous version is more suited for massively parallel SNMP messaging.
2.1.1 Synchronous One-line Applications
This is the simplest and the most high-level API to standard SNMP
Applications. It's advised to employ for singular and blocking
operations as well as for rapid prototyping.
2.1.1.1 Command Generator
All Command Generator Applications are implemented by a single class:
- class CommandGenerator([snmpEngine])
-
Create a SNMP Command Generator object.
Although instantiation of this class is cheap, in the course of its further
use, SNMP engine configuration is built and maintained though methods
invocation.
Therefore it is advised to keep and reuse CommandGenerator instance
(or snmpEngine instance if passed as an initializer)
for as long as possible within user applicatin.
Methods of the CommandGenerator class instances implement
specific request types.
- getCmd(
authData,
transportTarget,
*varNames,
lookupNames=False,
lookupValues=False
)
-
Perform SNMP GET request and return a response or error indication.
The authData is a
SNMP Security Parameters object,
transportTarget is a SNMP
Transport Configuration object
and *varNames is a sequence of
Managed Objects names.
The getCmd method returns a tuple of
errorIndication,
errorStatus,
errorIndex,
varBinds.
Non-empty errorIndication string indicates SNMP engine-level
error.
The pair of errorStatus and errorIndex
variables determines SNMP PDU-level error. These are instances of pyasn1
Integer class.
If errorStatus evaluates to true, this indicates SNMP PDU
error caused by Managed Object at position errorIndex-1
in varBinds.
Doing errorStatus.prettyPrint() would return an
explanatory text error message.
The varBinds is a sequence of Managed Objects.
Those found in response are bound by position to Managed Object names passed in request.
If lookupNames parameter evaluates to True, PySNMP will
attempt to gather more information on
Managed Objects returned in
varBinds by searching for relevant MIB module and looking
up there. Instance of
MibVariable class will be returned as Managed
Object names.
If lookupValues parameter evaluates to True, Managed Objects
Instances values
returned in varBinds may be converted into a more precise
type (employing
TEXTUAL-CONVENTION data
from MIB) if PySNMP has relevant MIB loaded. Otherwise response values will
belong to protocol-level
Managed Object Instance value types.
The following code performs SNMP GET operation
- using SNMP v2c
- with community name 'public'
- over IPv4/UDP
- against an Agent listening at localhost (UDP port 161)
- requesting two Managed Object Instances specified by name in string form
from pysnmp.entity.rfc3413.oneliner import cmdgen
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
cmdgen.CommunityData('public'),
cmdgen.UdpTransportTarget(('localhost', 161)),
'1.3.6.1.2.1.1.1.0',
'1.3.6.1.2.1.1.6.0'
)
# Check for errors and print out results
if errorIndication:
print(errorIndication)
else:
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex)-1] or '?'
)
)
else:
for name, val in varBinds:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
|
- setCmd(
authData,
transportTarget,
*varBinds,
lookupNames=False,
lookupValues=False
)
-
Perform SNMP SET request and return a response or error indication.
The authData, transportTarget,
lookupNames and lookupValues parameters
have the same semantics as in getCmd
method.
The *varBinds input parameter is a sequence of
Managed Objects to be modified at the Agent.
The setCmd method returns a tuple of
errorIndication,
errorStatus,
errorIndex,
varBinds.
having the same meaning as in getCmd method.
The following code performs SNMP SET operation
- using SNMP v3
- with username 'usr-md5-des', MD5 authentication and DES privacy protocols
- over IPv4/UDP
- against an Agent listening at localhost (UDP port 161)
- setting SNMPv2-MIB::sysName.0 object to a new value
The MibVariable object is used on input to
allow symbolic Managed Object Instance name specification. Response names
are requested to be returned also in form of a MibVariable object and
response values converted into MIB-defined type.
from pysnmp.entity.rfc3413.oneliner import cmdgen
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBinds = cmdGen.setCmd(
cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
cmdgen.UdpTransportTarget(('localhost', 161)),
(cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0), 'my new value'),
lookupNames=True, lookupValues=True
)
# Check for errors and print out results
if errorIndication:
print(errorIndication)
else:
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex)-1] or '?'
)
)
else:
for name, val in varBinds:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
|
- nextCmd(
authData,
transportTarget,
*varNames,
lookupNames=False,
lookupValues=False,
lexicographicMode=False,
ignoreNonIncreasingOid=False,
maxRows=0
)
-
Perform SNMP GETNEXT request and return a response or error indication.
The GETNEXT request type implies referring to Managed Objects whose Object
Names are "next greater" to those used in request.
The authData, transportTarget,
lookupNames and lookupValues parameters
have the same semantics as in getCmd
method.
The *varNames parameter is a sequence of
Managed Objects names to query Agent
for their "next" greater neignbours' Managed Objects Instances values. Unlike
the same-named parameter of getCmd method,
a partial (prefix part of) Managed Objects names are allowed here. For instance,
a '1.3.6.1' argument would ask the Agent to report Managed
Object Instance value with the next greater name known to this Agent
(which may turn out to be '1.3.6.1.2.1.1.1.0').
The nextCmd method returns a tuple of
errorIndication,
errorStatus,
errorIndex,
varBindTable.
The errorIndication, errorStatus and
errorIndex parameters have the same meaning as in
getCmd method.
The varBindTable parameter is a sequence of
varBinds. Each varBind of
varBinds in varBindTable represent a
set of Managed Objects whose Object Names reside inside
OID sub-tree of Managed Object name passed in request.
In other words, with this oneliner API, an invocation of
nextCmd method for a single Managed Object might return
a sequence of Managed Objects so that Object Name passed in request would
be a prefix for Object Names returned in response (as a side note, the same
method in Applications API would return varBinds as held
in a single response, and regardless of the prefix property).
It's possible to modify the above behaviour so that the
varBindTable returned would contain *all*
Managed Objects from those passed in request up to the end of
the list of available Managed Objects at the Agent. This option
is enabled by passing the lexicographicMode=True
parameter to nextCmd method.
In some cases application is also interested in some contiguous set of Managed
Objects Instances not necessarily strictly belonging to the same subtree.
The maxRows=NNN parameter to nextCmd would
stop Command Generator once the required number (NNN) of Managed Objects
Instances are retrieved from the Agent.
Properties of the varBinds parameter is the same as in
getCmd method.
The following code performs SNMP GETNEXT operation against a MIB subtree
- using SNMP v1
- with community name 'public'
- over IPv4/UDP
- against an Agent listening at localhost (UDP port 161)
- for some columns of the IF-MIB::ifEntry table
- stop reading values from Agent once response names leave the scopes of
initial names (e.g. OBJECT IDENTIFIER's)
The MibVariable object is used on input to
allow symbolic MIB table columns specification. Response values
are requested to be converted into MIB-defined type.
Note: the code below needs access to IF-MIB (e.g. IF-MIB.py) which
is installed with the pysnmp-mibs package or could be
converted manually into
pysnmp MIB module from IF-MIB text source.
from pysnmp.entity.rfc3413.oneliner import cmdgen
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
cmdgen.CommunityData('public', mpModel=0),
cmdgen.UdpTransportTarget(('localhost', 161)),
cmdgen.MibVariable('IF-MIB', 'ifDescr'),
cmdgen.MibVariable('IF-MIB', 'ifType'),
cmdgen.MibVariable('IF-MIB', 'ifMtu'),
cmdgen.MibVariable('IF-MIB', 'ifSpeed'),
cmdgen.MibVariable('IF-MIB', 'ifPhysAddress'),
lookupValues=True
)
if errorIndication:
print(errorIndication)
else:
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
)
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
|
- bulkCmd(
authData,
transportTarget,
nonRepeaters,
maxRepetitions,
*varNames,
lookupNames=False,
lookupValues=False,
lexicographicMode=False,
ignoreNonIncreasingOid=False,
maxRows=0
)
-
Perform SNMP GETBULK request and return a response or error indication.
The GETBULK request type has the same semantics as GETNEXT one except that
the latter is able to report multiple Managed Objects per each Managed Object
name passed in request.
The authData, transportTarget,
*varNames, lookupNames, lookupValues,
lexicographicMode and maxRows input parameters to the
bulkCmd method are the same as of nextCmd.
The nonRepeaters parameter indicates how many of
*varNames passed in request should be queried for a single
instance with in a request.
The maxRepetitions parameter indicates for how many instances
of Managed Objects in the rest of *varNames, besides first
nonRepeaters ones, should be queried within a single request.
The bulkCmd method returns a tuple of
errorIndication,
errorStatus,
errorIndex,
varBindTable.
having same meaning as in nextCmd method.
The following code performs SNMP GETBULK operation against a MIB subtree
- using SNMP v3
- with SNMPv3, user 'usr-sha-aes128', SHA auth, AES128 privacy
- over IPv6/UDP
- against an Agent listening at ::1 (UDP port 161)
- with values non-repeaters = 0, max-repetitions = 20
- for the SNMPv2-MIB::system subtree
- stop reading values from Agent once response names leave the scopes of
initial names (e.g. OBJECT IDENTIFIER's)
The MibVariable object is used on input to
allow symbolic MIB table columns specification.
from pysnmp.entity.rfc3413.oneliner import cmdgen
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
cmdgen.UsmUserData('usr-sha-aes128', 'authkey1', 'privkey1',
authProtocol=cmdgen.usmHMACSHAAuthProtocol,
privProtocol=cmdgen.usmAesCfb128Protocol),
cmdgen.Udp6TransportTarget(('::1', 161)),
0, 20,
cmdgen.MibVariable('SNMPv2-MIB', 'system')
)
if errorIndication:
print(errorIndication)
else:
if errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
)
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
|
2.1.1.2 Notification Originator
The Notification Originator Application is implemented within a single class:
- class NotificationOriginator([snmpContext])
-
Create a SNMP Notification Originator object.
Although instantiation of this class is cheap, in the course of its further
use, SNMP engine configuration is built and maintained though methods
invocation.
Therefore it is advised to keep and reuse NotificationOriginator instance
(or snmpEngine instance if passed as an initializer)
for as long as possible within user applicatin.
All notifications are sent by in invocation of the following method:
- sendNotification(
authData,
transportTarget,
notifyType,
notificationType,
*varBinds
)
-
Send either unconfirmed (TRAP) or confirmed (INFORM) SNMP notification
and possibly return an error indication.
The authData and transportTarget parameters
have the same semantics as in getCmd
method.
The notifyType parameter determines the type of notification
to be generated. Supported values include "trap" for
unconfirmed notification or "inform" for a confirmed one.
The notificationType parameter indicates the kind of
event to notify Manager about in form of SMI NOTIFICATION-TYPE object
name. Either
ObjectIdentifier class
instance, its initialization value (like '1.3.6.1.6.3.1.1.5.1') or
MibVariable object can be used on input to
allow MIB symbols references.
For example, '1.3.6.1.6.3.1.1.5.1' or MibVariable('SNMPv2-MIB', 'coldStart')
specify SNMPv2-MIB::coldStart type of trap.
When sending SNMP v1 traps, the notificationType
parameter encodes both Generic and Specific trap numbers
hardwired into SNMP v1 TRAP PDU, but missing in SNMP v2c TRAP and INFORM
PDUs.
notificationType
|
GenericTrap
|
SpecificTrap
|
1.3.6.1.6.3.1.1.5.1 | coldStart(0) | 0 |
1.3.6.1.6.3.1.1.5.2 | warmStart(1) | 0 |
1.3.6.1.6.3.1.1.5.3 | linkDown(2) | 0 |
1.3.6.1.6.3.1.1.5.4 | linkUp(3) | 0 |
1.3.6.1.6.3.1.1.5.5 | authenticationFailure(4) | 0 |
1.3.6.1.6.3.1.1.5.6 | egpNeighborLoss(5) | 0 |
1.3.6.1.6.3.1.1.5.0.1 | enterpriseSpecific(6) | 1 |
1.3.6.1.6.3.1.1.5.0.999 | enterpriseSpecific(6) | 999 |
1.3.6.1.6.3.1.1.5.0.N | enterpriseSpecific(6) | N |
The *varBinds input parameter is a tuple of Managed
Objects to be passed over to Manager along with Notification. The syntax
of *varBinds is the same as in
getCmd
The sendNotification method returns an
errorIndication parameter which has the same meaning as
in getCmd method.
When sending SNMP traps to a SNMPv1 system, PDU parameters
that are present in SNMPv1 PDU but are missing in SNMPv2c PDU
are mapped one to another via special Managed Objects Inctance
values in *varBinds.
- SNMP v1 PDU enterprise parameter is passed as a value of
1.3.6.1.6.3.1.1.4.3.0 Managed Object Instance in *varBinds.
If not specified, the default value is 1.3.6.1.6.3.1.1.5. If Generic
encoded in notificationType is enterpriseSpecific,
the enterprise parameter is implicitly initialized into
notificationType value minus trailing sub-OID.
- SNMP v1 PDU agent-addr parameter is passed as a value of
1.3.6.1.6.3.18.1.3.0 Managed Object Instance in *varBinds.
- SNMP v1 PDU time-stamp parameter is passed as a value of
1.3.6.1.2.1.1.3.0 Managed Object Instance in *varBinds.
The following code sends SNMP v2c TRAP message:
- using SNMP v2c
- with community name 'public'
- over IPv4/UDP
- send TRAP notification
- with TRAP ID 'coldStart' specified as a MIB symbol
- include managed object information specified as a MIB symbol
from pysnmp.entity.rfc3413.oneliner import ntforg
ntfOrg = ntforg.NotificationOriginator()
errorIndication = ntfOrg.sendNotification(
ntforg.CommunityData('public'),
ntforg.UdpTransportTarget(('localhost', 162)),
'trap',
ntforg.MibVariable('SNMPv2-MIB', 'coldStart'),
(ntforg.MibVariable('SNMPv2-MIB', 'sysName', 0), 'new name')
)
if errorIndication:
print('Notification not sent: %s' % errorIndication)
|
To send SNMP v1 traps using standard Notification Originator
application API, one may need to pass, and possibly override some
of defaulted, SNMP v1 PDU fields that are not present as such in SNMP
v2c PDU and thus in the API.
The following example sends SNMP v1 TRAP message overriding implicit
defaults:
- using SNMP v1
- with community name 'public'
- over IPv4/UDP
- send TRAP notification
- with Generic Trap #6 (enterpriseSpecific) and Specific Trap 432
- overriding local snmpEngine's Uptime with value 12345
- overriding Agent Address with '127.0.0.1'
- overriding Enterprise OID with 1.3.6.1.4.1.20408.4.1.1.2
- include managed object information '1.3.6.1.2.1.1.1.0' = 'my system'
specified as an OID-value pair
from pysnmp.entity.rfc3413.oneliner import ntforg
from pysnmp.proto import rfc1902
ntfOrg = ntforg.NotificationOriginator()
errorIndication = ntfOrg.sendNotification(
ntforg.CommunityData('public', mpModel=0),
ntforg.UdpTransportTarget(('localhost', 162)),
'trap',
'1.3.6.1.4.1.20408.4.1.1.2.0.432',
('1.3.6.1.2.1.1.3.0', 12345),
('1.3.6.1.6.3.18.1.3.0', '127.0.0.1'),
('1.3.6.1.6.3.1.1.4.3.0', '1.3.6.1.4.1.20408.4.1.1.2'),
('1.3.6.1.2.1.1.1.0', rfc1902.OctetString('my system'))
)
if errorIndication:
print('Notification not sent: %s' % errorIndication)
|
The following code sends SNMP v2c INFORM message over SNMPv3:
- using SNMP v3
- with user 'usr-md5-des', auth: MD5, priv 3DES
- over IPv4/UDP
- send INFORM notification
- with TRAP ID 'warmStart' specified as a string OID
- include managed object information 1.3.6.1.2.1.1.5.0 = 'system name'
specified as an OID-value pair
from pysnmp.entity.rfc3413.oneliner import ntforg
from pysnmp.proto import rfc1902
ntfOrg = ntforg.NotificationOriginator()
errorIndication = ntfOrg.sendNotification(
ntforg.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
ntforg.UdpTransportTarget(('localhost', 162)),
'inform',
'1.3.6.1.6.3.1.1.5.2',
('1.3.6.1.2.1.1.5.0', rfc1902.OctetString('system name'))
)
if errorIndication:
print('Notification not sent: %s' % errorIndication)
|
2.1.2 Asynchronous One-line Applications
Asynchronous API to oneliner Applications is actually a foundation for
Synchronous version, so they're very similar.
This Asynchronous API is useful for purposes such as running multiple,
possibly different, SNMP Applications at the same time or handling other
activities inside user's program while SNMP Application is waiting for
input/output.
2.1.2.1 Asynchronous Command Generator
All Command Generator Applications are implemented within a single class:
- class AsynCommandGenerator([snmpEngine])
-
Create an asynchronous SNMP Command Generator object.
Although instantiation of this class is cheap, in the course of its further
use, SNMP engine configuration is built and maintained though methods
invocation.
Therefore it is advised to keep and reuse CommandGenerator instance
(or snmpEngine instance if passed as an initializer)
for as long as possible within user applicatin.
Methods of the AsynCommandGenerator class instances implement
specific request types. These methods are similar to those described in the
CommandGenerator class section except that
asynchronous interface uses a callback function for delivering responses.
- getCmd(
authData,
transportTarget,
varNames,
(cbFun, cbCtx),
lookupNames=False,
lookupValues=False
)
-
Prepare SNMP GET request to be dispatched. Return the
sendRequestHandle value.
The cbFun parameter is a reference to a callable object
(such as a Python function) having the following signature:
- cbFun(
sendRequestHandle,
errorIndication,
errorStatus,
errorIndex,
varBinds,
cbCtx
)
-
Where sendRequestHandle is an integer value used for matching
response to request. Its counterpart is returned on request submission by
the getCmd method.
The cbCtx parameter is a reference to the
cbCtx object being passed to getCmd
method. Its purpose is to carry opaque application's state from request
through response methods.
The errorIndication, errorStatus,
errorIndex and varBinds parameters
have the same meaning as in getCmd
method.
The authData, transportTarget,
varNames, lookupNames and
lookupValues parameters have the same meaning as in
getCmd method except that
varNames is passed as a sequence, not as individual
Managed Objects Instances names.
The getCmd method returns unique
sendRequestHandle integer value used for
matching subsequent response to this request.
The following code performs multiple, simultaneous SNMP GET operations
for multiple Managed Objects Instances to a single Agent.
Authentication information used in this example are the same for all targets.
So the GET operation is performed:
- using SNMP v2c
- with SNMPv2c community 'public'
- over IPv4/UDP
- against an Agent listening at 127.0.0.1
- for the SNMPv2-MIB::sysDescr.0, SNMPv2-MIB::sysLocation.0 and SNMPv2-MIB::sysName.0 objects
from pysnmp.entity.rfc3413.oneliner import cmdgen
def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
if errorIndication:
print(errorIndication)
return
if errorStatus:
print('%s at %s' % \
(errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex)-1] or '?')
)
return
for oid, val in varBinds:
if val is None:
print(oid.prettyPrint())
else:
print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
cmdGen = cmdgen.AsynCommandGenerator()
for varName in ( cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
cmdgen.MibVariable('SNMPv2-MIB', 'sysLocation', 0),
cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0) ):
cmdGen.getCmd(
cmdgen.CommunityData('public'),
cmdgen.UdpTransportTarget(('127.0.0.1', 161)),
(varName,),
(cbFun, None)
)
cmdGen.snmpEngine.transportDispatcher.runDispatcher()
|
It is trivial to modify the above code to make it using different
SNMP versions, credentials and query different Managed Objects Instances
per each target.
All queries are made in parallel, so with default timeout and retries
settings, the above code will terminate in 6 seconds regardless of
Agents avialability and responsiveness.
- setCmd(
authData,
transportTarget,
varBinds,
(cbFun, cbCtx),
lookupNames=False,
lookupValues=False
)
-
Prepare SNMP SET request to be dispatched. Return the
sendRequestHandle value.
The authData, transportTarget,
varNames, lookupNames and
lookupValues parameters have the same meaning as in
setCmd.
The cbFun and cbCtx parameters
have the same meaning as in
AsynCommandGenerator.getCmd method.
- nextCmd(
authData,
transportTarget,
varNames,
(cbFun, cbCtx),
lookupNames=False,
lookupValues=False
)
-
Prepare SNMP GETNEXT request to be dispatched. Return the
sendRequestHandle value.
The authData, transportTarget,
varNames, lookupNames and
lookupValues parameters have the same meaning as in
nextCmd method except that
varNames is passed as a sequence, not as individual
Managed Objects Instances names.
The cbFun and cbCtx parameters
have the same meaning as in
AsynCommandGenerator.getCmd method.
Appliction can indicate to GETNEXT SNMP Application that it is no more
interested in further information from Agent and wishes to stop by
returning True from the cbFun. Otherwise it should return
False.
The varNames parameter has the same meaning as in
CommandGenerator.nextCmd method
except that here it is passed in as a tuple.
The following code performs multiple, simultaneous SNMP GETNEXT operations
against distinct Agents identified by their transport addresses.
Authentication information and queried Managed Objects Instances used in
this example are the same for all targets. So the GETNEXT operation is performed:
- using SNMP v3
- with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols
- over IPv4/UDP
- against Agents listening at 127.0.0.1, 192.168.1.1, 10.40.1.1 (port 161)
- for the SNMPv2-MIB::system subtree
from pysnmp.entity.rfc3413.oneliner import cmdgen
def cbFun(sendRequestHandle, errorIndication, \
errorStatus, errorIndex, varBindTable, cbCtx):
if errorIndication:
print(errorIndication)
return
if errorStatus:
print('%s at %s' % \
(errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?')
)
return
for varBindRow in varBindTable:
for oid, val in varBindRow:
if val is None:
return # stop table retrieval
else:
print('%s = %s' % (oid.prettyPrint(), val.prettyPrint()))
return True # continue table retrieval
cmdGen = cmdgen.AsynCommandGenerator()
for transportTarget in ( cmdgen.UdpTransportTarget(('127.0.0.1', 161)),
cmdgen.UdpTransportTarget(('192.168.1.1', 161)),
cmdgen.UdpTransportTarget(('10.40.1.1', 161)) ):
cmdGen.nextCmd(
cmdgen.UsmUserData('usr-md5-des', 'authkey1', 'privkey1'),
transportTarget,
( cmdgen.MibVariable('SNMPv2-MIB', 'system'), ),
(cbFun, None)
)
cmdGen.snmpEngine.transportDispatcher.runDispatcher()
|
- bulkCmd(
authData,
transportTarget,
nonRepeaters,
maxRepetitions,
varNames,
(cbFun, cbCtx),
lookupNames=False,
lookupValues=False
)
-
Prepare SNMP GETBULK request to be dispatched. Return the
sendRequestHandle value.
The authData, transportTarget,
nonRepeaters, maxRepetitions
varNames, lookupNames and
lookupValues parameters have the same meaning as in
bulkCmd method except that
varNames is passed as a sequence, not as individual
Managed Objects Instances names.
The cbFun and cbCtx parameters
have the same meaning as in
AsynCommandGenerator.nextCmd method.
After one or more requests have been submitted by calling one or more
of the methods above, Transport Dispatcher must be invoked to get SNMP
engine running. This is done by calling:
-
asynCommandGenerator.snmpEngine.transportDispatcher.runDispatcher
()
-
Where asynCommandGenerator is
AsynCommandGenerator class instance.
The runDispatcher() method terminates when no pending requests
left for running Applications.
2.1.2.2 Asynchronous Notification Originator
The Notification Originator Application is implemented within a single class:
- class AsynNotificationOriginator([snmpContext])
-
Create an asynchronous SNMP Notification Originator object.
The only method of AsynNotificationOriginator class is
similar to that described in the
NotificationOriginator class section except that asynchronous interface
uses a callback function for delivery confirmation when confirmed notification
are used.
- sendNotification(
authData,
transportTarget,
notifyType,
notificationType,
varBinds,
(cbFun, cbCtx)
)
-
Prepare SNMP TRAP or INFORM notification to be dispatched. Return the
sendRequestHandle value.
The cbFun parameter is a reference to a callable object
(such as Python function) that takes the following parameters:
- cbFun(
sendRequestHandle,
errorIndication,
cbCtx
)
-
Where the sendRequestHandle, errorIndication
and cbCtx parameters have the same meaning as in
callback function in
AsynCommandGenerator.getCmd method.
The cbCtx parameter has the same meaning as in
AsynCommandGenerator.getCmd method.
The notifyType, notificationType and
varBinds parameters have the same meaning as in
NotificationOriginator.sendNotification method
except that here it is passed in as a tuple.
The sendNotification method returns unique
sendRequestHandle integer value used for
matching subsequent delivery confirmation response to arbitrary notification.
After one or more notifications have been submitted by calling the
sendNotification method, Transport Dispatcher must be
invoked to get SNMP engine running. This is done by calling:
-
asynNotificationOriginator.snmpEngine.transportDispatcher.runDispatcher
()
-
Where asynNotificationOriginator is
AsynNotificationOriginator class instance.
The runDispatcher() method terminates when no unconfirmed
notifications left for running Applications.
The following code sends multiple, simultaneous SNMP INFORM messages
to multiple Managers. Authentication information used in this example is
the same for all targets.
- using SNMP v2c
- with SNMPv2c community 'public'
- over IPv4/UDP
- against Managers listening at 127.0.0.1, 127.0.0.2, 127.0.0.3 (port 162)
from pysnmp.entity.rfc3413.oneliner import ntforg
from pysnmp.proto import rfc1902
def cbFun(sendRequestHandle, errorIndication, cbCtx):
if errorIndication:
print(errorIndication)
else:
print('INFORM %s delivered' % sendRequestHandle)
ntfOrg = ntforg.AsynNotificationOriginator()
for target in ( ntforg.UdpTransportTarget(('127.0.0.1', 162)),
ntforg.UdpTransportTarget(('127.0.0.2', 162)),
ntforg.UdpTransportTarget(('127.0.0.3', 162)) ):
ntfOrg.sendNotification(
ntforg.CommunityData('public'),
target,
'inform',
ntforg.MibVariable('SNMPv2-MIB', 'coldStart'),
( ('1.3.6.1.2.1.1.5.0', rfc1902.OctetString('system name')), ),
(cbFun, None)
)
ntfOrg.snmpEngine.transportDispatcher.runDispatcher()
|
The above script terminates as all queries are either acknowledged
or timed out. With default timeout and retries settings, this will happen
in no longer than 6 seconds regardless of Managers avialability and
responsiveness.
2.1.3 Security configuration
Calls to oneliner Applications API require Security Parameters and
Transport configuration objects as input parameters. These classes
serve as convenience shortcuts to SNMP engine configuration facilities
and for keeping persistent authentication/transport configuration
between SNMP engine calls.
Security Parameters object is Security Model specific.
UsmUserData class serves SNMPv3 User-Based Security
Model configuration, while CommunityData class
is used for Community-Based Security Model of SNMPv1/SNMPv2c.
- class UsmUserData(
securityName,
authKey='',
privKey='',
authProtocol=usmNoAuthProtocol,
privProtocol=usmNoPrivProtocol
)
-
Create an object holding User-Based Security Model specific configuration
parameters.
Mandatory securityName parameter is SNMPv3 USM username
passed in as a string.
Optional authKey parameter is a secret key (string typed)
used within USM for SNMP PDU authorization. Setting it to a non-empty
value implies MD5-based PDU authentication (usmHMACMD5AuthProtocol)
to take effect. Default hashing method may be changed by means of further
authProtocol parameter.
Optional privKey parameter is a secret key (string typed)
used within USM for SNMP PDU encryption. Setting it to a non-empty
value implies MD5-based PDU authentication (usmHMACMD5AuthProtocol)
and DES-based encryption (usmDESPrivProtocol) to
take effect. Default hashing and/or encryption methods may be changed by
means of further authProtocol and/or
privProtocol parameters.
Optional authProtocol parameter may be used to specify
non-default hash function algorithm. Possible values include:
- usmHMACMD5AuthProtocol -- MD5-based authentication protocol
- usmHMACSHAAuthProtocol -- SHA-based authentication protocol
- usmNoAuthProtocol -- no authentication to use
Optional privProtocol parameter may be used to specify
non-default ciphering algorithm. Possible values include:
- usmDESPrivProtocol -- DES-based encryption protocol
- usmAesCfb128Protocol -- AES128-based encryption protocol (RFC3826)
- usm3DESEDEPrivProtocol -- triple DES-based encryption protocol (Extended Security Options)
- usmAesCfb192Protocol -- AES192-based encryption protocol (Extended Security Options)
- usmAesCfb256Protocol -- AES256-based encryption protocol (Extended Security Options)
- usmNoPrivProtocol -- no encryption to use
All these symbols are defined in
pysnmp.entity.rfc3413.oneliner.cmdgen module.
- class CommunityData(
communityName,
mpModel=1
)
-
Create an object holding Community-Based Security Model specific configuration
parameters.
Mandatory communityName parameter is SNMPv1/SNMPv2c Community name
passed as a string.
Optional mpModel parameter indicates whether SNMPv2c
(mpModel=1, default) or SNMPv1 (mpModel=0) protocol should be used.
2.1.4 Transport configuration
Transport configuration object is Transport domain specific.
UdpTransportTarget class represents a remote
network endpoint of a UDP-over-IPv4 transport.
- class UdpTransportTarget(
transportAddr,
timeout=1,
retries=5
)
-
Create an object representing a network path connecting two
SNMP entities through a UDP/IPv4 socket.
Mandatory transportAddr parameter indicates remote address
in form of a tuple of FQDN, port
where FQDN is a string representing either hostname
or IPv4 address in quad-dotted form, port is an
integer.
Optional timeout and retries parameters
may be used to modify default response timeout (1 second) and number
of succesive request retries (5 times).
- class Udp6TransportTarget(
transportAddr,
timeout=1,
retries=5
)
-
Create an object representing a network path connecting two
SNMP entities through a UDP/IPv6 socket.
Mandatory transportAddr parameter indicates remote address
in form of a tuple of FQDN, port
where FQDN is a string representing either hostname
or IPv6 address in semicolon-separated form, port is an
integer.
Optional timeout and retries parameters
may be used to modify default response timeout (1 second) and number
of succesive request retries (5 times).
2.2 Managed Objects names and values
On the protocol level, a Managed Object Instance is represented by a pair
of Name and Value items collectively called a Variable-Binding.
In PySNMP oneliner API, a Managed Object Instance is represented by a
two-component sequence of two objects -- one represents Managed Object Name
or Managed Object Instance Name, and the other - Managed Object Instance
Value. The types of these objects may vary, details follow.
2.2.1 Managed Objects Names
Managed Object or Managed Object Instance Name is an instance of
ObjectName class which is derived from PyASN1
ObjectIdentifier.
In most cases, PySNMP oneliner API will automatically create an instance of
ObjectName class from its initialization value which
can be:
- a plain string of dot-separated numbers, e.g. '1.3.6.1.2.1.1.1.0'
- a tuple of integers e.g., (1, 3, 6, 1, 2, 1, 1, 1, 0)
- an instance of ObjectIdentifier class or its derivative such as ObjectName
In order to make use of additional information related to Managed Objects,
such as their human-friendly representation, associated value type, description
of intended use and other details contained in MIBs, the
MibVariable class instances may be used interchangeably
instead of ObjectName objects.
- class MibVariable(
varName
)
-
Create an object representing a varying amount of Managed Object Name
information. At the bare minimum MibVariable object
will only hold an OBJECT IDENTIFIER that identifies particular
Managed Object. However more information on Managed Object may be
gathered by PySNMP during the course of SNMP request processing.
All the extra information comes through a lookup at a MIB where particular
Managed Object is specified.
The mandatory varName argument must hold a valid
initializer for
ObjectIdentifier
kind of objects.
or
- class MibVariable(
mibName,
symName,
*indices
)
-
Create an object potentially representing all MIB information
on particular Managed Object. By the moment of instantiation
no additional information is acquired, but during the later stages
of SNMP request processing, PySNMP will attempt to lookup additional
information at the MIB named mibName for the object
registered there under name symName.
If requested MIB or symbol can not be found, the PySnmpError
exception will be thrown.
The mandatory mibName and symName
arguments refer to the names under which particular Managed Object
is specified in the MIB (e.g. 'IF-MIB' and 'ifTable' respectively).
Both parameters are Python strings.
The optional indices sequence semantics depend on the
type of MIB Object refered by mibName and
symName parameters.
- For MibTableColumn objects indices
are a sequence of Conceptual Table Instance ID in a human-friendly
form (e.g. "127.0.0.1"-indexed element of a IP-MIB::ipAdEntAddr column)
- For MibScalar objects indices
are interpreted as an sub-OBJECT IDENTIFIER
Methods of the MibVariable objects are as follows:
- getMibSymbol(
)
-
Return a sequence of mibName, symName
and indices identifying arbitrary Managed Object.
- getOid(
)
-
Return Managed Object Name in form of ObjectIdentifier object.
- getMibNode(
)
-
Return MIB information in form of a
Managed Object
identified by this particular name.
- isFullyResolved(
)
-
Return True if MIB lookup for initial initializers was
successful and complete MIB information is available.
2.2.2 Managed Objects Values
Managed Object Instance Value is an instance of some
PyASN1 class or its
SNMP-specific derivative. The latter case reflects SNMP-specific
ASN.1 sub-type.
PySNMP implementation of SNMPv3 architecture always exposes, SMIv2 definitions for
Managed Objects are always used regardless of the underlying SNMP protocol
version being talked with a peer. For instance, an SNMPv3 Manager will always
report SMIv2 types even when working to SNMPv1 Agent (which is SMIv1-compliant).
The list of Managed Object Instance Value classes follows.
- class Integer(
value
)
-
Create a SMIv2 Integer object. The value
parameter should be an integer value. Instances of this class mimic basic
properties of a Python integer. SMIv2 Integer class is derived from
PyASN1 Integer.
- class Integer32(
value
)
-
Create a SMIv2 Integer32 object. This object is similar to
Integer class instance.
- class OctetIdentifier(
value
)
-
Create a SMIv2 OctetIdentifier object.
The value
parameter could be a tuple of integer sub-IDs or a human-friendly
string form like ".1.3.6.1.3.1". SMIv2 OctetString class is derived from
PyASN1 OctetIdentifier.
- class OctetString(
value
)
-
Create a SMIv2 OctetString object. The value
parameter should be a string value. Instances of this class mimic basic
properties of a Python string. SMIv2 OctetString class is derived from
PyASN1 OctetString.
- class IpAddress(
value
)
-
Create a SMIv2 IpAddress object. The value
parameter should be an IP address expressed in quad-dotted notation (e.g.
"127.0.0.1"). SMIv2 IpAddress class is derived from
PyASN1 OctetString.
- class Counter32(
value
)
-
Create a SMIv2 Counter32 object. Besides different value
constraints, this object is similar to Integer
class instance.
- class Gauge32(
value
)
-
Create a SMIv2 Gauge32 object. Besides different value
constraints, this object is similar to Integer
class instance.
- class Unsigned32(
value
)
-
Create a SMIv2 Unsigned32 object. Besides different value
constraints, this object is similar to Integer
class instance.
- class TimeTicks(
value
)
-
Create a SMIv2 TimeTicks object. Besides different value
constraints, this object is similar to Integer
class instance.
- class Opaque(
value
)
-
Create a SMIv2 Opaque object. This object is similar to
OctetString class instance.
- class Counter64(
value
)
-
Create a SMIv2 Counter64 object. Besides different value
constraints, this object is similar to Integer
class instance.
- class Bits(
value
)
-
Create a SMIv2 Bits object. The value
parameter should be sequence of names of bits raised to one. Unmentioned
bits default to zero. The Bits class is derived from
PyASN1 OctetString.
All the above types are directly used by SNMP protocol and can be exchanged
between user application and PySNMP in the course of SNMP engine operations
through PySNMP APIs. However, by SNMP design, some additional information
on specific Managed Objects Instances value ranges and human-friendly
representation can be carried by MIBs in form of
TEXTUAL-CONVENTION SMI constructs. PySNMP implements this
feature in form of TextualConvention class which is
actually a derivative of one of the above Managed Objects Instance Value
classes so objects of these classes can be used interchangeably in all
PySNMP APIs.
For more information on SNMP Managed Value objects properties,
refer to their base classes in PyASN1
documentation.
2.3 MIB services
PySNMP supports both Manager and Agent-side operations on
Managed Objects,
including MIB lookup and custom Managed Objects implementation.
Managed Objects, implemented in
Python code, is the basis for PySNMP MIB services. Managed Objects
are collected into a pool and then managed by a
MIB builder. Both Manager and Agent
applications deal with their Managed Objects through role-specific
MIB view and
MIB instrumentation. The same
set of Managed Objects could serve both Manager and Agent purposes within
a single SNMP entity.
2.3.1 Data model for Managed Objects
In PySNMP, Managed Objects specified in MIBs
take shape of Python objects that implement various kinds of
SMIv2 definitions.
Managed Objects specified in a MIB file translate
in a one-to-one fashion into Python modules.
Automated conversion of MIB text files into Python modules can be done
through the use of smidump tool of
libsmi package
and "build-pysnmp-mib" script shipped with PySNMP.
The pysnmp.smi.mibs.SNMPv2-SMI module
implements the following classes:
- class MibScalar(
name,
syntax
)
-
A representation of a scalar Managed Object specification identified by
name with associated value of type syntax.
Objects of this kind never hold actual values, rather they serve the following
purposes:
- Logically bind Managed Object Name with Value
- Specify value type (including TEXTUAL-CONVENTION-based constraints)
- Provide human-friendly Managed Object name and value representation
The name parameter represents an
Object Identifier which can be expressed as
either a tuple of integers or tuple-like
Object Identifier class instance.
The syntax parameter represents Managed Object Instance
value type.
The MibScalar class implements the following methods:
- getName()
-
Return the name initializer an
OctetIdentifier object.
- getSyntax()
-
Return the syntax initializer which is a
PyASN1 object including its
TEXTUAL-CONVENTION
derivative. The syntax object does not carry any value, it
denotes an acceptable type specifier and may be used for cloning
compliant objects for building SNMP messages or pretty printing concrete
values.
- getUnits()
-
Return value units in form of a Python string. This is mostly used for
pretty printing things like "10 seconds", not just "10".
- getDescription()
-
Return a textual, human-readable description of the Managed Object semantics,
meaning, uses and restrictions. Since these descriptions may be quite large,
they are not loaded into memory by default. This setting can be altered
through a property of MibBuilder.
- class MibScalarInstance(
name, syntax
)
-
A representation of scalar Managed Object Instance or
Conceptual Table element
with name and associated value carried by the
syntax object. This class is a subclass of
MibScalar but, unlike
MibScalar, it represents existing Managed
Object holding a value.
The name of Managed Object Instance is a concatination
of name of a Managed Object and instance identifier.
For scalar Managed Objects, instance identifier is always a single
zero (0,). For Conceptual Table elements
instance identifier is a concatination of table indices.
The name and syntax parameters
have the same meaning as in MibScalar class.
- class MibTableColumn(
name, syntax
)
-
A representation of
Conceptual Table Column
specification with name and associated value
of type syntax. This class is a subclass of
MibScalar.
The name parameter has the same meaning as in
MibScalar class.
The syntax parameter represents
type of the value associated with
columnar Managed Object.
The MibTableColumn class implements the following
methods:
- setProtoInstance(
instanceClass
)
-
Configure MibTableColumn object to instantiate
instanceClass when creating Columnar Objects.
By default, MibScalarInstance
is instantiated.
- class MibTableRow(
name
)
-
A representation of a Conceptual Table
Row specification with name.
This class is a subclass of MibScalar although
it can't have any associated value.
The name parameter has the same meaning as in
MibScalar class.
The MibTableRow class implements the following methods:
- getInstIdFromIndices(
*indices
)
-
Compute and return Conceptual Table Column
instance identifier from *indices using MIB Table
Index definition.
Types of *indices must coerce into Table Index syntax.
- getIndicesFromInstId(
instanceId
)
-
Compute and return a tuple of Conceptual Table
Index values from Column instance identifier instanceId
using MIB Table Index definition.
The number of types of returned index values depend on MIB Table definition.
- class MibTable(
name
)
-
Represents
Conceptual Table specification
with name. This class is a subclass of
MibScalar although it can't have
any associated value.
The name parameter has the same meaning as in
MibScalar class.
The following examples explain how MIB text could be expressed in terms of
PySNMP SMI data model. First example is on a scalar:
myManagedObject = MibScalar((1, 3, 6, 1, 4, 1, 20408, 2, 1),
OctetString()).setMaxAccess("readonly")
|
Managed Object Instance can be put into a stand-alone PySNMP SMI module or
be implemented inside Agent application. Managed Object Instance will be
associated with its parent Managed Object, by the
MIB building part of PySNMP,
on the basis of their names relation.
myManagedObjectInstance = MibScalarInstance(myManagedObject.getName() + (0,),
myManagedObject.getSyntax().clone('my string'))
|
Let's consider SNMP Conceptual Table created in an "MY-MIB.py" file:
myTable = MibTable((1, 3, 6, 1, 4, 1, 20408, 2, 1))
myTableEntry = MibTableRow(myTable.getName() + (1,)).setIndexNames(
(0, "MY-MIB", "myTableIndex")
)
myTableIndex = MibTableColumn(myTableEntry.getName() + (1,), Integer())
myTableValue = MibTableColumn(myTableEntry.getName() + (2,), OctetString())
|
Populate Managed Objects table with Managed Objects Instance in the first
column.
myTableValueInstance = MibScalarInstance(myTableValue.getName() + (1,),
myTableValue.getSyntax().clone('my value'))
|
For more real-life cases, refer to modules in pysnmp.smi.mibs
sub-package.
2.3.2 MIB builder
The pythonized MIB modules are then managed by the
MibBuilder class from pysnmp.smi.builder
module.
- class MibBuilder()
-
Create MIB modules loader/evaluator/indexer.
- loadModules(
*modNames
)
-
Locate in search path and evaluate each of *modNames
through Python execfile() passing a reference to
MibBuilder class instance to module's global scope.
Evaluating modules might register their objects at
MibBuilder through
exportSymbols() call.
MIB builder would then create an in-memory index of registered MIB
objects by MIB names.
Search path is managed by the getMibPath() and
setMibPath() methods.
The loadModules method may be further invoked recursively
on dependent MIB modules import.
- unloadModules(
*modNames
)
-
Drop all references to Python objects previously created through
calling loadModules() method against [here optional]
*modNames. This method would invoke
unexportSymbols()
against MIB symbols previously registered under each of
*modNames.
Missing *modNames implies all currently loaded modules.
- importSymbols(
modName,
*symNames
)
-
Return a tuple of Managed Objects looked up by
their MIB names *symNames.
Managed Objects returned in tuple are
position-bound to *symNames parameters.
If MIB module modName is not yet loaded, the
importSymbols() method
would be invoked implicitly.
- exportSymbols(
modName,
*anonymousSyms,
**namedSyms
)
-
Register Managed Objects *anonymousSyms and/or
**namedSyms at MibBuilder within
MIB module modName scope.
Managed Objects defined in MIB are always named. These are exported using
**namedSyms parameter(s). Managed Objects Instances
don't have to have MIB names, unless Application wants to access
Managed Objects Instances by MIB name, so these may be exported through
*anonymousSyms.
- unexportSymbols(
modName,
*symNames
)
-
Drop all references to Python objects previously registered
under *symNames within modName
through exportSymbols() call.
Missing *symNames implies all symbols currently
registered within modName module.
In the following example MIB builder will be created, MIB modules
loaded up and Managed Object definition looked up by symbolic name:
>>> from pysnmp.smi import builder
>>>
>>> # create MIB builder
... mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB', 'IF-MIB')
>>>
>>> # get Managed Object definition by symbol name
... mibNode, = mibBuilder.importSymbols('SNMPv2-MIB', 'sysDescr')
>>> print(mibNode.getName())
(1, 3, 6, 1, 2, 1, 1, 1)
>>> print(repr(mibNode.getSyntax()))
DisplayString('')
>>>
|
2.3.3 MIB view controller
The following facilities are intended for Manager-side access to MIB
definitions. The pysnmp.smi.view module contains the
following items:
- class MibViewController(mibBuilder)
-
The MibViewController class instance tackles
Managed Objects,
constructed by MibBuilder, for their properties
and provide efficient/ordered access to Managed Objects properties.
Most important of these are OID names and labels.
The mibBuilder argument is an instance of
MibBuilder class.
The MibViewController class implements the following
methods:
- getNodeName(name)
-
The name parameter is
Managed Object name.
It can be either a tuple representing sub-OIDs
or Object Identifier class instance. Sub-OIDs
can be a mix of integers and string labels. For example, the following
are valid values of name:
-
(1, 3, 6, 1)
-
('iso', 'org', 'dod', 'internet')
-
('iso', 2, 'dod', 1)
-
pysnmp.proto.rfc1902.ObjectIdentifier("1.3.6.1")
The getNodeName method returns a tuple of
(oid, label, suffix)
where:
- The oid and label are tuples of sub-OIDs
of best (longest) matched Managed Object in integer and label forms
respectively.
- The suffix parameter is the unmatched, trailing part of
original name parameter.
If a Managed Object is looked up with getNodeName method
and an exact match occured, suffix would be an empty tuple.
If suffix is not empty, it indicates either an index part of
Conceptual Table instance name
(which can be further parsed into index values by
MibTableRow class methods) or
a partial Managed Object name match.
In order to distinguish MIB Table element match from a failure, see if
closest matched Managed Object oid (MIB symbol
label[-1]) is an instance of
MibTableColumn class.
If even partial match fails, the SmiError exception is
raised.
>>> from pysnmp.smi import builder, view
>>>
>>> mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB')
>>> mibViewController = view.MibViewController(mibBuilder)
>>>
>>> oid, label, suffix = mibViewController.getNodeName(
(1,3,6,1,2,'mib-2',1,'sysDescr')
)
>>> print(oid)
(1, 3, 6, 1, 2, 1, 1, 1)
>>> print(label)
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>> print(suffix)
()
|
- getNextNodeName(
name, modName=''
)
-
The getNextNodeName method works the same as
getNodeName but it deals
with Managed Object whose name appears to be next to the name
given on input.
The modName parameter is MIB module name as seen by
MibBuilder. Use this parameter to restrict
by-name to particular MIB module's
scope.
- getFirstNodeName(modName='')
-
The getFirstNodeName method works the same as
getNodeName but it returns
Managed Object whose name appears to be the first among others within
MIB module modName.
If no modName is given, the whole OID namespace is assumed.
- getNodeLocation(name)
-
The getNodeLocation method returns MIB location of
Managed Object by OID name as a tuple of
(modName, mibName, suffix).
The modName and mibName parameters are
as used in MibBuilder interface. The
suffix parameter is as described in
getNodeName() method.
>>> from pysnmp.smi import builder, view
>>>
>>> mibBuilder = builder.MibBuilder().loadModules('SNMPv2-MIB')
>>> mibViewController = view.MibViewController(mibBuilder)
>>>
>>> modName, symName, suffix = mibViewController.getNodeLocation(
(1,3,6,1,2,1,1,1,123)
)
>>> print(modName)
SNMPv2-MIB
>>> print(symName)
sysDescr
>>> print(suffix)
(123,)
|
2.3.4 Implementing Managed Objects Instances
The following chapter explains SNMP Agent-controlled Managed Object
Instances to real-life objects mapping.
SNMP defines four types of operations on Managed Objects Instances.
For scalars, these are:
- Get Managed Object Instance value (though SNMP GET request)
- Modify Managed Object Instance value (though SNMP SET request)
Conceptual Tables additionaly support:
- Table row creation (through SNMP SET against a special-purpose
RowStatus column instance)
- Table row removal (similary, through SNMP SET against RowStatus
column instance)
PySNMP Managed Objects Instances are implemented by the
MibScalarInstance objects
while a value associated with Managed Object Instance is
represented by its syntax initialization parameter.
There are two distinct approaches to Managed Objects Instances
implementation in PySNMP. The first one is simpler to use
but it only works for relatively static Managed Objects. The other
is universal but it is more complex to deal with.
2.3.4.1 Associated value gatewaying
This method only works for scalars and static tables (meaning no row
creation and deletion is performed through SNMP). Also, it is not
safe with this method to modify dependent values though a single
request as failed modification won't roll back others in the bulk.
Whenever SNMP Agent receives read or modification request against arbitrary
Managed Object Instance, it ends up clone()'ing syntax
parameter of MibScalarInstance object.
Read queries (e.g. GET/GETNEXT/GETBULK) trigger clone method
invocation without passing it new value, while new value will be
fed to the clone method on modification request.
This value-based gatewaying method works by listening on the clone()
method of MibScalarInstance associated value thus fetching current
or applying new state of some outer system represented by arbitrary Managed
Object Instance.
Consider SMI-to-filesystem gateway for example, where a Managed Object
Instance would represent particular file contents. File contents would
be solely dependent on SNMP updates.
class MyFile(OctetString):
def clone(self, value=None):
if value is not None:
# SNMP SET
open('/tmp/myfile', 'w').write(value)
# SNMP S/GET*
return OctetString.clone(self, open('/tmp/myfile', 'r').read())
mibBuilder.exportSymbols(
'MYFILE-MIB', MibScalarInstance((1, 3, 6, 1, 4, 1, 20408, 1), MyFile())
)
|
A variation of this through-value SMI gatewaying method would be for a
third-party system to keep Managed Object Instance value synchronized
with system's current state. Take file size monitor for instance -- the
following code would be run periodically to measure most recent file size
and re-build its SMI projection:
myManagedObjectInstance = MibScalarInstance(
(1, 3, 6, 1, 4, 1, 20408, 1), Integer(os.stat('/var/adm/messages')[6])
)
mibBuilder.exportSymbols(
'FILESIZE-MIB', myManagedObjectInstance=myManagedObjectInstance
)
|
2.3.4.2 Tapping on Management Instrumentation API
This is a generic SMI Managed Objects Instances to real-life objects
mapping method. It works for scalars and tables of any origin, though,
programming with it involves customization of PySNMP SMI base classes
what adds up to usage complexity.
A single SNMP request may invoke an operation on multiple Managed
Objects Instances. In SNMP design, it must either succeed on all
Managed Objects Instances or be rolled back and reported as a
failure otherwise.
SNMP engine talks to its Managed Objects through a protocol which is
comprised from a collection of API methods (further refered to as
Management Instrumentation API), implemented by
Managed Objects classes
and a definite sequence of their invocation. Default handlers implemented
in Managed Objects classes read/modify/create the syntax
parameter, passed on instantiation, to
MibScalarInstance objects for scalars
and MibTableColumn for tables. The essence
of this Management Instrumentation Tapping technique is to listen on
Management Instrumentation API methods for gaining control over particular
Managed Object at request processing points.
Formal parameters of Management Instrumentation API methods don't make
much sense to custom implementation, so they are partially documented here and,
in most cases, should be blindly passed down as-is to the overloaded
method to not to interfere with behind-the-scene SMI workings.
Value read methods implemented by
Managed Objects and
invoked by SNMP engine in response to SNMP GET/GETNEXT/GETBULK requests
are:
- readTest(
*args
)
-
The readTest method is invoked by SNMP engine prior to
performing actual Managed Object Instance value read to give
implementation a chance to ensure that subsequent value read is likely
to succeed.
- readGet(
*args
)
-
The readGet method is invoked by SNMP engine to fetch
Managed Object Instance's value. This method must return a tuple
of (name, value) which is
returned by overloaded method invocation. Custom implementation
may replace the value part by its own version taken
from third-party sources.
- readTestNext(
*args
)
-
The readTestNext method is invoked by SNMP engine prior
to performing actual Managed Object Instance value read to give
implementation a chance to ensure that subsequent value read is likely
to succeed.
- readGetNext(
*args
)
-
The readGetNext method is invoked by SNMP engine
to fetch Managed Object Instance's value. This method must return a tuple
of (name, value) which is returned by
overloaded method invocation. Custom implementation may replace the
value part by its own version taken from third-party
sources.
The following is a re-implementation of file size monitor:
class FileWatcherInstance(MibScalarInstance):
def readTest(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.readTest(self, name, val, idx, (acFun, acCtx))
try:
os.stat('/var/adm/messages')
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def readGet(self, name, val, idx, (acFun, acCtx)):
name, val = MibScalarInstance.readGet(self, name, val, idx, (acFun, acCtx))
try:
return name, val.clone(os.stat('/var/adm/messages')[6])
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
mibBuilder.exportSymbols(
'FILESIZE-MIB', FileWatcherInstance((1,3,6,1,4,1,20408,1), Integer())
)
|
Value modification methods implemented by
Managed Objects and
invoked by SNMP engine in response to SNMP SET request:
- writeTest(
name,
value,
*args
)
-
The writeTest method is invoked by SNMP engine prior to
performing actual Managed Object Instance value modification to give
implementation a chance to ensure that subsequent value modification
is likely to succeed.
Upon successful completion, this method brings Managed Object Instance into
a state of pending modification which ends through either calling
writeCleanup() on success or
writeUndo() on failure.
- writeCommit(
*args
)
-
The writeCommit method is invoked by SNMP engine by way of
request processing in attempt to apply pending value,
previously passed to Managed Object Instance through
writeTest method. Custom implementation may
attempt to apply pending value to a third-party system.
- writeCleanup(
*args
)
-
The writeCleanup method is invoked by SNMP engine by way of
request processing to bring Managed Object Instance out of
pending value modification state. Custom implementation may attempt to
bring a third-party system out of value modification state.
- writeUndo(
*args
)
-
The writeUndo method is invoked by SNMP engine by way of
request processing to drop the value applied
to Managed Object Instance by the previously called
writeCommit() method and re-assign previous value.
This method also brings Managed Object Instance out of pending value
modification state. Custom implementation may attempt to bring a
third-party system out of value modification state.
The following is a re-implementation of SMI-to-filesystem binding for
file modification:
class MyFileInstance(MibScalarInstance):
def writeTest(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.writeTest(self, name, val, idx, (acFun, acCtx))
try:
open('/tmp/myfile.new', 'w').write(val)
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def writeCommit(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.writeCommit(self, name, val, idx, (acFun, acCtx))
try:
os.rename('/tmp/myfile', '/tmp/myfile.old')
os.rename('/tmp/myfile.new', /tmp/myfile')
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def writeCleanup(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.writeCleanup(self, name, val, idx, (acFun, acCtx))
try:
os.unlink('/tmp/myfile.old')
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def writeUndo(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.writeUndo(self, name, val, idx, (acFun, acCtx))
try:
os.rename('/tmp/myfile.old', '/tmp/myfile')
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
mibBuilder.exportSymbols(
'MYFILE-MIB', MyFileInstance((1,3,6,1,4,1,20408,1), OctetString())
)
|
Table row creation methods implemented by
Managed Objects and
invoked by SNMP engine in response to SNMP SET request against
a non-existent or SNMPv2-TC::RowStatus type Table Column
Instance (table cell) object:
- createTest(
name,
value,
*args
)
-
The createTest method is invoked by SNMP engine as a
first step of Columnar Instance (e.g. Managed Object Instance) creation
to make sure the column instance could be created and optionally supplied
value is good. Custom implementation may attempt to create a new object
at a third-party system.
The name and value parameters hold
OID/value pair as arrived in request.
Upon successful completion, this method brings Managed Object Instance into
a state of pending creation which ends through either calling
createCleanup() on success or
createUndo() on failure.
- createCommit(
*args
)
-
The createCommit method is invoked by SNMP engine by way
of Columnar Object creation to indicate that newly created Columnar Object
has been brough on-line and in attempt to apply [optional] pending
value, as passed through
createTest() method. Custom implementation may
bring previously created object on-line at a third-party system.
- createCleanup(
*args
)
-
The createCleanup method is invoked by SNMP engine by way
of Columnar Instance creation to indicate a success. Custom implementation
may pass this information to a third-party system.
- createUndo(
*args
)
-
The createUndo method is invoked by SNMP engine by way
of Columnar Instance creation to indicate a failure. Custom implementation
may destroy previously created object at a third-party system.
The following is a SMI-to-filesystem binding for file creation:
class MyFileInstance(MibScalarInstance):
def createTest(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.createTest(self, name, val, idx, (acFun, acCtx))
# Build path to file to create from column index
myFileEntry, = mibBuilder.importSymbols('MYFILE-MIB', 'myFileEntry')
indices = myFileEntry.getIndicesFromInstId(name[myFileEntry.getName()+1:])
self.__myFile = apply(os.path.join, indices)
try:
open('%s.new' % self.__myFile, 'w')
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def createCommit(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.createCommit(self, name, val, idx, (acFun, acCtx))
try:
os.rename(self.__myFile, '%s.old' % self.__myFile)
os.rename('%s.new' % self.__myFile, self.__myFile)
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def createCleanup(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.createCleanup(self, name, val, idx, (acFun, acCtx))
try:
os.unlink('%s.old' % self.__myFile)
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
def createUndo(self, name, val, idx, (acFun, acCtx)):
MibScalarInstance.createUndo(self, name, val, idx, (acFun, acCtx))
try:
os.rename('%s.old' % self.__myFile, self.__myFile)
except StandardError, why:
raise ResourceUnavailableError(idx=idx, name=name)
# Register custom Managed Object Instance at Column
myFileColumn, = mibBuilder.importSymbols('MYFILE-MIB', 'myFileColumn')
myFileColumn.setProtoInstance(MyFileInstance)
|
In the above example, it is assumed that there is a MIB module named
MYFILE-MIB where
a MIB table column named
myFileColumn is defined.
Appendixies
ASN.1 standard
SNMP relies on Abstract Syntax Notation One (ASN.1)
ITU-T standard
. It is actually a family of standards targeting network systems
interoperability and protocols development automation.
In theory, ASN.1 technology provides a complete solution for protocol
development: new protocol could be expressed in terms of
data structures described in a specialized formal language.
The ASN.1 notation is designed purely for data description. All data
structures there are based on a small set of elementary data types,
such as INTEGER or SEQUENCE OF some other types.
Whenever protocol designer wants to define a more precise, narrow set of
valid values for a field, a subtype can be created from a base ASN.1
type or another subtype by tearing up a constraint on various data
properties to parent ASN.1 type. For example, a subtype of in INTEGER may
allow only arbitrary values of an integer.
Another way to create a subtype from existing type is to add
or replace ASN.1 tag, which serves like an ID for a type. In this
new type has all the same properties of its parent type but is now known
under a different name.
Once something gets expressed in ASN.1 notation, it could then be
automatically translated into a variety of platform-specific implementations.
They are often take shape of a program written in some common programming
language like C or Python.
This is where the major feature of ASN.1 emerges. ASN.1 text could be
automatically compiled into a high-quality code, that handles all the
nightmares of platform-specifics, virtually for free. This code would
handle byte-ordering and value ranges, data structures validations and
consistency issues.
But the most useful feature is its ability to represent data in a way
suitable for transmission over a communication medium. This is called
encoding in ASN.1, and also known as
concrete or transfer syntax in computer science.
SNMP uses these features of ASN.1 for handling Managed Objects and guiding
protocol operations.
Object Identifier
This technique is a simple, unambiguous, decentralized and extensible
method of naming anything. It was developed within ASN.1 standard as
one of its build-in data types.
An Object Identifier consists of a sequence of integers. Each integer in
this sequence maps to a node in a tree, so iterating an OID traverses this
tree from root to leaf, forming a branch. Nodes in OID tree hold a group of
conceptually related objects. Nodes become more specific from root to
leaves. Sub-trees, or parts of OID space, often become a courtesy of various
organizations and individuals.
OIDs are conventionally written as a dot-separated sequence of integers, from
left to right as from root to leaves. For example, .1.3.6.1 is an arbitrary
OID.
For the purpose of making OIDs human-readable, integers in OIDs
(AKA sub-OIDs) can be replaced with a textual labels. Consider
.org.iso.dod.internet as a labeled version of the previous example.
The numeric and labeled OID representations are invariant and may mix
within a single OID.
ASN.1 data encoding
For several entities to exchange ASN.1 data items some common transmission
protocol is needed. This protocol would have to be able to represent
ASN.1 values in a platform-native way. This might require handling hardware
and/or software specific issues such as varying integer sizes, byte ordering,
character encoding and so
on.
Besides data representation issues, this communication protocol would
have to break up data being transmitted into small chunks. The reason
is that most data transmission technologies handle only a few bits in
a channel at any moment of time. After buffering and packing up few bits
into larger chunks, most link-level protocols still handle information
in small grains. Typical measurement is eight bit or octet.
For all the reasons mentioned above, ASN.1 family of standards
suggests several methods of two-way ASN.1 data conversion protocols.
They are sometimes referred to as data encoding or
serialization.
SNMP uses somewhat restricted flavor of Basic Encoding Rules
(BER) for its ASN.1 data serialization purposes. The SNMP-specific
restrictions make BER encoding deterministic -- with these restrictions
applied, there is a one-to-one mapping between ASN.1 value and octet-stream
produced by BER encoder. Determinism in encoding makes it possible for
trivial SNMP entities to reduce their SNMP engine implementation to opaque
octet-streams manipulations.
|