CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pysnmp

A comprehensive Python SNMP library supporting v1/v2c/v3 with authentication and privacy protocols

84

0.94x
Overview
Eval results
Files

data-types.mddocs/

SNMP Data Types and Exceptions

PySNMP implements the complete set of SNMP data types from RFC 1902 and exception values from RFC 1905, providing type-safe handling of SNMP variables and comprehensive error reporting.

Capabilities

Basic Data Types

Core SNMP data types for representing various kinds of management information.

Null Type

Represents absence of a value or placeholder in SNMP operations.

class Null:
    def __init__(self, value: str | None = None):
        """
        Create a NULL value.
        
        Parameters:
        - value: Ignored (NULL has no value)
        """

Usage Example:

from pysnmp.proto.rfc1902 import Null

null_value = Null()
print(null_value)  # Empty string representation

Integer Types

32-bit signed integer values with optional named values for enumerated types.

class Integer32:
    def __init__(self, value: int = 0):
        """
        Create a 32-bit signed integer (-2147483648 to 2147483647).
        
        Parameters:
        - value: Integer value
        """

class Integer(Integer32):
    """Alias for Integer32 (backward compatibility)"""

Usage Example:

from pysnmp.proto.rfc1902 import Integer32, Integer

# Basic integer
status = Integer32(1)

# Using alias
admin_status = Integer(1)  # Same as Integer32

# Named values for enumeration
from pysnmp.proto.rfc1902 import Integer32

class IfAdminStatus(Integer32):
    namedValues = {
        'up': 1,
        'down': 2,
        'testing': 3
    }

interface_status = IfAdminStatus('up')  # Creates Integer32(1)

Octet String Type

Variable-length sequences of octets (bytes) for text, binary data, and addresses.

class OctetString:
    def __init__(self, value: str | bytes = b''):
        """
        Create an octet string.
        
        Parameters:
        - value: String or bytes value
        """
    
    def asOctets(self) -> bytes:
        """Return value as bytes"""
    
    def asNumbers(self) -> tuple[int, ...]:
        """Return value as tuple of integers (0-255)"""

Usage Example:

from pysnmp.proto.rfc1902 import OctetString

# Text string
sys_descr = OctetString('Linux router 4.15.0')

# Binary data  
mac_address = OctetString(b'\\x00\\x11\\x22\\x33\\x44\\x55')

# Access as bytes
binary_data = sys_descr.asOctets()  # b'Linux router 4.15.0'

# Access as numbers
mac_numbers = mac_address.asNumbers()  # (0, 17, 34, 51, 68, 85)

Object Identifier Type

Hierarchical object identifiers (OIDs) for naming management objects.

class ObjectIdentifier:
    def __init__(self, value: str | tuple[int, ...] = ()):
        """
        Create an object identifier.
        
        Parameters:
        - value: OID as dotted string or tuple of integers
        """
    
    def asTuple(self) -> tuple[int, ...]:
        """Return OID as tuple of integers"""

Usage Example:

from pysnmp.proto.rfc1902 import ObjectIdentifier

# From dotted string
sys_descr_oid = ObjectIdentifier('1.3.6.1.2.1.1.1.0')

# From tuple
if_table_oid = ObjectIdentifier((1, 3, 6, 1, 2, 1, 2, 2))

# Access as tuple
oid_tuple = sys_descr_oid.asTuple()  # (1, 3, 6, 1, 2, 1, 1, 1, 0)

Network Address Types

Specialized types for network addressing and identification.

IP Address Type

IPv4 addresses represented as 4-octet values.

class IpAddress(OctetString):
    def __init__(self, value: str | bytes = '0.0.0.0'):
        """
        Create an IPv4 address (4 octets).
        
        Parameters:
        - value: IPv4 address as string or 4 bytes
        """

Usage Example:

from pysnmp.proto.rfc1902 import IpAddress

# From string
router_ip = IpAddress('192.168.1.1')

# From bytes
gateway_ip = IpAddress(b'\\xc0\\xa8\\x01\\x01')  # 192.168.1.1

print(router_ip)  # 192.168.1.1

Counter Types

