Learning Python Network Programming

(Sean Pound) #1
Chapter 5

You can see that cmdgen takes the following parameters:



  • CommunityData(): Set the community string as public.

  • UdpTransportTarget(): This is the host target, where the snmp agent is
    running. This is specified in a pair of the hostname and the UDP port.

  • MibVariable: This is a tuple of values that includes the MIB version number
    and the MIB target string (which in this case is sysDescr; this refers to the
    description of the system).


The output of this command consists of a four-value tuple. Out of those, three are
related to the errors returned by the command generator, and the fourth one is
related to the actual variables that bind the returned data.


The following example shows how the preceding method can be used for fetching
the SNMP host description string from a running SNMP daemon:


from pysnmp.entity.rfc3413.oneliner import cmdgen

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

if __name__ == '__manin__':
cmd_generator = cmdgen.CommandGenerator()

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
)

# Check for errors and print out results
if error_notify:
print(error_notify)
elif error_status:
print(error_status)
else:
for name, val in var_binds:
print('%s = %s' % (name.prettyPrint(),
val.prettyPrint()))
Free download pdf