Search code examples
pythonsnmppysnmp

Is it possible to pull the interface name and interface status from this table?


Ultimately, I would like to be able to have the output in the format of:

'Interface lo is up'

The output is:

['IF-MIB::ifDescr.1 = lo', 'IF-MIB::ifOperStatus.1 = up']

['IF-MIB::ifDescr.2 = eth0', 'IF-MIB::ifOperStatus.2 = up']

Code:

from pysnmp.hlapi import *

for errorIndication,errorStatus,errorIndex,varBinds in nextCmd(SnmpEngine(), \
  CommunityData('public', mpModel=0), \
    UdpTransportTarget(('demo.snmplabs.com', 161)),
    ContextData(),
    ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
    ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
    lexicographicMode=False):

  table = []
  for varBind in varBinds:
    table.append(varBind.prettyPrint().strip())
    for i in table:
      if i not in table:
        table.append(i)
  print(table)
    for varBind in varBinds:
      table.append(varBind.prettyPrint().strip())
      for i in table:
        if i not in table:
          table.append(i)
    print(table)

Solution

  • A resolved PySNMP ObjectType consists of an ObjectIdentity and a value belonging to a valid SNMP type which is also referred to as an objectSyntax in PySNMP. You can access these elements using Python’s standard indexing.

    In your loop, varBinds is a list consisting of the fully resolved ObjectTypes corresponding to the two ObjectIdentitys you passed to nextCmd. You could unpack varBinds to reflect each objectType, then index into each to get the objectSyntax. When you call its prettyPrint method, you’ll get the human-readable string that we’re used to.

    from pysnmp.hlapi import *
    
    for _, _, _, varBinds in nextCmd(
            SnmpEngine(),
            CommunityData('public', mpModel=0),
            UdpTransportTarget(('demo.snmplabs.com', 161)),
            ContextData(),
            ObjectType(ObjectIdentity('IF-MIB', 'ifDescr')),
            ObjectType(ObjectIdentity('IF-MIB', 'ifOperStatus')),
            lexicographicMode=False):
        descr, status = varBinds  # unpack the list of resolved objectTypes
        iface_name = descr[1].prettyPrint()  # access the objectSyntax and get its human-readable form
        iface_status = status[1].prettyPrint()
        print("Interface {iface} is {status}"
              .format(iface=iface_name, status=iface_status))