API References#

Dealing with many SNMP features may quickly overwhelm developers who aim at a quick and trivial task, PySNMP employs a layered architecture approach where the topmost programming API tries to be as simple as possible to allow immediate solutions for most common use cases.

It will let you perform SNMP GET/SET/WALK and TRAP/INFORM operations by pasting code snippets from PySNMP documentation and sample scripts right into your Python interactive session.

Most of SNMP operations involve packet exchange over network. PySNMP is shipped with asyncio binding that let you run PySNMP in parallel with other tasks your application may perform.

Synchronous SNMP#

Most simple and straightforward way to use PySNMP is by employing its Synchronous, blocking API. It’s also the default API offered by users on pysnmp.hlapi sub-package import.

Warning

Completely deprecated in PySNMP 6.2 release.

Asynchronous: asyncio#

The asyncio module first appeared in standard library since Python 3.3 (in provisional basis). Its main design feature is that it makes asynchronous code looking like synchronous one. That greatly simplifies development and maintenance.

Command Generator

Notification Originator

Transport Configuration#

The following shortcut classes convey configuration information to SNMP engine’s Local Configuration Datastore (RFC 2271#section-3.4.2) as well as to underlying socket API. Once committed to LCD, SNMP engine saves its configuration for the lifetime of SNMP engine object.

class pysnmp.hlapi.asyncio.UdpTransportTarget(transportAddr: Tuple, timeout: float = 1, retries: int = 5, tagList=b'')#

Creates UDP/IPv4 configuration entry and initialize socket API if needed.

This object can be used for adding new entries to Local Configuration Datastore (LCD) managed by SnmpEngine class instance.

See RFC 1906#section-3 for more information on the UDP transport mapping.

Parameters:
  • transportAddr (tuple) – Indicates remote address in Python socket module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv4 address in quad-dotted form, port is an integer.

  • timeout (int) – Response timeout in seconds.

  • retries (int) – Maximum number of request retries, 0 retries means just a single request.

  • tagList (str) – Arbitrary string that contains a list of tag values which are used to select target addresses for a particular operation (RFC 3413#section-4.1.4).

Examples

>>> from pysnmp.hlapi.asyncio import UdpTransportTarget
>>> UdpTransportTarget(('demo.pysnmp.com', 161))
UdpTransportTarget(('195.218.195.228', 161), timeout=1, retries=5, tagList='')
>>>
setLocalAddress(iface)#

Set source address.

Parameters:

iface (tuple) – Indicates network address of a local interface from which SNMP packets will be originated. Format is the same as of transportAddress.

Returns:

self

class pysnmp.hlapi.asyncio.Udp6TransportTarget(transportAddr: Tuple, timeout: float = 1, retries: int = 5, tagList=b'')#

Creates UDP/IPv6 configuration entry and initialize socket API if needed.

This object can be used by AsyncCommandGenerator or AsyncNotificationOriginator and their derevatives for adding new entries to Local Configuration Datastore (LCD) managed by SnmpEngine class instance.

See RFC 1906#section-3, RFC 2851#section-4 for more information on the UDP and IPv6 transport mapping.

Parameters:
  • transportAddr (tuple) – Indicates remote address in Python socket module format which is a tuple of FQDN, port where FQDN is a string representing either hostname or IPv6 address in one of three conventional forms (RFC 1924#section-3), port is an integer.

  • timeout (int) – Response timeout in seconds.

  • retries (int) – Maximum number of request retries, 0 retries means just a single request.

  • tagList (str) – Arbitrary string that contains a list of tag values which are used to select target addresses for a particular operation (RFC 3413#section-4.1.4).

Examples

>>> from pysnmp.hlapi.asyncio import Udp6TransportTarget
>>> Udp6TransportTarget(('google.com', 161))
Udp6TransportTarget(('2a00:1450:4014:80a::100e', 161), timeout=1, retries=5, tagList='')
>>> Udp6TransportTarget(('FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 161))
Udp6TransportTarget(('fedc:ba98:7654:3210:fedc:ba98:7654:3210', 161), timeout=1, retries=5, tagList='')
>>> Udp6TransportTarget(('1080:0:0:0:8:800:200C:417A', 161))
Udp6TransportTarget(('1080::8:800:200c:417a', 161), timeout=1, retries=5, tagList='')
>>> Udp6TransportTarget(('::0', 161))
Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList='')
>>> Udp6TransportTarget(('::', 161))
Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList='')
>>>
setLocalAddress(iface)#

Set source address.

Parameters:

iface (tuple) – Indicates network address of a local interface from which SNMP packets will be originated. Format is the same as of transportAddress.

Returns:

self

SNMP Engine#

SNMP Engine is a central, stateful object used by all SNMP v3 subsystems. Calls to high-level Applications API also consume SNMP Engine object on input.

Security Parameters#

Calls to high-level Applications API consume Security Parameters configuration object on input. The shortcut classes described in this section convey configuration information to SNMP engine’s Local Configuration Datastore (RFC 2271#section-3.4.2). Once committed to LCD, SNMP engine saves its configuration for the lifetime of SNMP engine object.

Community-Based#

Security Parameters object is Security Model specific. The CommunityData class is used for configuring Community-Based Security Model of SNMPv1/SNMPv2c.

User-Based#

The UsmUserData class provides SNMPv3 User-Based Security Model configuration for SNMP v3 systems.

Authentication protocol identifiers

Privacy (encryption) protocol identifiers

Key material types

Note

SNMP authentication and encryption keys must be at least 8 and at most 32 octets long.

Transport configuration is I/O framework specific and is described in respective sections.

SNMP Context#

SNMP engine may serve several instances of the same MIB within possibly multiple SNMP entities. SNMP context is a tool for unambiguously identifying a collection of MIB variables behind the SNMP engine. See RFC 3411#section-3.3.1 for details.

Note

The SNMP context information is not tied to SNMPv3/USM user, but it is transferred in SNMPv3 message header.

Legacy SNMPv1/v2c protocols do not accommodate the SNMP context information at all.

To fit legacy SNMPv1/SNMPv2c systems into unified SNMPv3 architecture, the mapping procedure is introduced by RFC 2576#section-5.1 which essentially lets you first configure and then supply the missing items (e.g. contextName, contextEngineId and other) to the upper layers of SNMP stack based on SNMPv1/v2c communityName and transport endpoint.

The SNMP context information necessary for this mapping procedure to operate is supplied through the CommunityData object.

MIB Services#

MIB Variables#

SNMP MIB variable is identified by an OBJECT IDENTIFIER (OID) and is accompanied by a value belonging to one of SNMP types (RFC 1902#section-2). This pair is collectively called a variable-binding in SNMP parlance.

The rfc1902 module implements RFC 1902#section-2 MACRO definitions.

class pysnmp.smi.rfc1902.ObjectIdentity(*args, **kwargs)#

Create an object representing MIB variable ID.

At the protocol level, MIB variable is only identified by an OID. However, when interacting with humans, MIB variable can also be referred to by its MIB name. The ObjectIdentity class supports various forms of MIB variable identification, providing automatic conversion from one to others. At the same time ObjectIdentity objects behave like tuples of py:obj:int sub-OIDs.

See RFC 1902#section-2 for more information on OBJECT-IDENTITY SMI definitions.

Parameters:

args – initial MIB variable identity. Recognized variants:

  • single tuple or integers representing OID

  • single str representing OID in dot-separated integers form

  • single str representing MIB variable in dot-separated labels form

  • single str representing MIB name. First variable defined in MIB is assumed.

  • pair of str representing MIB name and variable name

  • pair of str representing MIB name and variable name followed by an arbitrary number of str and/or int values representing MIB variable instance identification.

Other Parameters:

kwargs – MIB resolution options(object):

  • whenever only MIB name is given, resolve into last variable defined in MIB if last=True. Otherwise resolves to first variable (default).

Notes

Actual conversion between MIB variable representation formats occurs upon resolveWithMib() invocation.

Examples

>>> from pysnmp.smi.rfc1902 import ObjectIdentity
>>> ObjectIdentity((1, 3, 6, 1, 2, 1, 1, 1, 0))
ObjectIdentity((1, 3, 6, 1, 2, 1, 1, 1, 0))
>>> ObjectIdentity('1.3.6.1.2.1.1.1.0')
ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0')
ObjectIdentity('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0')
>>> ObjectIdentity('SNMPv2-MIB', 'system')
ObjectIdentity('SNMPv2-MIB', 'system')
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> ObjectIdentity('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123)
ObjectIdentity('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123)
getMibSymbol()#

Returns MIB variable symbolic identification.

Returns:

  • str – MIB module name

  • str – MIB variable symbolic name

  • ObjectName – class instance representing MIB variable instance index.

Raises:

SmiError – If MIB variable conversion has not been performed.

Examples

>>> objectIdentity = ObjectIdentity('1.3.6.1.2.1.1.1.0')
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
>>>
getOid()#

Returns OID identifying MIB variable.

Returns:

ObjectName – full OID identifying MIB variable including possible index part.

Raises:

SmiError – If MIB variable conversion has not been performed.

Examples

>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
ObjectName('1.3.6.1.2.1.1.1.0')
>>>
getLabel()#

Returns symbolic path to this MIB variable.

Meaning a sequence of symbolic identifications for each of parent MIB objects in MIB tree.

Returns:

tuple – sequence of names of nodes in a MIB tree from the top of the tree towards this MIB variable.

Raises:

SmiError – If MIB variable conversion has not been performed.

Notes

Returned sequence may not contain full path to this MIB variable if some symbols are now known at the moment of MIB look up.

Examples

>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)
>>> objectIdentity.resolveWithMib(mibViewController)
>>> objectIdentity.getOid()
('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr')
>>>
addAsn1MibSource(*asn1Sources, **kwargs)#

Adds path to a repository to search ASN.1 MIB files.

Parameters:

*asn1Sources – one or more URL in form of str identifying local or remote ASN.1 MIB repositories. Path must include the @mib@ component which will be replaced with MIB module name at the time of search.

Returns:

ObjectIdentity – reference to itself

Notes

Please refer to HttpReader classes for in-depth information on ASN.1 MIB lookup.

Examples

>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addAsn1MibSource('https://mibs.pysnmp.com/asn1/@mib@')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
addMibSource(*mibSources)#

Adds path to repository to search PySNMP MIB files.

Parameters:

*mibSources – one or more paths to search or Python package names to import and search for PySNMP MIB modules.

Returns:

ObjectIdentity – reference to itself

Notes

Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the mibdump.py tool.

Examples

>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
loadMibs(*modNames)#

Schedules search and load of given MIB modules.

Parameters:

*modNames – one or more MIB module names to load up and use for MIB variables resolution purposes.

Returns:

ObjectIdentity – reference to itself

Examples

>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').loadMibs('IF-MIB', 'TCP-MIB')
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
resolveWithMib(mibViewController, ignoreErrors=True)#

Perform MIB variable ID conversion.

Parameters:

mibViewController (MibViewController) – class instance representing MIB browsing functionality.

Other Parameters:

ignoreErrors (bool) – If True (default), ignore MIB object name casting failures if possible.

Returns:

ObjectIdentity – reference to itself

Raises:

SmiError – In case of fatal MIB hanling errora

Notes

Calling this method might cause the following sequence of events (exact details depends on many factors):

  • ASN.1 MIB file downloaded and handed over to MibCompiler for conversion into Python MIB module (based on pysnmp classes)

  • Python MIB module is imported by SNMP engine, internal indices created

  • MibViewController looks up the rest of MIB identification information based on whatever information is already available, ObjectIdentity class instance gets updated and ready for further use.

Examples

>>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>> objectIdentity.resolveWithMib(mibViewController)
ObjectIdentity('SNMPv2-MIB', 'sysDescr')
>>>
class pysnmp.smi.rfc1902.ObjectType(objectIdentity, objectSyntax=<Null value object, tagSet <TagSet object, tags 0:0:5>, subtypeSpec <ConstraintsIntersection object, consts <SingleValueConstraint object, consts b''>>, encoding iso-8859-1, payload []>)#

Create an object representing MIB variable.

Instances of ObjectType class are containers incorporating ObjectIdentity class instance (identifying MIB variable) and optional value belonging to one of SNMP types (RFC 1902).

Typical MIB variable is defined like this (from SNMPv2-MIB.txt):

sysDescr OBJECT-TYPE
    SYNTAX      DisplayString (SIZE (0..255))
    MAX-ACCESS  read-only
    STATUS      current
    DESCRIPTION
            "A textual description of the entity.  This value should..."
    ::= { system 1 }

Corresponding ObjectType instantiation would look like this:

ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386 box')

In order to behave like SNMP variable-binding (RFC 1157#section-4.1.1), ObjectType objects also support sequence protocol addressing objectIdentity as its 0-th element and objectSyntax as 1-st.

See RFC 1902#section-2 for more information on OBJECT-TYPE SMI definitions.

Parameters:
  • objectIdentity (ObjectIdentity) – Class instance representing MIB variable identification.

  • objectSyntax – Represents a value associated with this MIB variable. Values of built-in Python types will be automatically converted into SNMP object as specified in OBJECT-TYPE->SYNTAX field.

Notes

Actual conversion between MIB variable representation formats occurs upon resolveWithMib() invocation.

Examples

>>> from pysnmp.smi.rfc1902 import *
>>> ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), Null(''))
>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')
addAsn1MibSource(*asn1Sources, **kwargs)#

Adds path to a repository to search ASN.1 MIB files.

Parameters:

*asn1Sources – one or more URL in form of str identifying local or remote ASN.1 MIB repositories. Path must include the @mib@ component which will be replaced with MIB module name at the time of search.

Returns:

ObjectType – reference to itself

Notes

Please refer to FileReader and HttpReader classes for in-depth information on ASN.1 MIB lookup.

Examples

>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).addAsn1MibSource('https://mibs.pysnmp.com/asn1/@mib@')
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))
>>>
addMibSource(*mibSources)#

Adds path to repository to search PySNMP MIB files.

Parameters:

*mibSources – one or more paths to search or Python package names to import and search for PySNMP MIB modules.

Returns:

ObjectType – reference to itself

Notes

Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the mibdump.py tool.

Examples

>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))
>>>
loadMibs(*modNames)#

Schedules search and load of given MIB modules.

Parameters:

*modNames – one or more MIB module names to load up and use for MIB variables resolution purposes.

Returns:

ObjectType – reference to itself

Examples

>>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).loadMibs('IF-MIB', 'TCP-MIB')
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'))
>>>
resolveWithMib(mibViewController, ignoreErrors=True)#

