A comprehensive Python SNMP library supporting v1/v2c/v3 with authentication and privacy protocols
84
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.
Core SNMP data types for representing various kinds of management information.
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 representation32-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)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)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)Specialized types for network addressing and identification.
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.1Monotonically increasing counters for statistical information.
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
"""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)Non-negative integers that can increase or decrease.
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 Gauge32Time 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 secondsEncapsulates 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
"""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'))SNMP exception values indicating various error conditions during variable access.
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"""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"""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}")Structure of Management Information objects for high-level MIB interaction.
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
"""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)
"""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
)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
]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)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.0Install with Tessl CLI
npx tessl i tessl/pypi-pysnmpevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10