Monotonically increasing counters for statistical information.

32-bit Counter

Non-negative integers that wrap at 2^32.

class Counter32:
    def __init__(self, value: int = 0):
        """
        Create a 32-bit counter (0 to 4294967295).
        
        Parameters:
        - value: Counter value
        """

64-bit Counter

Extended counters for high-speed interfaces and large values.

class Counter64:
    def __init__(self, value: int = 0):
        """
        Create a 64-bit counter (0 to 18446744073709551615).
        
        Parameters:
        - value: Counter value
        """

Usage Example:

from pysnmp.proto.rfc1902 import Counter32, Counter64

# 32-bit counter for interface packets
if_in_octets = Counter32(1234567890)

# 64-bit counter for high-speed interface bytes
if_in_octets_64 = Counter64(12345678901234567890)

Gauge Types

Non-negative integers that can increase or decrease.

32-bit Gauge

Represents current values that can fluctuate.

class Gauge32:
    def __init__(self, value: int = 0):
        """
        Create a 32-bit gauge (0 to 4294967295).
        
        Parameters:
        - value: Gauge value
        """

class Unsigned32(Gauge32):
    """Alias for Gauge32"""

Usage Example:

from pysnmp.proto.rfc1902 import Gauge32, Unsigned32

# Interface speed in bits per second
if_speed = Gauge32(100000000)  # 100 Mbps

# Using alias
buffer_size = Unsigned32(65536)  # Same as Gauge32

Time Type

Time intervals and timestamps in centiseconds.

class TimeTicks:
    def __init__(self, value: int = 0):
        """
        Create a time value in 1/100th seconds.
        
        Parameters:
        - value: Time in centiseconds
        """

Usage Example:

from pysnmp.proto.rfc1902 import TimeTicks

# System uptime (5 minutes = 30000 centiseconds)
sys_uptime = TimeTicks(30000)

# Convert to seconds
uptime_seconds = int(sys_uptime) / 100  # 300.0 seconds

Specialized Types

Opaque Type

Encapsulates arbitrary data using ASN.1 encoding.

class Opaque(OctetString):
    def __init__(self, value: bytes = b''):
        """
        Create an opaque value for arbitrary ASN.1 encoded data.
        
        Parameters:
        - value: ASN.1 encoded bytes
        """

Bits Type

Bit strings for representing sets of binary flags.

class Bits(OctetString):
    def __init__(self, value: str = ''):
        """
        Create a bit string.
        
        Parameters:
        - value: Bit string representation
        """

Usage Example:

from pysnmp.proto.rfc1902 import Bits

# Interface capabilities
if_capabilities = Bits("10110000")  # Binary representation

# Named bits for enumerated capabilities
class IfCapabilities(Bits):
    namedValues = {
        'autoNegotiation': 0,
        'fullDuplex': 1,
        'halfDuplex': 2,
        'gigabit': 3
    }

capabilities = IfCapabilities(('autoNegotiation', 'fullDuplex'))

Exception Values

SNMP exception values indicating various error conditions during variable access.

NoSuchObject Exception

Indicates that the specified object does not exist at the given OID.

class NoSuchObject:
    """Exception value indicating object doesn't exist at OID"""

noSuchObject: NoSuchObject
"""Pre-instantiated NoSuchObject instance"""

NoSuchInstance Exception

Indicates that no instance exists at the specified OID.

class NoSuchInstance:
    """Exception value indicating instance doesn't exist at OID"""

noSuchInstance: NoSuchInstance
"""Pre-instantiated NoSuchInstance instance"""

EndOfMibView Exception

Indicates the end of the MIB tree during walk operations.

class EndOfMibView:
    """Exception value indicating end of MIB traversal"""

endOfMibView: EndOfMibView
"""Pre-instantiated EndOfMibView instance"""

### UnSpecified Exception

Indicates unspecified values in SNMP operations.