Perform MIB variable ID and associated value conversion.

Parameters:

mibViewController (MibViewController) – class instance representing MIB browsing functionality.

Other Parameters:

ignoreErrors (bool) – If True (default), ignore MIB object name or value casting failures if possible.

Returns:

ObjectType – reference to itself

Raises:

SmiError – In case of fatal MIB hanling errora

Notes

Calling this method involves resolveWithMib() method invocation.

Examples

>>> from pysmi.hlapi.asyncio import varbinds
>>> mibViewController = varbinds.AbstractVarBinds.getMibViewController( engine )
>>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386')
>>> objectType.resolveWithMib(mibViewController)
ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), DisplayString('Linux i386'))
>>> str(objectType)
'SNMPv2-MIB::sysDescr."0" = Linux i386'
>>>

MIB Notification Types#

SNMP Notifications are enumerated and imply including certain set of MIB variables. Notification Originator applications refer to MIBs for MIB notifications through NOTIFICATION-TYPE ASN.1 macro. It conveys a set of MIB variables to be gathered and reported in SNMP Notification. The rfc1902 module implements RFC 1902#section-2 macro definitions.

class pysnmp.smi.rfc1902.NotificationType(objectIdentity, instanceIndex=(), objects={})#

Create an object representing SNMP Notification.

