Learning Python Network Programming

(Sean Pound) #1

Interacting with Remote Systems


SNMP is a client/server-based network protocol. The server daemon provides the
requested information to the clients. In your machine, if SNMP has been installed
and configured properly, then you can use the snmpwalk utility command to query
the basic system information by using the following syntax:


snmpwalk -v2c -c public localhost


iso.3.6.1.2.1.1.1.0 = STRING: "Linux debian6box 2.6.32-5-686 #1 SMP
Tue May 13 16:33:32 UTC 2014 i686"


iso.3.6.1.2.1.1.2.0 = OID: iso.3.6.1.4.1.8072.3.2.10


iso.3.6.1.2.1.1.3.0 = Timeticks: (88855240) 10 days, 6:49:12.40


iso.3.6.1.2.1.1.4.0 = STRING: "Me [email protected]"


iso.3.6.1.2.1.1.5.0 = STRING: "debian6box"


iso.3.6.1.2.1.1.6.0 = STRING: "Sitting on the Dock of the Bay"


The output of the preceding command will show the MIB number and its values. For
example, the MIB number iso.3.6.1.2.1.1.1.0 shows that it's a string type value,
such as Linux debian6box 2.6.32-5-686 #1 SMP Tue May 13 16:33:32 UTC
2014 i686.


In Python, you can use a third-party library called pysnmp for interfacing with the
snmp daemon. You can install the pysnmp module by using pip.


$ pip install pysnmp


This module provides a useful wrapper for the snmp commands. Let's learn how to
create an snmpwalk command. To begin, import a command generator.


from pysnmp.entity.rfc3413.oneliner import cmdgen
cmd_generator = cmdgen.CommandGenerator()

Then define the necessary default values for the connection assuming that the snmpd
daemon has been running on port 161 of the local machine and the community
string has been set to public.


SNMP_HOST = 'localhost'
SNMP_PORT = 161
SNMP_COMMUNITY = 'public'

Now invoke the getCmd() method with the help of the necessary data.


error_notify, error_status, error_index, var_binds =
cmd_generator.getCmd(
cmdgen.CommunityData(SNMP_COMMUNITY),
cmdgen.UdpTransportTarget((SNMP_HOST, SNMP_PORT)),
cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),
lookupNames=True, lookupValues=True
)
Free download pdf