```python { .api }
class UnSpecified:
    """Exception value indicating unspecified value"""

unSpecified: UnSpecified
"""Pre-instantiated UnSpecified instance"""

Usage Example:

from pysnmp.proto.rfc1905 import noSuchObject, noSuchInstance, endOfMibView, unSpecified

# Check for exception values in responses
def process_varbinds(varBinds):
    for oid, value in varBinds:
        if value is noSuchObject:
            print(f"Object {oid} does not exist")
        elif value is noSuchInstance:
            print(f"No instance at {oid}")
        elif value is endOfMibView:
            print(f"End of MIB reached at {oid}")
        elif value is unSpecified:
            print(f"Unspecified value at {oid}")
        else:
            print(f"{oid} = {value}")

SMI Objects

Structure of Management Information objects for high-level MIB interaction.

ObjectIdentity

Represents MIB variable identity with automatic OID/name resolution.

class ObjectIdentity:
    def __init__(self, *args, **kwargs):
        """
        Create MIB object identity with OID/name resolution.
        
        Parameters:
        - args: OID as string, tuple, or MIB symbol
        - kwargs: Additional options for MIB resolution
        """

ObjectType

Combines object identity with a value for SNMP operations.

class ObjectType(ObjectIdentity):
    def __init__(self, objectIdentity: ObjectIdentity, objectSyntax=None):
        """
        Create MIB object type with identity and value.
        
        Parameters:
        - objectIdentity: Object identity (OID or MIB symbol)
        - objectSyntax: Object value (SNMP data type)
        """

NotificationType

Represents SNMP notifications with MIB information.

class NotificationType(ObjectIdentity):
    def __init__(self, *args, **kwargs):
        """
        Create SNMP notification type.
        
        Parameters:
        - args: Notification OID or MIB symbol
        - kwargs: Additional notification options
        """

Usage Example:

from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType, NotificationType
from pysnmp.proto.rfc1902 import OctetString

# Object identity from OID
sys_descr_id = ObjectIdentity('1.3.6.1.2.1.1.1.0')

# Object type with value  
sys_contact = ObjectType(
    ObjectIdentity('1.3.6.1.2.1.1.4.0'),
    OctetString('admin@company.com')
)

# Notification type
link_down_trap = NotificationType(
    ObjectIdentity('1.3.6.1.6.3.1.1.5.3')  # linkDown
)

Type Construction Patterns

Creating Variable Bindings

from pysnmp.smi.rfc1902 import ObjectType, ObjectIdentity
from pysnmp.proto.rfc1902 import OctetString, Counter32, Gauge32

# Simple variable binding for GET
sys_name = ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0'))

# Variable binding for SET with value
sys_location = ObjectType(
    ObjectIdentity('1.3.6.1.2.1.1.6.0'),
    OctetString('Server Room A')
)

# Multiple variable bindings
var_binds = [
    ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),  # sysDescr
    ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0')),  # sysUpTime
    ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0'))   # sysName
]

Type Conversion and Validation

from pysnmp.proto.rfc1902 import *

# Type conversion
string_value = OctetString("12345")
int_value = Integer32(int(string_value))  # Convert string to int

# Range validation (automatic in constructors)
try:
    large_int = Integer32(5000000000)  # Raises error (> 2^31-1)
except Exception as e:
    print(f"Value out of range: {e}")

# Gauge vs Counter selection
current_connections = Gauge32(150)      # Can go up or down
total_packets = Counter32(1000000)      # Only increases (wraps at 2^32)

Working with Complex Types

from pysnmp.proto.rfc1902 import *

# IP Address handling
router_ip = IpAddress('10.1.1.1')
ip_bytes = router_ip.asOctets()          # b'\\n\\x01\\x01\\x01'
ip_numbers = router_ip.asNumbers()       # (10, 1, 1, 1)

# Object Identifier manipulation
base_oid = ObjectIdentifier('1.3.6.1.2.1.1')
instance_oid = base_oid + (1, 0)         # Append .1.0
print(instance_oid)                      # 1.3.6.1.2.1.1.1.0

# Time calculations
uptime = TimeTicks(36000)                # 6 minutes in centiseconds
uptime_minutes = float(uptime) / 6000    # Convert to minutes: 6.0

Install with Tessl CLI

npx tessl i tessl/pypi-pysnmp

docs

authentication.md

data-types.md

high-level-api.md

index.md

tile.json