Instances of NotificationType class are containers incorporating ObjectIdentity class instance (identifying particular notification) and a collection of MIB variables IDs that NotificationOriginator should gather and put into notification message.

Typical notification is defined like this (from IF-MIB.txt):

linkDown NOTIFICATION-TYPE
    OBJECTS { ifIndex, ifAdminStatus, ifOperStatus }
    STATUS  current
    DESCRIPTION
           "A linkDown trap signifies that the SNMP entity..."
    ::= { snmpTraps 3 }

Corresponding NotificationType instantiation would look like this:

NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))

To retain similarity with SNMP variable-bindings, NotificationType objects behave like a sequence of ObjectType class instances.

See RFC 1902#section-2 for more information on NOTIFICATION-TYPE SMI definitions.

Parameters:
  • objectIdentity (ObjectIdentity) – Class instance representing MIB notification type identification.

  • instanceIndex (ObjectName) – Trailing part of MIB variables OID identification that represents concrete instance of a MIB variable. When notification is prepared, instanceIndex is appended to each MIB variable identification listed in NOTIFICATION-TYPE->OBJECTS clause.

  • objects (dict) – Dictionary-like object that may return values by OID key. The objects dictionary is consulted when notification is being prepared. OIDs are taken from MIB variables listed in NOTIFICATION-TYPE->OBJECTS with instanceIndex part appended.

