0
# SNMP Data Types and Exceptions
1
2
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.
3
4
## Capabilities
5
6
### Basic Data Types
7
8
Core SNMP data types for representing various kinds of management information.
9
10
#### Null Type
11
12
Represents absence of a value or placeholder in SNMP operations.
13
14
```python { .api }
15
class Null:
16
def __init__(self, value: str | None = None):
17
"""
18
Create a NULL value.
19
20
Parameters:
21
- value: Ignored (NULL has no value)
22
"""
23
```
24
25
Usage Example:
26
27
```python
28
from pysnmp.proto.rfc1902 import Null
29
30
null_value = Null()
31
print(null_value) # Empty string representation
32
```
33
34
#### Integer Types
35
36
32-bit signed integer values with optional named values for enumerated types.
37
38
```python { .api }
39
class Integer32:
40
def __init__(self, value: int = 0):
41
"""
42
Create a 32-bit signed integer (-2147483648 to 2147483647).
43
44
Parameters:
45
- value: Integer value
46
"""
47
48
class Integer(Integer32):
49
"""Alias for Integer32 (backward compatibility)"""
50
```
51
52
Usage Example:
53
54
```python
55
from pysnmp.proto.rfc1902 import Integer32, Integer
56
57
# Basic integer
58
status = Integer32(1)
59
60
# Using alias
61
admin_status = Integer(1) # Same as Integer32
62
63
# Named values for enumeration
64
from pysnmp.proto.rfc1902 import Integer32
65
66
class IfAdminStatus(Integer32):
67
namedValues = {
68
'up': 1,
69
'down': 2,
70
'testing': 3
71
}
72
73
interface_status = IfAdminStatus('up') # Creates Integer32(1)
74
```
75
76
#### Octet String Type
77
78
Variable-length sequences of octets (bytes) for text, binary data, and addresses.
79
80
```python { .api }
81
class OctetString:
82
def __init__(self, value: str | bytes = b''):
83
"""
84
Create an octet string.
85
86
Parameters:
87
- value: String or bytes value
88
"""
89
90
def asOctets(self) -> bytes:
91
"""Return value as bytes"""
92
93
def asNumbers(self) -> tuple[int, ...]:
94
"""Return value as tuple of integers (0-255)"""
95
```
96
97
Usage Example:
98
99
```python
100
from pysnmp.proto.rfc1902 import OctetString
101
102
# Text string
103
sys_descr = OctetString('Linux router 4.15.0')
104
105
# Binary data
106
mac_address = OctetString(b'\\x00\\x11\\x22\\x33\\x44\\x55')
107
108
# Access as bytes
109
binary_data = sys_descr.asOctets() # b'Linux router 4.15.0'
110
111
# Access as numbers
112
mac_numbers = mac_address.asNumbers() # (0, 17, 34, 51, 68, 85)
113
```
114
115
#### Object Identifier Type
116
117
Hierarchical object identifiers (OIDs) for naming management objects.
118
119
```python { .api }
120
class ObjectIdentifier:
121
def __init__(self, value: str | tuple[int, ...] = ()):
122
"""
123
Create an object identifier.
124
125
Parameters:
126
- value: OID as dotted string or tuple of integers
127
"""
128
129
def asTuple(self) -> tuple[int, ...]:
130
"""Return OID as tuple of integers"""
131
```
132
133
Usage Example:
134
135
```python
136
from pysnmp.proto.rfc1902 import ObjectIdentifier
137
138
# From dotted string
139
sys_descr_oid = ObjectIdentifier('1.3.6.1.2.1.1.1.0')
140
141
# From tuple
142
if_table_oid = ObjectIdentifier((1, 3, 6, 1, 2, 1, 2, 2))
143
144
# Access as tuple
145
oid_tuple = sys_descr_oid.asTuple() # (1, 3, 6, 1, 2, 1, 1, 1, 0)
146
```
147
148
### Network Address Types
149
150
Specialized types for network addressing and identification.
151
152
#### IP Address Type
153
154
IPv4 addresses represented as 4-octet values.
155
156
```python { .api }
157
class IpAddress(OctetString):
158
def __init__(self, value: str | bytes = '0.0.0.0'):
159
"""
160
Create an IPv4 address (4 octets).
161
162
Parameters:
163
- value: IPv4 address as string or 4 bytes
164
"""
165
```
166
167
Usage Example:
168
169
```python
170
from pysnmp.proto.rfc1902 import IpAddress
171
172
# From string
173
router_ip = IpAddress('192.168.1.1')
174
175
# From bytes
176
gateway_ip = IpAddress(b'\\xc0\\xa8\\x01\\x01') # 192.168.1.1
177
178
print(router_ip) # 192.168.1.1
179
```
180
181
### Counter Types
182
183
Monotonically increasing counters for statistical information.
184
185
#### 32-bit Counter
186
187
Non-negative integers that wrap at 2^32.
188
189
```python { .api }
190
class Counter32:
191
def __init__(self, value: int = 0):
192
"""
193
Create a 32-bit counter (0 to 4294967295).
194
195
Parameters:
196
- value: Counter value
197
"""
198
```
199
200
#### 64-bit Counter
201
202
Extended counters for high-speed interfaces and large values.
203
204
```python { .api }
205
class Counter64:
206
def __init__(self, value: int = 0):
207
"""
208
Create a 64-bit counter (0 to 18446744073709551615).
209
210
Parameters:
211
- value: Counter value
212
"""
213
```
214
215
Usage Example:
216
217
```python
218
from pysnmp.proto.rfc1902 import Counter32, Counter64
219
220
# 32-bit counter for interface packets
221
if_in_octets = Counter32(1234567890)
222
223
# 64-bit counter for high-speed interface bytes
224
if_in_octets_64 = Counter64(12345678901234567890)
225
```
226
227
### Gauge Types
228
229
Non-negative integers that can increase or decrease.
230
231
#### 32-bit Gauge
232
233
Represents current values that can fluctuate.
234
235
```python { .api }
236
class Gauge32:
237
def __init__(self, value: int = 0):
238
"""
239
Create a 32-bit gauge (0 to 4294967295).
240
241
Parameters:
242
- value: Gauge value
243
"""
244
245
class Unsigned32(Gauge32):
246
"""Alias for Gauge32"""
247
```
248
249
Usage Example:
250
251
```python
252
from pysnmp.proto.rfc1902 import Gauge32, Unsigned32
253
254
# Interface speed in bits per second
255
if_speed = Gauge32(100000000) # 100 Mbps
256
257
# Using alias
258
buffer_size = Unsigned32(65536) # Same as Gauge32
259
```
260
261
### Time Type
262
263
Time intervals and timestamps in centiseconds.
264
265
```python { .api }
266
class TimeTicks:
267
def __init__(self, value: int = 0):
268
"""
269
Create a time value in 1/100th seconds.
270
271
Parameters:
272
- value: Time in centiseconds
273
"""
274
```
275
276
Usage Example:
277
278
```python
279
from pysnmp.proto.rfc1902 import TimeTicks
280
281
# System uptime (5 minutes = 30000 centiseconds)
282
sys_uptime = TimeTicks(30000)
283
284
# Convert to seconds
285
uptime_seconds = int(sys_uptime) / 100 # 300.0 seconds
286
```
287
288
### Specialized Types
289
290
#### Opaque Type
291
292
Encapsulates arbitrary data using ASN.1 encoding.
293
294
```python { .api }
295
class Opaque(OctetString):
296
def __init__(self, value: bytes = b''):
297
"""
298
Create an opaque value for arbitrary ASN.1 encoded data.
299
300
Parameters:
301
- value: ASN.1 encoded bytes
302
"""
303
```
304
305
#### Bits Type
306
307
Bit strings for representing sets of binary flags.
308
309
```python { .api }
310
class Bits(OctetString):
311
def __init__(self, value: str = ''):
312
"""
313
Create a bit string.
314
315
Parameters:
316
- value: Bit string representation
317
"""
318
```
319
320
Usage Example:
321
322
```python
323
from pysnmp.proto.rfc1902 import Bits
324
325
# Interface capabilities
326
if_capabilities = Bits("10110000") # Binary representation
327
328
# Named bits for enumerated capabilities
329
class IfCapabilities(Bits):
330
namedValues = {
331
'autoNegotiation': 0,
332
'fullDuplex': 1,
333
'halfDuplex': 2,
334
'gigabit': 3
335
}
336
337
capabilities = IfCapabilities(('autoNegotiation', 'fullDuplex'))
338
```
339
340
## Exception Values
341
342
SNMP exception values indicating various error conditions during variable access.
343
344
### NoSuchObject Exception
345
346
Indicates that the specified object does not exist at the given OID.
347
348
```python { .api }
349
class NoSuchObject:
350
"""Exception value indicating object doesn't exist at OID"""
351
352
noSuchObject: NoSuchObject
353
"""Pre-instantiated NoSuchObject instance"""
354
```
355
356
### NoSuchInstance Exception
357
358
Indicates that no instance exists at the specified OID.
359
360
```python { .api }
361
class NoSuchInstance:
362
"""Exception value indicating instance doesn't exist at OID"""
363
364
noSuchInstance: NoSuchInstance
365
"""Pre-instantiated NoSuchInstance instance"""
366
```
367
368
### EndOfMibView Exception
369
370
Indicates the end of the MIB tree during walk operations.
371
372
```python { .api }
373
class EndOfMibView:
374
"""Exception value indicating end of MIB traversal"""
375
376
endOfMibView: EndOfMibView
377
"""Pre-instantiated EndOfMibView instance"""
378
379
### UnSpecified Exception
380
381
Indicates unspecified values in SNMP operations.
382
383
```python { .api }
384
class UnSpecified:
385
"""Exception value indicating unspecified value"""
386
387
unSpecified: UnSpecified
388
"""Pre-instantiated UnSpecified instance"""
389
```
390
391
Usage Example:
392
393
```python
394
from pysnmp.proto.rfc1905 import noSuchObject, noSuchInstance, endOfMibView, unSpecified
395
396
# Check for exception values in responses
397
def process_varbinds(varBinds):
398
for oid, value in varBinds:
399
if value is noSuchObject:
400
print(f"Object {oid} does not exist")
401
elif value is noSuchInstance:
402
print(f"No instance at {oid}")
403
elif value is endOfMibView:
404
print(f"End of MIB reached at {oid}")
405
elif value is unSpecified:
406
print(f"Unspecified value at {oid}")
407
else:
408
print(f"{oid} = {value}")
409
```
410
411
## SMI Objects
412
413
Structure of Management Information objects for high-level MIB interaction.
414
415
### ObjectIdentity
416
417
Represents MIB variable identity with automatic OID/name resolution.
418
419
```python { .api }
420
class ObjectIdentity:
421
def __init__(self, *args, **kwargs):
422
"""
423
Create MIB object identity with OID/name resolution.
424
425
Parameters:
426
- args: OID as string, tuple, or MIB symbol
427
- kwargs: Additional options for MIB resolution
428
"""
429
```
430
431
### ObjectType
432
433
Combines object identity with a value for SNMP operations.
434
435
```python { .api }
436
class ObjectType(ObjectIdentity):
437
def __init__(self, objectIdentity: ObjectIdentity, objectSyntax=None):
438
"""
439
Create MIB object type with identity and value.
440
441
Parameters:
442
- objectIdentity: Object identity (OID or MIB symbol)
443
- objectSyntax: Object value (SNMP data type)
444
"""
445
```
446
447
### NotificationType
448
449
Represents SNMP notifications with MIB information.
450
451
```python { .api }
452
class NotificationType(ObjectIdentity):
453
def __init__(self, *args, **kwargs):
454
"""
455
Create SNMP notification type.
456
457
Parameters:
458
- args: Notification OID or MIB symbol
459
- kwargs: Additional notification options
460
"""
461
```
462
463
Usage Example:
464
465
```python
466
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType, NotificationType
467
from pysnmp.proto.rfc1902 import OctetString
468
469
# Object identity from OID
470
sys_descr_id = ObjectIdentity('1.3.6.1.2.1.1.1.0')
471
472
# Object type with value
473
sys_contact = ObjectType(
474
ObjectIdentity('1.3.6.1.2.1.1.4.0'),
475
OctetString('admin@company.com')
476
)
477
478
# Notification type
479
link_down_trap = NotificationType(
480
ObjectIdentity('1.3.6.1.6.3.1.1.5.3') # linkDown
481
)
482
```
483
484
## Type Construction Patterns
485
486
### Creating Variable Bindings
487
488
```python
489
from pysnmp.smi.rfc1902 import ObjectType, ObjectIdentity
490
from pysnmp.proto.rfc1902 import OctetString, Counter32, Gauge32
491
492
# Simple variable binding for GET
493
sys_name = ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0'))
494
495
# Variable binding for SET with value
496
sys_location = ObjectType(
497
ObjectIdentity('1.3.6.1.2.1.1.6.0'),
498
OctetString('Server Room A')
499
)
500
501
# Multiple variable bindings
502
var_binds = [
503
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')), # sysDescr
504
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.3.0')), # sysUpTime
505
ObjectType(ObjectIdentity('1.3.6.1.2.1.1.5.0')) # sysName
506
]
507
```
508
509
### Type Conversion and Validation
510
511
```python
512
from pysnmp.proto.rfc1902 import *
513
514
# Type conversion
515
string_value = OctetString("12345")
516
int_value = Integer32(int(string_value)) # Convert string to int
517
518
# Range validation (automatic in constructors)
519
try:
520
large_int = Integer32(5000000000) # Raises error (> 2^31-1)
521
except Exception as e:
522
print(f"Value out of range: {e}")
523
524
# Gauge vs Counter selection
525
current_connections = Gauge32(150) # Can go up or down
526
total_packets = Counter32(1000000) # Only increases (wraps at 2^32)
527
```
528
529
### Working with Complex Types
530
531
```python
532
from pysnmp.proto.rfc1902 import *
533
534
# IP Address handling
535
router_ip = IpAddress('10.1.1.1')
536
ip_bytes = router_ip.asOctets() # b'\\n\\x01\\x01\\x01'
537
ip_numbers = router_ip.asNumbers() # (10, 1, 1, 1)
538
539
# Object Identifier manipulation
540
base_oid = ObjectIdentifier('1.3.6.1.2.1.1')
541
instance_oid = base_oid + (1, 0) # Append .1.0
542
print(instance_oid) # 1.3.6.1.2.1.1.1.0
543
544
# Time calculations
545
uptime = TimeTicks(36000) # 6 minutes in centiseconds
546
uptime_minutes = float(uptime) / 6000 # Convert to minutes: 6.0
547
```