November 5, 2024

SNMP Module in Python

Simple Network Management Protocol (SNMP) is used for network management, including monitoring and configuring network devices. In Python, you can work with SNMP using several libraries, such as pysnmp and snmpwalk. This guide will focus on how to use the pysnmp library to perform SNMP operations.

1. Installing the pysnmp Library

The pysnmp library provides a pure-Python implementation of SNMP. You can install it using pip:

pip install pysnmp

2. Basic Operations with pysnmp

With pysnmp, you can perform various SNMP operations, including querying and setting SNMP data. Here are examples of basic SNMP operations using pysnmp.

2.1 SNMP Get Request

An SNMP Get request retrieves the value of a specific OID (Object Identifier) from an SNMP-enabled device.

Example

from pysnmp.hlapi import *

def snmp_get(target, oid):
    iterator = nextCmd(
        SnmpEngine(),
        CommunityData('public', mpModel=0),
        UdpTransportTarget((target, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(oid))
    )

    for (errorIndication, errorStatus, errorIndex, varBinds) in iterator:
        if errorIndication:
            print(errorIndication)
            return None
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(), errorIndex))
            return None
        else:
            for varBind in varBinds:
                return ' = '.join([x.prettyPrint() for x in varBind])

# Example usage
target_ip = '192.168.1.1'
oid = '1.3.6.1.2.1.1.1.0'  # System description
print(snmp_get(target_ip, oid))

This script queries the system description of a device with IP address 192.168.1.1.

2.2 SNMP Set Request

An SNMP Set request is used to modify the value of a specific OID.

Example

def snmp_set(target, oid, value):
    iterator = setCmd(
        SnmpEngine(),
        CommunityData('private', mpModel=0),
        UdpTransportTarget((target, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(oid), value)
    )

    for (errorIndication, errorStatus, errorIndex, varBinds) in iterator:
        if errorIndication:
            print(errorIndication)
            return None
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(), errorIndex))
            return None
        else:
            return 'Success'

# Example usage
target_ip = '192.168.1.1'
oid = '1.3.6.1.2.1.1.5.0'  # System name
value = 'New System Name'
print(snmp_set(target_ip, oid, value))

This script sets the system name of a device with IP address 192.168.1.1.

3. SNMP Walk

SNMP Walk is used to retrieve a subtree of values under a specific OID.

Example

def snmp_walk(target, oid):
    iterator = nextCmd(
        SnmpEngine(),
        CommunityData('public', mpModel=0),
        UdpTransportTarget((target, 161)),
        ContextData(),
        ObjectType(ObjectIdentity(oid)),
        lexicographicMode=False
    )

    results = []
    for (errorIndication, errorStatus, errorIndex, varBinds) in iterator:
        if errorIndication:
            print(errorIndication)
            return None
        elif errorStatus:
            print('%s at %s' % (errorStatus.prettyPrint(), errorIndex))
            return None
        else:
            for varBind in varBinds:
                results.append(' = '.join([x.prettyPrint() for x in varBind]))

    return results

# Example usage
target_ip = '192.168.1.1'
oid = '1.3.6.1.2.1.2'  # Interfaces table
for result in snmp_walk(target_ip, oid):
    print(result)

This script performs an SNMP Walk on the Interfaces table OID of a device with IP address 192.168.1.1.

4. Summary

The pysnmp library is a powerful tool for working with SNMP in Python. It allows you to perform SNMP Get, Set, and Walk operations, making it easy to manage and monitor network devices programmatically. Understanding these basic operations provides a foundation for more advanced network management tasks.