Notes

Actual notification type and MIB variables look up occurs upon resolveWithMib() invocation.

Examples

>>> from pysnmp.smi.rfc1902 import *
>>> NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3'))
NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3'), (), {})
>>> NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), ObjectName('3.5'))
NotificationType(ObjectIdentity('1.3.6.1.6.3.1.1.5.3'), ObjectName('3.5'), {})
addVarBinds(*varBinds)#

Appends variable-binding to notification.

Parameters:

*varBinds (ObjectType) – One or more ObjectType class instances.

Returns:

NotificationType – reference to itself

Notes

This method can be used to add custom variable-bindings to notification message in addition to MIB variables specified in NOTIFICATION-TYPE->OBJECTS clause.

Examples

>>> nt = NotificationType(ObjectIdentity('IP-MIB', 'linkDown'))
>>> nt.addVarBinds(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
NotificationType(ObjectIdentity('IP-MIB', 'linkDown'), (), {})
>>>
addAsn1MibSource(*asn1Sources, **kwargs)#

Adds path to a repository to search ASN.1 MIB files.

Parameters:

*asn1Sources – one or more URL in form of str identifying local or remote ASN.1 MIB repositories. Path must include the @mib@ component which will be replaced with MIB module name at the time of search.

Returns:

NotificationType – reference to itself

Notes

Please refer to FileReader and HttpReader classes for in-depth information on ASN.1 MIB lookup.

Examples

>>> NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}).addAsn1MibSource('https://mibs.pysnmp.com/asn1/@mib@')
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>
addMibSource(*mibSources)#

