Library reference¶
Dealing with many SNMP features may quickly overwhelm developers who aim at a quick and trivial task, PySNMP employs a layered architecture approach where the topmost programming API tries to be as simple as possible to allow immediate solutions for most common use cases. It will let you perform SNMP GET/SET/WALK and TRAP/INFORM operations by pasting code snippets from PySNMP documentation and example scripts right into your Python interactive session.
Most of SNMP operations involve packet exchange over network. PySNMP is shipped with a set of bindings to popular asynchronous Python I/O frameworks that let you run PySNMP in parallel with other tasks your application may perform.
Synchronous SNMP¶
Most simple and strightforward 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.
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.UdpTransportTarget(transportAddr: TransportAddrT, timeout: int = 1, retries: int = 5, tagList: Any = 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
SnmpEngineclass instance.See RFC 1906 Section 3 for more information on the UDP transport mapping.
- Parameters:
transportAddr (tuple) – Indicates remote address in Python
socketmodule 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(('127.0.0.1', 161)) UdpTransportTarget(('127.0.0.1', 161), timeout=1, retries=5, tagList=b'') >>>
- setLocalAddress(iface: tuple[str, ...] | None) AbstractTransportTarget[TransportAddrT]
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.Udp6TransportTarget(transportAddr: TransportAddrT, timeout: int = 1, retries: int = 5, tagList: Any = b'')
Creates UDP/IPv6 configuration entry and initialize socket API if needed.
This object can be used by
getCmd()and the other command-generator coroutines, or bysendNotification(), for adding new entries to Local Configuration Datastore (LCD) managed bySnmpEngineclass 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
socketmodule 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(('::1', 161)) Udp6TransportTarget(('::1', 161), timeout=1, retries=5, tagList=b'') >>> 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=b'') >>> Udp6TransportTarget(('1080:0:0:0:8:800:200C:417A', 161)) Udp6TransportTarget(('1080::8:800:200c:417a', 161), timeout=1, retries=5, tagList=b'') >>> Udp6TransportTarget(('::0', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList=b'') >>> Udp6TransportTarget(('::', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList=b'') >>>
- setLocalAddress(iface: tuple[str, ...] | None) AbstractTransportTarget[TransportAddrT]
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
Command Generator
Notification Originator
Transport configuration¶
- class pysnmp.hlapi.asyncio.UdpTransportTarget(transportAddr: TransportAddrT, timeout: int = 1, retries: int = 5, tagList: Any = 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
SnmpEngineclass instance.See RFC 1906 Section 3 for more information on the UDP transport mapping.
- Parameters:
transportAddr (tuple) – Indicates remote address in Python
socketmodule 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(('127.0.0.1', 161)) UdpTransportTarget(('127.0.0.1', 161), timeout=1, retries=5, tagList=b'') >>>
- setLocalAddress(iface: tuple[str, ...] | None) AbstractTransportTarget[TransportAddrT]¶
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: TransportAddrT, timeout: int = 1, retries: int = 5, tagList: Any = b'')¶
Creates UDP/IPv6 configuration entry and initialize socket API if needed.
This object can be used by
getCmd()and the other command-generator coroutines, or bysendNotification(), for adding new entries to Local Configuration Datastore (LCD) managed bySnmpEngineclass 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
socketmodule 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(('::1', 161)) Udp6TransportTarget(('::1', 161), timeout=1, retries=5, tagList=b'') >>> 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=b'') >>> Udp6TransportTarget(('1080:0:0:0:8:800:200C:417A', 161)) Udp6TransportTarget(('1080::8:800:200c:417a', 161), timeout=1, retries=5, tagList=b'') >>> Udp6TransportTarget(('::0', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList=b'') >>> Udp6TransportTarget(('::', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList=b'') >>>
- setLocalAddress(iface: tuple[str, ...] | None) AbstractTransportTarget[TransportAddrT]¶
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
Asynchronous: asyncio¶
PySNMP builds its asynchronous API on the standard library asyncio
module. Its main design feature is that it makes asynchronous code look
like synchronous code, which greatly simplifies development and
maintenance.
Command Generator
Notification Originator
Transport configuration¶
- class pysnmp.hlapi.asyncio.UdpTransportTarget(transportAddr: TransportAddrT, timeout: int = 1, retries: int = 5, tagList: Any = 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
SnmpEngineclass instance.See RFC 1906 Section 3 for more information on the UDP transport mapping.
- Parameters:
transportAddr (tuple) – Indicates remote address in Python
socketmodule 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(('127.0.0.1', 161)) UdpTransportTarget(('127.0.0.1', 161), timeout=1, retries=5, tagList=b'') >>>
- setLocalAddress(iface: tuple[str, ...] | None) AbstractTransportTarget[TransportAddrT]
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: TransportAddrT, timeout: int = 1, retries: int = 5, tagList: Any = b'')
Creates UDP/IPv6 configuration entry and initialize socket API if needed.
This object can be used by
getCmd()and the other command-generator coroutines, or bysendNotification(), for adding new entries to Local Configuration Datastore (LCD) managed bySnmpEngineclass 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
socketmodule 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(('::1', 161)) Udp6TransportTarget(('::1', 161), timeout=1, retries=5, tagList=b'') >>> 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=b'') >>> Udp6TransportTarget(('1080:0:0:0:8:800:200C:417A', 161)) Udp6TransportTarget(('1080::8:800:200c:417a', 161), timeout=1, retries=5, tagList=b'') >>> Udp6TransportTarget(('::0', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList=b'') >>> Udp6TransportTarget(('::', 161)) Udp6TransportTarget(('::', 161), timeout=1, retries=5, tagList=b'') >>>
- setLocalAddress(iface: tuple[str, ...] | None) AbstractTransportTarget[TransportAddrT]
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 substsems. Calls to high-level Applications API also consume SNMP Engine object on input.
- class pysnmp.hlapi.SnmpEngine(snmpEngineID=None)¶
Creates SNMP engine object.
SNMP engine object is central in SNMP v3 architecture. It is an umbrella object that coordinates interactions between all parts of SNMP v3 system. See RFC 3412 Section 2.1 (where it is termed The Dispatcher).
With PySNMP design, SnmpEngine is the only stateful object, all SNMP v3 operations require an instance of SNMP engine. Users do not normally request services directly from SnmpEngine, but pass it around to other PySNMP interfaces.
It is possible to run multiple instances of SnmpEngine in the application. In a multithreaded environment, each thread that works with SNMP must have its own SnmpEngine instance.
- Parameters:
snmpEngineID (
OctetString) – Unique and unambiguous identifier of an SNMP engine. If not given, snmpEngineID is autogenerated and stored on the filesystem. See RFC 3411 Section 3.1.1 for details.enableLegacyVersions (
bool) – Whether this engine speaks SNMPv1 and SNMPv2c at all. When false, the v1 and v2c message processing and security models are never registered, so an inbound v1 or v2c message is counted in snmpInBadVersions and dropped, and an outbound one fails with unsupportedMsgProcessingModel. Defaults to what the PYSNMP_DISABLE_V1_V2C environment variable says, and to true when it says nothing.
Examples
>>> engine = SnmpEngine() >>> type(engine.snmpEngineID).__name__ 'SnmpEngineID' >>> repr(engine).startswith('SnmpEngine(snmpEngineID=<SnmpEngineID value object') True >>> v3Only = SnmpEngine(enableLegacyVersions=False) >>> sorted(int(x) for x in v3Only.messageProcessingSubsystems) [3] >>>
Assemble the subsystems, and settle which SNMP versions this engine speaks.
snmpEngineID defaults to the one the MIB generated for this host, which is derived from a MAC address where one can be found. snmpEngineBoots is incremented here: RFC 3414 Section 2.2 counts a boot as an engine coming up, and USM’s time window checks depend on it moving.
enableLegacyVersions decides whether the v1 and v2c message processing and security models are registered at all. Leaving them out is the enforcement – see the note in the body – and None means take the default from the environment.
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.
- class pysnmp.hlapi.CommunityData(communityIndex, communityName=None, mpModel=1, contextEngineId=None, contextName='', tag='')¶
Creates SNMP v1/v2c configuration entry.
This object can be used by
getCmd()and the other command-generator coroutines, or bysendNotification(), for adding new entries to Local Configuration Datastore (LCD) managed bySnmpEngineclass instance.See RFC 2576 Section 5.3 for more information on the SNMP-COMMUNITY-MIB::snmpCommunityTable.
- Parameters:
communityIndex (
str,OctetString) – Unique index value of a row in snmpCommunityTable. If it is the only positional parameter, it is treated as a communityName.communityName (
str,OctetString) – SNMP v1/v2c community string.mpModel (
int) – SNMP message processing model AKA SNMP version. Known SNMP versions are:0 - for SNMP v1
1 - for SNMP v2c (default)
- contextEngineId:
str,OctetString Indicates the location of the context in which management information is accessed when using the community string specified by the above communityName.
- contextName:
str,OctetString The context in which management information is accessed when using the above communityName.
- tag:
str Arbitrary string that specifies a set of transport endpoints from which a command responder application will accept management requests with given communityName or to which notification originator application will send notifications when targets are specified by a tag value(s).
The other way to look at the tag feature is that it can make specific communityName only valid for certain targets.
The other use-case is when multiple distinct SNMP peers share the same communityName – binding each instance of communityName to transport endpoint lets you distinguish SNMP peers from each other (e.g. resolving communityName into proper securityName).
For more technical information on SNMP configuration tags please refer to RFC 3413 Section 4.1.1 and RFC 2576 Section 5.3 (e.g. the snmpCommunityTransportTag object).
See also:
UdpTransportTarget
Warning
If the same communityIndex value is supplied repeatedly with different communityName (or other parameters), the later call supersedes all previous calls.
Make sure not to configure duplicate communityName values unless they have distinct mpModel and/or tag fields. This will make communityName based database lookup ambiguous.
Examples
>>> from pysnmp.hlapi import CommunityData >>> community = CommunityData('public') >>> community.communityName, community.mpModel, community.contextEngineId, community.contextName, community.tag, community.securityName == community.communityIndex ('public', 1, None, b'', b'', True) >>> CommunityData('public', 'public') CommunityData(communityIndex='public', communityName=<COMMUNITY>, mpModel=1, contextEngineId=None, contextName=b'', tag=b'', securityName='public') >>>
Configure community-based access, deriving what was not given.
Called with one argument, that argument is the community name – the older two-argument form put the index first, and telling them apart is what the swapping here is for.
The index defaults to a hash of everything that distinguishes this configuration, so two different communities do not collide in the LCD, and the security name tracks the index rather than the community, so the name VACM sees is not the secret.
User-based¶
The UsmUserData class provides SNMPv3 User-Based
Security Model configuration for SNMP v3 systems.
- class pysnmp.hlapi.UsmUserData(userName, authKey=None, privKey=None, authProtocol=usmNoAuthProtocol, privProtocol=usmNoPrivProtocol, securityEngineId=None, authKeyType=usmKeyTypePassphrase, privKeyType=usmKeyTypePassphrase)¶
Creates SNMP v3 User Security Model (USM) configuration entry.
This object can be used by
getCmd()and the other command-generator coroutines, or bysendNotification(), for adding new entries to Local Configuration Datastore (LCD) managed bySnmpEngineclass instance.See RFC 3414 Section 5 for more information on the SNMP-USER-BASED-SM-MIB::usmUserTable.
- Parameters:
userName (
str,OctetString) – A human readable string representing the name of the SNMP USM user.- Other Parameters:
authKey (
str,OctetString) – Initial value of the secret authentication key. If not set,usmNoAuthProtocolis implied. If set and no authProtocol is specified,usmHMACMD5AuthProtocoltakes effect.privKey (
str,OctetString) – Initial value of the secret encryption key. If not set,usmNoPrivProtocolis implied. If set and no privProtocol is specified,usmDESPrivProtocoltakes effect.authProtocol (
tuple,ObjectIdentifier) – An indication of whether messages sent on behalf of this USM user can be authenticated, and if so, the type of authentication protocol which is used.Supported authentication protocol identifiers are:
usmNoAuthProtocol(default is authKey not given)usmHMACMD5AuthProtocol(default if authKey is given)
- securityEngineId:
OctetString The snmpEngineID of the authoritative SNMP engine to which a dateRequest message is to be sent. Will be automatically discovered from peer if not given, unless localized keys are used. In the latter case securityEngineId must be specified.
See RFC 3414 Section 2.5.1 for technical explanation.
- securityName:
str,OctetString Together with the snmpEngineID it identifies a row in the SNMP-USER-BASED-SM-MIB::usmUserTable that is to be used for securing the message.
See RFC 3414 Section 2.5.1 for technical explanation.
- privProtocol:
tuple,ObjectIdentifier An indication of whether messages sent on behalf of this USM user be encrypted, and if so, the type of encryption protocol which is used.
Supported encryption protocol identifiers are:
usmNoPrivProtocol(default is authKey not given)usmDESPrivProtocol(default if authKey is given)
- authKeyType:
int Type of authKey material. See RFC 3414 Section 2.6 for technical explanation.
Supported key types are:
- privKeyType:
int Type of privKey material. See RFC 3414 Section 2.6 for technical explanation.
Supported key types are:
Notes
If
usmKeyTypeLocalizedis used when running a non-authoritative SNMP engine, USM key localization mechanism is not invoked. As a consequence, local SNMP engine configuration won’t get automatically populated with remote SNMP engine’s securityEngineId.Therefore peer SNMP engine’s securityEngineId must be added to local configuration and associated with its localized keys.
Alternatively, the magic securityEngineId value of five zeros (0x0000000000) can be used to refer to the localized keys that should be used with any unknown remote SNMP engine. This feature is specific to pysnmp.
Examples
>>> from pysnmp.hlapi import UsmUserData >>> UsmUserData('testuser', authKey='authenticationkey') UsmUserData(userName='testuser', authKey=<AUTHKEY>, privKey=<PRIVKEY>, authProtocol=(1, 3, 6, 1, 6, 3, 10, 1, 1, 2), privProtocol=(1, 3, 6, 1, 6, 3, 10, 1, 2, 1), securityEngineId='<DEFAULT>', securityName='testuser', authKeyType=0, privKeyType=0) >>> UsmUserData('testuser', authKey='authenticationkey', privKey='encryptionkey') UsmUserData(userName='testuser', authKey=<AUTHKEY>, privKey=<PRIVKEY>, authProtocol=(1, 3, 6, 1, 6, 3, 10, 1, 1, 2), privProtocol=(1, 3, 6, 1, 6, 3, 10, 1, 2, 2), securityEngineId='<DEFAULT>', securityName='testuser', authKeyType=0, privKeyType=0) >>>
Configure a USM user, deriving the security level from the keys given.
The level is not passed in: a user with neither key is noAuthNoPriv, with an authentication key authNoPriv, and with both authPriv. A privacy key without an authentication key is refused, since RFC 3414 has no such level.
Where a key is given and its protocol is not, the protocol defaults to what RFC 3414 specifies – HMAC-MD5 and DES – which are weak and are what the run-time warnings are about.
Authentication protocol identifiers
- pysnmp.hlapi.usmNoAuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 1)¶
No Authentication Protocol
- pysnmp.hlapi.usmHMACMD5AuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 2)¶
The HMAC-MD5-96 Digest Authentication Protocol (RFC 3414 Section 6)
- pysnmp.hlapi.usmHMACSHAAuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 3)¶
The HMAC-SHA-96 Digest Authentication Protocol AKA SHA-1 (RFC 3414 Section 7)
- pysnmp.hlapi.usmHMAC128SHA224AuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 4)¶
The HMAC-SHA-2 Digest Authentication Protocols (RFC 7860)
- pysnmp.hlapi.usmHMAC192SHA256AuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 5)¶
The HMAC-SHA-2 Digest Authentication Protocols (RFC 7860)
- pysnmp.hlapi.usmHMAC256SHA384AuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 6)¶
The HMAC-SHA-2 Digest Authentication Protocols (RFC 7860)
- pysnmp.hlapi.usmHMAC384SHA512AuthProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 1, 7)¶
The HMAC-SHA-2 Digest Authentication Protocols (RFC 7860)
Privacy (encryption) protocol identifiers
- pysnmp.hlapi.usmNoPrivProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 2, 1)¶
No Privacy Protocol
- pysnmp.hlapi.usmDESPrivProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 2, 2)¶
The CBC-DES Symmetric Encryption Protocol (RFC 3414 Section 8)
- pysnmp.hlapi.usm3DESEDEPrivProtocol = (1, 3, 6, 1, 6, 3, 10, 1, 2, 3)¶
The 3DES-EDE Symmetric Encryption Protocol (draft-reeder-snmpv3-usm-3desede-00)
- pysnmp.hlapi.usmAesCfb128Protocol = (1, 3, 6, 1, 6, 3, 10, 1, 2, 4)¶
The CFB128-AES-128 Symmetric Encryption Protocol (RFC 3826 Section 3)
- pysnmp.hlapi.usmAesCfb192Protocol = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 101)¶
The CFB128-AES-192 Symmetric Encryption Protocol (draft-blumenthal-aes-usm-04) with Reeder key localization
- pysnmp.hlapi.usmAesCfb256Protocol = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 102)¶
The CFB128-AES-256 Symmetric Encryption Protocol (draft-blumenthal-aes-usm-04) with Reeder key localization
- pysnmp.hlapi.usmAesBlumenthalCfb192Protocol = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 1)¶
The CFB128-AES-192 Symmetric Encryption Protocol (draft-blumenthal-aes-usm-04)
- pysnmp.hlapi.usmAesBlumenthalCfb256Protocol = (1, 3, 6, 1, 4, 1, 9, 12, 6, 1, 2)¶
The CFB128-AES-256 Symmetric Encryption Protocol (draft-blumenthal-aes-usm-04)
Key material types
- pysnmp.hlapi.usmKeyTypePassphrase = 0¶
USM key material type - plain-text pass phrase (RFC 3414 Section 2.6)
- pysnmp.hlapi.usmKeyTypeMaster = 1¶
USM key material type - hashed pass-phrase AKA master key (RFC 3414 Section 2.6)
- pysnmp.hlapi.usmKeyTypeLocalized = 2¶
USM key material type - hashed pass-phrase hashed with Context SNMP Engine ID (RFC 3414 Section 2.6)
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.
- class pysnmp.hlapi.ContextData(contextEngineId: Any | None = None, contextName: Any = b'')¶
Creates UDP/IPv6 configuration entry and initialize socket API if needed.
This object can be used by
getCmd()and the other command-generator coroutines, or bysendNotification(), and their derevatives for forming SNMP PDU and also adding new entries to Local Configuration Datastore (LCD) in order to support SNMPv1/v2c with SNMPv3 interoperability.See RFC 3411 Section 4.1 for SNMP Context details.
- Parameters:
contextEngineId (str) – Uniquely identifies an SNMP entity that may realize an instance of a MIB with a particular contextName (RFC 3411 Section 3.3.2). More frequently than not, ContextEngineID is the same as authoritative SnmpEngineID, however if SNMP Engine serves multiple SNMP Entities, their ContextEngineIDs would be distinct. Default is authoritative SNMP Engine ID.
contextName (str) – Used to name an instance of MIB (RFC 3411 Section 3.3.3). Default is empty string.
Examples
>>> from pysnmp.hlapi import ContextData >>> from pysnmp.proto.rfc1902 import OctetString >>> ContextData() ContextData(contextEngineId=None, contextName=b'') >>> ContextData(OctetString(hexValue='01020ABBA0')).contextEngineId.prettyPrint() '0x01020abba0' >>> ContextData(contextName='mycontext') ContextData(contextEngineId=None, contextName='mycontext')
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 definiitons.
- 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
tupleofintsub-OIDs.See RFC 1902 Section 2 for more information on OBJECT-IDENTITY SMI definitions.
- Parameters:
args – initial MIB variable identity. Recognized variants:
single
tupleor integers representing OIDsingle
strrepresenting OID in dot-separated integers formsingle
strrepresenting MIB variable in dot-separated labels formsingle
strrepresenting MIB name. First variable defined in MIB is assumed.pair of
strrepresenting MIB name and variable namepair of
strrepresenting MIB name and variable name followed by an arbitrary number ofstrand/orintvalues 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)
Arguments are kept unresolved; resolveWithMib() is what interprets them.
What was passed can be a name, an OID, a module and symbol, or a symbol and index values, and telling those apart needs a MIB view that may not exist yet. So this only records them, and the object stays dirty until resolved.
- getMibSymbol()¶
Return MIB variable symbolic identification.
- Returns:
str – MIB module name
str – MIB variable symbolic name
ObjectName– class instance representing MIB variable instance index.
- Raises:
pysnmp.smi.error.SmiError – If MIB variable conversion has not been performed.
Examples
>>> from pysnmp.smi import builder, view >>> mibViewController = view.MibViewController(builder.MibBuilder()) >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.resolveWithMib(mibViewController) ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.getMibSymbol()[:2] ('SNMPv2-MIB', 'sysDescr') >>> objectIdentity.getMibSymbol()[2][0].prettyPrint() '0' >>>
- getOid()¶
Return OID identifying MIB variable.
- Returns:
ObjectName– full OID identifying MIB variable including possible index part.- Raises:
pysnmp.smi.error.SmiError – If MIB variable conversion has not been performed.
Examples
>>> from pysnmp.smi import builder, view >>> mibViewController = view.MibViewController(builder.MibBuilder()) >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.resolveWithMib(mibViewController) ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.getOid().prettyPrint() '1.3.6.1.2.1.1.1.0' >>>
- getLabel()¶
Return 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:
pysnmp.smi.error.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
>>> from pysnmp.smi import builder, view >>> mibViewController = view.MibViewController(builder.MibBuilder()) >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.resolveWithMib(mibViewController) ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0) >>> objectIdentity.getLabel() ('iso', 'org', 'dod', 'internet', 'mgmt', 'mib-2', 'system', 'sysDescr') >>>
- getMibNode()¶
The MIB object this resolved to. Raises until resolveWithMib() has run.
- isFullyResolved()¶
Whether the MIB lookup has happened and the OID and node are known.
- addAsn1MibSource(*asn1Sources, **kwargs)¶
Add path to a repository to search ASN.1 MIB files.
- Parameters:
*asn1Sources – one or more URL in form of
stridentifying 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
FileReader,HttpReaderandZipReaderclasses for in-depth information on ASN.1 MIB lookup.Examples
>>> ObjectIdentity('SNMPv2-MIB', 'sysDescr').addAsn1MibSource('https://pysnmp.github.io:443/mibs/asn1/@mib@') ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>>
- addMibSource(*mibSources)¶
Add 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.- Returns:
ObjectIdentity– reference to itself- Raises:
pysnmp.smi.error.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
MibCompilerfor conversion into Python MIB module (based on pysnmp classes)Python MIB module is imported by SNMP engine, internal indices created
MibViewControllerlooks up the rest of MIB identification information based on whatever information is already available,ObjectIdentityclass instance gets updated and ready for further use.
Examples
>>> from pysnmp.smi import builder, view >>> mibViewController = view.MibViewController(builder.MibBuilder()) >>> objectIdentity = ObjectIdentity('SNMPv2-MIB', 'sysDescr') >>> str(objectIdentity.resolveWithMib(mibViewController)) '1.3.6.1.2.1.1.1' >>>
- prettyPrint()¶
The MIB name, as MODULE::symbol with any index appended.
- __repr__()¶
How this identity was constructed, not what it resolved to.
- __str__()¶
The OID in dotted form.
- __eq__(other)¶
Compare by OID.
- __lt__(other)¶
Order by OID.
- __bool__()¶
Whether the OID is non-empty.
- __getitem__(i)¶
One sub-identifier, or a slice of them.
- __len__()¶
How many sub-identifiers the OID has.
- __add__(other)¶
Extend the OID on the right.
- __radd__(other)¶
Extend the OID on the left.
- __hash__()¶
Hash by OID. Raises until resolved, since the OID is what identifies it.
- __getattr__(attr)¶
Forward the OID’s own methods, once there is an OID to forward to.
This stands in for inheriting from ObjectIdentifier: an identity is not an OID until it has been resolved against a MIB, so the methods appear only then rather than being present and wrong beforehand.
- class pysnmp.smi.rfc1902.ObjectType(objectIdentity, objectSyntax=<Null value object, payload []>)¶
Create an object representing MIB variable.
Instances of
ObjectTypeclass are containers incorporatingObjectIdentityclass 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),
ObjectTypeobjects 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 * >>> repr(ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'))).startswith("ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), <Null value object") True >>> ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386') ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0), 'Linux i386')
Pairs an identity with a value, both unresolved until resolveWithMib().
The syntax the value has to conform to comes from the MIB, so the value cannot be checked or converted here. unSpecified is the value a GET carries, where the caller is asking rather than telling.
- __getitem__(i)¶
The identity at 0, the value at 1, as a binding is a pair.
- __str__()¶
The binding as MODULE::symbol.index = value.
- __repr__()¶
The identity and value this was constructed from.
- isFullyResolved()¶
Whether the identity resolved and the value took its MIB-defined type.
- addAsn1MibSource(*asn1Sources, **kwargs)¶
Add path to a repository to search ASN.1 MIB files.
- Parameters:
*asn1Sources – one or more URL in form of
stridentifying 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,HttpReaderandZipReaderclasses for in-depth information on ASN.1 MIB lookup.Examples
>>> repr(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).addAsn1MibSource('https://pysnmp.github.io:443/mibs/asn1/@mib@')).startswith("ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), <Null value object") True >>>
- addMibSource(*mibSources)¶
Add 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
>>> repr(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs')).startswith("ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), <Null value object") True >>>
- 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
>>> repr(ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr')).loadMibs('IF-MIB', 'TCP-MIB')).startswith("ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), <Null value object") True >>>
- 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:
pysnmp.smi.error.SmiError – In case of fatal MIB hanling errora
Notes
Calling this method involves
resolveWithMib()method invocation.Examples
>>> from pysnmp.smi import builder, view >>> mibViewController = view.MibViewController(builder.MibBuilder()) >>> objectType = ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr'), 'Linux i386') >>> str(objectType.resolveWithMib(mibViewController)) 'SNMPv2-MIB::sysDescr = Linux i386' >>> str(objectType) 'SNMPv2-MIB::sysDescr = Linux i386' >>>
- getUnits()¶
Return UNITS clause value from the resolved MIB node.
- Returns:
str– The UNITS clause value associated with the MIB object, or empty string if no UNITS clause is defined.- Raises:
pysnmp.smi.error.SmiError – If MIB variable conversion has not been performed.
- prettyPrint()¶
The binding with both halves rendered as the MIB defines them.
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 definiitons.
- class pysnmp.smi.rfc1902.NotificationType(objectIdentity, instanceIndex=(), objects=None)¶
Create an object representing SNMP Notification.
Instances of
NotificationTypeclass are containers incorporatingObjectIdentityclass instance (identifying particular notification) and a collection of MIB variables IDs thatsendNotification()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,
NotificationTypeobjects behave like a sequence ofObjectTypeclass 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.proto.rfc1902 import ObjectName >>> 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'), (), {}) >>> repr(NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), ObjectName('3.5'))).startswith("NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), <ObjectName value object") True
Records the notification and the objects it will carry, unresolved.
Which objects a notification carries is what its MIB definition says, so the list is filled in by resolveWithMib(); objects supplies values for those the sender has to provide itself.
- __getitem__(i)¶
One of the notification’s bindings, by position.
- __repr__()¶
The identity, instance index and objects this was constructed from.
- addVarBinds(*varBinds)¶
Append variable-binding to notification.
- Parameters:
*varBinds (
ObjectType) – One or moreObjectTypeclass 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)¶
Add path to a repository to search ASN.1 MIB files.
- Parameters:
*asn1Sources – one or more URL in form of
stridentifying 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,HttpReaderandZipReaderclasses for in-depth information on ASN.1 MIB lookup.Examples
>>> NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), (), {}).addAsn1MibSource('https://pysnmp.github.io:443/mibs/asn1/@mib@') NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), (), {}) >>>
- addMibSource(*mibSources)¶
Add 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('SNMPv2-MIB', 'coldStart'), (), {}).addMibSource('/opt/pysnmp/mibs', 'pysnmp_mibs') NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), (), {}) >>>
- 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('SNMPv2-MIB', 'coldStart'), (), {}).loadMibs('SNMPv2-MIB') NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), (), {}) >>>
- isFullyResolved()¶
Whether the notification and every object it carries have resolved.
- 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:
pysnmp.smi.error.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 calledMIB variables names are read from NOTIFICATION-TYPE->OBJECTS clause,
ObjectTypeinstances 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
>>> from pysnmp.smi import builder, view >>> mibViewController = view.MibViewController(builder.MibBuilder()) >>> notificationType = NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart')) >>> notificationType.resolveWithMib(mibViewController) NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart'), (), {}) >>>
- prettyPrint()¶
The notification and its bindings, each rendered as the MIB defines them.
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 Python ASN.1 types implementation.
Null type¶
- class pysnmp.proto.rfc1902.Null(initializer)¶
Creates an instance of SNMP Null class.
Nulltype represents the absence of value.- Parameters:
initializer (str) – Python string object. Must be an empty string.
- Raises:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Null('') <Null value object, payload []> >>>
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.
Integer32type represents integer-valued information between -2147483648 to 2147483647 inclusive (RFC 1902 Section 7.1.1). This type is indistinguishable from theIntegertype. TheInteger32type may be sub-typed to be more constrained than the baseInteger32type.- Parameters:
initializer (int) – Python integer in range between -2147483648 to 2147483647 inclusive or
Integer32.- Raises:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Integer32(1234) <Integer32 value object, payload [1234]> >>> Integer32(1) > 2 False >>> Integer32(1) + 1 <Integer32 value object, payload [2]> >>> int(Integer32(321)) 321 >>> SmallInteger = Integer32.withRange(1,3) >>> SmallInteger(1) <Integer32 value object, payload [1]> >>> DiscreetInteger = Integer32.withValues(4, 8, 1) >>> DiscreetInteger(4) <Integer32 value object, payload [4]> >>>
- subtypeSpec = <ConstraintsIntersection object, consts <ValueRangeConstraint object, consts -2147483648, 2147483647>>¶
Set (on class, not on instance) or return a
ConstraintsIntersectionobject imposing constraints on ASN.1 type initialization values.
- classmethod withValues(*values)¶
Create a subclass with discreet values constraint.
- classmethod withRange(minimum, maximum)¶
Create a subclass with value range constraint.
Integer type¶
- class pysnmp.proto.rfc1902.Integer(initializer)¶
Creates an instance of SNMP INTEGER class.
The
Integertype represents integer-valued information as named-number enumerations (RFC 1902 Section 7.1.1). This type inherits and is indistinguishable fromInteger32class. TheIntegertype may be sub-typed to be more constrained than the baseIntegertype.- Parameters:
initializer (int) – Python integer in range between -2147483648 to 2147483647 inclusive or
Integerclass instance. In case of named-numbered enumerations, initialization is also possible by enumerated literal.- Raises:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Integer(1234) <Integer value object, payload [1234]> >>> Integer(1) > 2 False >>> Integer(1) + 1 <Integer value object, payload [2]> >>> int(Integer(321)) 321 >>> SomeState = Integer.withNamedValues(enable=1, disable=0) >>> SomeState(1) <Integer value object, payload [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
OctetStringtype 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
OctetStringclass instance.- Other Parameters:
hexValue (str) – Python string representing octets in a hexadecimal notation (e.g. DEADBEEF).
- Raises:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> OctetString('some apples') <OctetString value object, payload [some apples]> >>> OctetString('some apples') + ' and oranges' <OctetString value object, payload [some apples and oranges]> >>> OctetString('some apples').asOctets() b'some apples' >>> OctetString('some apples').prettyPrint() 'some apples' >>> SomeString = OctetString.withSize(3, 12) >>> SomeString(hexValue='deadbeef').asOctets() b'\xde\xad\xbe\xef' >>> SomeString(hexValue='deadbeef').prettyPrint() '0xdeadbeef' >>>
- subtypeSpec = <ConstraintsIntersection object, consts <ValueSizeConstraint object, consts 0, 65535>>¶
Set (on class, not on instance) or return a
ConstraintsIntersectionobject imposing constraints on ASN.1 type initialization values.
- setFixedLength(value)¶
Pin this string to an exact length, and return it for chaining.
A fixed length is not a constraint pyasn1 carries: it is what tells the table index code how many sub-identifiers to take for this column, which it cannot work out from the value alone.
- isFixedLength()¶
Whether a fixed length has been pinned.
- getFixedLength()¶
The pinned length, or None.
- clone(*args, **kwargs)¶
Clone, carrying the fixed length across.
pyasn1’s clone knows nothing about the fixed length, so a plain clone would silently drop it and break indexing on the copy.
- subtype(*args, **kwargs)¶
Subtype, carrying the fixed length across, for the same reason as clone.
- classmethod withSize(minimum, maximum)¶
Create 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
IpAddressclass 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> IpAddress('127.0.0.1') <IpAddress value object, payload [127.0.0.1]> >>> IpAddress(hexValue='7f000001').prettyPrint() '127.0.0.1' >>> IpAddress(hexValue='7f000001').asOctets() b'\x7f\x00\x00\x01' >>> IpAddress('\x7f\x00\x00\x01') <IpAddress value object, payload [127.0.0.1]> >>>
ObjectIdentifier type¶
- class pysnmp.proto.rfc1902.ObjectIdentifier(initializer)¶
Creates an instance of SNMP OBJECT IDENTIFIER class.
The
ObjectIdentifiertype 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> ObjectIdentifier((1, 3, 6)) <ObjectIdentifier value object, payload [1.3.6]> >>> ObjectIdentifier('1.3.6') <ObjectIdentifier value object, payload [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.
Counter32type 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Counter32(1234) <Counter32 value object, payload [1234]> >>> Counter32(1) + 1 <Counter32 value object, payload [2]> >>> int(Counter32(321)) 321 >>>
Gauge32 type¶
- class pysnmp.proto.rfc1902.Gauge32(initializer)¶
Creates an instance of SNMP Gauge32 class.
Gauge32type 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Gauge32(1234) <Gauge32 value object, payload [1234]> >>> Gauge32(1) + 1 <Gauge32 value object, payload [2]> >>> int(Gauge32(321)) 321 >>>
Unsigned32 type¶
- class pysnmp.proto.rfc1902.Unsigned32(initializer)¶
Creates an instance of SNMP Unsigned32 class.
Unsigned32type 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Unsigned32(1234) <Unsigned32 value object, payload [1234]> >>> Unsigned32(1) + 1 <Unsigned32 value object, payload [2]> >>> int(Unsigned32(321)) 321 >>>
TimeTicks type¶
- class pysnmp.proto.rfc1902.TimeTicks(initializer)¶
Creates an instance of SNMP TimeTicks class.
TimeTickstype 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> TimeTicks(1234) <TimeTicks value object, payload [1234]> >>> TimeTicks(1) + 1 <TimeTicks value object, payload [2]> >>> int(TimeTicks(321)) 321 >>>
Opaque type¶
- class pysnmp.proto.rfc1902.Opaque(initializer)¶
Creates an instance of SNMP Opaque class.
The
Opaquetype 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Opaque('some apples') <Opaque value object, payload [some apples]> >>> Opaque('some apples') + ' and oranges' <Opaque value object, payload [some apples and oranges]> >>> Opaque('some apples').asOctets() b'some apples' >>> Opaque('some apples').prettyPrint() 'some apples' >>> Opaque(hexValue='deadbeef').asOctets() b'\xde\xad\xbe\xef' >>> Opaque(hexValue='deadbeef').prettyPrint() '0xdeadbeef' >>>
Counter64 type¶
- class pysnmp.proto.rfc1902.Counter64(initializer)¶
Creates an instance of SNMP Counter64 class.
Counter64type 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:
pyasn1.error.PyAsn1Error – On constraint violation or bad initializer.
Examples
>>> from pysnmp.proto.rfc1902 import * >>> Counter64(1234) <Counter64 value object, payload [1234]> >>> Counter64(1) + 1 <Counter64 value object, payload [2]> >>> int(Counter64(321)) 321 >>>
Bits type¶
- class pysnmp.proto.rfc1902.Bits(initializer)¶
Creates an instance of SNMP BITS class.
The
Bitstype 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
OctetStringclass instance.- Other Parameters:
hexValue (str) – Python string representing octets in a hexadecimal notation (e.g. DEADBEEF).
- Raises:
pyasn1.error.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 value object, payload [apple, orange]> >>> SomeBits('\x80') <Bits value object, payload [apple]> >>> SomeBits(hexValue='80') <Bits value object, payload [apple]> >>> SomeBits(hexValue='80').prettyPrint() 'apple' >>>
Build a subclass on the fly when named bits are given to the constructor.
- static __new__(cls, *args, **kwargs)¶
Build a subclass on the fly when named bits are given to the constructor.
- prettyIn(bits)¶
Accept either bit names or the raw octets they pack into.
Bit 0 is the high bit of the first octet, not the low bit – RFC 1902 numbers them the other way round from how they would fall out of a shift.
- prettyOut(value)¶
Render as the names of the bits that are set, in bit order.
- classmethod withNamedBits(**values)¶
Create a subclass with discreet named bits constraint.
Reduce fully duplicate enumerations along the way.