Adds path to repository to search PySNMP MIB files.

Parameters:

*mibSources – one or more paths to search or Python package names to import and search for PySNMP MIB modules.

Returns:

NotificationType – reference to itself

Notes

Normally, ASN.1-to-Python MIB modules conversion is performed automatically through PySNMP/PySMI interaction. ASN1 MIB modules could also be manually compiled into Python via the mibdump.py tool.

Examples

>>> NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}).addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>
loadMibs(*modNames)#

Schedules search and load of given MIB modules.

Parameters:

*modNames – one or more MIB module names to load up and use for MIB variables resolution purposes.

Returns:

NotificationType – reference to itself

Examples

>>> NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {}).loadMibs('IF-MIB', 'TCP-MIB')
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>
resolveWithMib(mibViewController, ignoreErrors=True)#

Perform MIB variable ID conversion and notification objects expansion.

Parameters:

mibViewController (MibViewController) – class instance representing MIB browsing functionality.

Other Parameters:

ignoreErrors (bool) – If True (default), ignore MIB object name or value casting failures if possible.

Returns:

NotificationType – reference to itself

Raises:

SmiError – In case of fatal MIB hanling errora

Notes

Calling this method might cause the following sequence of events (exact details depends on many factors):

  • pysnmp.smi.rfc1902.ObjectIdentity.resolveWithMib() is called

  • MIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause, ObjectType instances are created from MIB variable OID and indexInstance suffix.

  • objects dictionary is queried for each MIB variable OID, acquired values are added to corresponding MIB variable

Examples

>>> notificationType = NotificationType(ObjectIdentity('IF-MIB', 'linkDown'))
>>> notificationType.resolveWithMib(mibViewController)
NotificationType(ObjectIdentity('IF-MIB', 'linkDown'), (), {})
>>>

SNMP Base Types#

SNMP represents real-world objects it serves along with their states in form of values. Those values each belong to one of SNMP types (RFC 1902#section-2) which, in turn, are based on ASN.1 data description language. PySNMP types are derived from PyASN1 implementation.

Null Type#

class pysnmp.proto.rfc1902.Null(initializer)#

Creates an instance of SNMP Null class.

Null type represents the absence of value.

Parameters:

initializer (str) – Python string object. Must be an empty string.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Null('')
Null('')
>>>

Note

The NULL type actually belongs to the base ASN.1 types. It is not defined in RFC 1902#section-2 as an SNMP type. The Null type is exposed through rfc1902 module just for convenience.

Integer32 Type#

class pysnmp.proto.rfc1902.Integer32(initializer)#

Creates an instance of SNMP Integer32 class.

Integer32 type represents integer-valued information between -2147483648 to 2147483647 inclusive (RFC 1902#section-7.1.1). This type is indistinguishable from the Integer type. The Integer32 type may be sub-typed to be more constrained than the base Integer32 type.

Parameters:

initializer (int) – Python integer in range between -2147483648 to 2147483647 inclusive or Integer32.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Integer32(1234)
Integer32(1234)
>>> Integer32(1) > 2
True
>>> Integer32(1) + 1
Integer32(2)
>>> int(Integer32(321))
321
>>> SmallInteger = Integer32.withRange(1,3)
>>> SmallInteger(1)
Integer32(1)
>>> DiscreetInteger = Integer32.withValues(4, 8, 1)
>>> DiscreetInteger(4)
Integer32(4)
>>>
subtypeSpec = <ConstraintsIntersection object, consts <ValueRangeConstraint object, consts -2147483648, 2147483647>>#

Set (on class, not on instance) or return a ConstraintsIntersection object imposing constraints on |ASN.1| type initialization values.

classmethod withValues(*values)#

Creates a subclass with discreet values constraint.

classmethod withRange(minimum, maximum)#

Creates a subclass with value range constraint.

Integer Type#

class pysnmp.proto.rfc1902.Integer(initializer)#

Creates an instance of SNMP INTEGER class.

The Integer type represents integer-valued information as named-number enumerations (RFC 1902#section-7.1.1). This type inherits and is indistinguishable from Integer32 class. The Integer type may be sub-typed to be more constrained than the base Integer type.

Parameters:

initializer (int) – Python integer in range between -2147483648 to 2147483647 inclusive or Integer class instance. In case of named-numbered enumerations, initialization is also possible by enumerated literal.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Integer(1234)
Integer(1234)
>>> Integer(1) > 2
True
>>> Integer(1) + 1
Integer(2)
>>> int(Integer(321))
321
>>> SomeState = Integer.withNamedValues(enable=1, disable=0)
>>> SomeState(1)
Integer('enable')
>>> int(SomeState('disable'))
0
>>>
classmethod withNamedValues(**values)#

Create a subclass with discreet named values constraint.

Reduce fully duplicate enumerations along the way.

OctetString Type#

class pysnmp.proto.rfc1902.OctetString(strValue=None, hexValue=None)#

Creates an instance of SNMP OCTET STRING class.

The OctetString type represents arbitrary binary or text data (RFC 1902#section-7.1.2). It may be sub-typed to be constrained in size.

Parameters:

strValue (str) – Python string or OctetString class instance.

Other Parameters:

hexValue (str) – Python string representing octets in a hexadecimal notation (e.g. DEADBEEF).

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> OctetString('some apples')
OctetString('some apples')
>>> OctetString('some apples') + ' and oranges'
OctetString('some apples and oranges')
>>> str(OctetString('some apples'))
'some apples'
>>> SomeString = OctetString.withSize(3, 12)
>>> str(SomeString(hexValue='deadbeef'))
'Þ­¾ï'
>>>
subtypeSpec = <ConstraintsIntersection object, consts <ValueSizeConstraint object, consts 0, 65535>>#

Set (on class, not on instance) or return a ConstraintsIntersection object imposing constraints on |ASN.1| type initialization values.

clone(*args, **kwargs)#

Create a modified version of |ASN.1| schema or value object.

The clone() method accepts the same set arguments as |ASN.1| class takes on instantiation except that all arguments of the clone() method are optional.

Whatever arguments are supplied, they are used to create a copy of self taking precedence over the ones used to instantiate self.

Note

Due to the immutable nature of the |ASN.1| object, if no arguments are supplied, no new |ASN.1| object will be created and self will be returned instead.

subtype(*args, **kwargs)#

Create a specialization of |ASN.1| schema or value object.

The subtype relationship between ASN.1 types has no correlation with subtype relationship between Python types. ASN.1 type is mainly identified by its tag(s) (TagSet) and value range constraints (ConstraintsIntersection). These ASN.1 type properties are implemented as |ASN.1| attributes.

The subtype() method accepts the same set arguments as |ASN.1| class takes on instantiation except that all parameters of the subtype() method are optional.

With the exception of the arguments described below, the rest of supplied arguments they are used to create a copy of self taking precedence over the ones used to instantiate self.

The following arguments to subtype() create a ASN.1 subtype out of |ASN.1| type:

Other Parameters:
  • implicitTag (Tag) – Implicitly apply given ASN.1 tag object to self’s TagSet, then use the result as new object’s ASN.1 tag(s).

  • explicitTag (Tag) – Explicitly apply given ASN.1 tag object to self’s TagSet, then use the result as new object’s ASN.1 tag(s).

  • subtypeSpec (ConstraintsIntersection) – Add ASN.1 constraints object to one of the self’s, then use the result as new object’s ASN.1 constraints.

Returns:

new instance of |ASN.1| schema or value object

Note

Due to the immutable nature of the |ASN.1| object, if no arguments are supplied, no new |ASN.1| object will be created and self will be returned instead.

classmethod withSize(minimum, maximum)#

Creates a subclass with value size constraint.

IpAddress Type#

class pysnmp.proto.rfc1902.IpAddress(strValue=None, hexValue=None)#

Creates an instance of SNMP IpAddress class.

The IpAddress class represents a 32-bit internet address as an OCTET STRING of length 4, in network byte-order (RFC 1902#section-7.1.5).

Parameters:

strValue (str) – The same as OctetString, additionally IPv4 address in dotted notation (‘127.0.0.1’).

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> IpAddress('127.0.0.1')
IpAddress(hexValue='7f000001')
>>> str(IpAddress(hexValue='7f000001'))
''
>>> IpAddress('')
IpAddress(hexValue='7f000001')
>>>

ObjectIdentifier Type#

class pysnmp.proto.rfc1902.ObjectIdentifier(initializer)#

Creates an instance of SNMP OBJECT IDENTIFIER class.

The ObjectIdentifier type represents administratively assigned names (RFC 1902#section-7.1.3). Supports sequence protocol where elements are integer sub-identifiers.

Parameters:

initializer (tuple, str) – Python tuple of up to 128 integers in range between 0 to 4294967295 inclusive or Python string containing OID in “dotted” form or ObjectIdentifier.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> ObjectIdentifier((1, 3, 6))
ObjectIdentifier('1.3.6')
>>> ObjectIdentifier('1.3.6')
ObjectIdentifier('1.3.6')
>>> tuple(ObjectIdentifier('1.3.6'))
(1, 3, 6)
>>> str(ObjectIdentifier('1.3.6'))
'1.3.6'
>>>

Counter32 Type#

class pysnmp.proto.rfc1902.Counter32(initializer)#

Creates an instance of SNMP Counter32 class.

Counter32 type represents a non-negative integer which monotonically increases until it reaches a maximum value of 4294967295, when it wraps around and starts increasing again from zero (RFC 1902#section-7.1.6).

Parameters:

initializer (int) – Python integer in range between 0 to 4294967295 inclusive or any Integer-based class.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Counter32(1234)
Counter32(1234)
>>> Counter32(1) + 1
Counter32(2)
>>> int(Counter32(321))
321
>>>

Gauge32 Type#

class pysnmp.proto.rfc1902.Gauge32(initializer)#

Creates an instance of SNMP Gauge32 class.

Gauge32 type represents a non-negative integer, which may increase or decrease, but shall never exceed a maximum value. The maximum value can not be greater than 4294967295 (RFC 1902#section-7.1.7).

Parameters:

initializer (int) – Python integer in range between 0 to 4294967295 inclusive or any Integer-based class.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Gauge32(1234)
Gauge32(1234)
>>> Gauge32(1) + 1
Gauge32(2)
>>> int(Gauge32(321))
321
>>>

Unsigned32 Type#

class pysnmp.proto.rfc1902.Unsigned32(initializer)#

Creates an instance of SNMP Unsigned32 class.

Unsigned32 type represents integer-valued information between 0 and 4294967295 (RFC 1902#section-7.1.11).

Parameters:

initializer (int) – Python integer in range between 0 to 4294967295 inclusive or any Integer-based class.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Unsigned32(1234)
Unsigned32(1234)
>>> Unsigned32(1) + 1
Unsigned32(2)
>>> int(Unsigned32(321))
321
>>>

TimeTicks Type#

class pysnmp.proto.rfc1902.TimeTicks(initializer)#

Creates an instance of SNMP TimeTicks class.

TimeTicks type represents a non-negative integer which represents the time, modulo 4294967296, in hundredths of a second between two epochs (RFC 1902#section-7.1.8).

Parameters:

initializer (int) – Python integer in range between 0 to 4294967295 inclusive or any Integer-based class.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> TimeTicks(1234)
TimeTicks(1234)
>>> TimeTicks(1) + 1
TimeTicks(2)
>>> int(TimeTicks(321))
321
>>>

Opaque Type#

class pysnmp.proto.rfc1902.Opaque(initializer)#

Creates an instance of SNMP Opaque class.

The Opaque type supports the capability to pass arbitrary ASN.1 syntax. A value is encoded using the ASN.1 BER into a string of octets. This, in turn, is encoded as an OCTET STRING, in effect “double-wrapping” the original ASN.1 value (RFC 1902#section-7.1.9).

Parameters:

strValue (str) – Python string or OctetString-based class instance.

Other Parameters:

hexValue (str) – Python string representing octets in a hexadecimal notation (e.g. DEADBEEF).

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Opaque('some apples')
Opaque('some apples')
>>> Opaque('some apples') + ' and oranges'
Opaque('some apples and oranges')
>>> str(Opaque('some apples'))
'some apples'
>>> str(Opaque(hexValue='deadbeef'))
'Þ­¾ï'
>>>

Counter64 Type#

class pysnmp.proto.rfc1902.Counter64(initializer)#

Creates an instance of SNMP Counter64 class.

Counter64 type represents a non-negative integer which monotonically increases until it reaches a maximum value of 18446744073709551615, when it wraps around and starts increasing again from zero (RFC 1902#section-7.1.10).

Parameters:

initializer (int) – Python integer in range between 0 to 4294967295 inclusive or any Integer-based class.

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> Counter64(1234)
Counter64(1234)
>>> Counter64(1) + 1
Counter64(2)
>>> int(Counter64(321))
321
>>>

Bits Type#

class pysnmp.proto.rfc1902.Bits(initializer)#

Creates an instance of SNMP BITS class.

The Bits type represents an enumeration of named bits. This collection is assigned non-negative, contiguous values, starting at zero. Only those named-bits so enumerated may be present in a value (RFC 1902#section-7.1.4).

The bits are named and identified by their position in the octet string. Position zero is the high order (or left-most) bit in the first octet of the string. Position 7 is the low order (or right-most) bit of the first octet of the string. Position 8 is the high order bit in the second octet of the string, and so on (BITS Pseudotype).

Parameters:

strValue (str, tuple) – Sequence of bit names or a Python string (as a raw data) or OctetString class instance.

Other Parameters:

hexValue (str) – Python string representing octets in a hexadecimal notation (e.g. DEADBEEF).

Raises:

PyAsn1Error : – On constraint violation or bad initializer.

Examples

>>> from pysnmp.proto.rfc1902 import *
>>> SomeBits = Bits.withNamedBits(apple=0, orange=1, peach=2)
>>> SomeBits(('apple', 'orange')).prettyPrint()
'apple, orange'
>>> SomeBits(('apple', 'orange'))
Bits(hexValue='c0')
>>> SomeBits('€')
Bits(hexValue='80')
>>> SomeBits(hexValue='80')
Bits(hexValue='80')
>>> SomeBits(hexValue='80').prettyPrint()
'apple'
>>>
classmethod withNamedBits(**values)#

Creates a subclass with discreet named bits constraint.

Reduce fully duplicate enumerations along the way.