SNMP polling to get network interface statistics

This is very common used case in industry. Lets see how this can be implemented in python using easysnmp python module. This can be further extended to inject collected data into databases or CSVs.


#!/usr/local/bin/python3
from easysnmp import Session
import sys

hostname = "192.168.0.6"
security_username = "testuser"
auth_password = "test_auth"
privacy_password = "test_priv"

session = Session(hostname=hostname, version=3, security_level="auth_with_privacy", security_username=security_username, auth_protocol="SHA", auth_password=auth_password, privacy_protocol="AES", privacy_password=privacy_password)

outDict = {}
inDict = {}
inErrDict = {}
outErrDict = {}
nameDict = {}
IFstats = {}
hostData = {"Host": hostname}

# ifHCOutOctets
try:
     for item in session.walk(oids=u'1.3.6.1.2.1.31.1.1.1.10'):
         outDict[item.oid_index] = {"Out": item.value}
except:
     print({"Host": hostname,"Error":"ERROR - SNMP error"})
     sys.exit(-1)

#ifHCInOctets
for item in session.walk(oids=u'1.3.6.1.2.1.31.1.1.1.6'):
    inDict[item.oid_index] = {"In": item.value}

#ifInErrors
for item in session.walk(oids=u'1.3.6.1.2.1.2.2.1.14'):
    inErrDict[item.oid_index] = {"inError": item.value}

#ifOutErrors
for item in session.walk(oids=u'1.3.6.1.2.1.2.2.1.20'):
    outErrDict[item.oid_index] = {"outError": item.value}

#ifDescr
for item in session.walk(oids=u'1.3.6.1.2.1.2.2.1.2'):
    nameDict[item.oid_index] = {"Interface": item.value}

# On the basis of index values package everything in single JSON object for the given host
for index in outDict.keys():
    IFName = nameDict[index].get('Interface')
    IFOut = outDict[index].get('Out')
    IFIn = inDict[index].get('In')
    IFinErr = inErrDict[index].get('inError')
    IFoutErr = outErrDict[index].get('outError')
    IFstats[IFName] = {"IFOut": IFOut, "IFIn": IFIn, "IFinError": IFinErr, "IFoutError": IFoutErr}

hostData['IFstats'] = IFstats
print(hostData)

Here is the sample result of above program.


{
   'Host':'10.91.126.101',
   'IFstats':{
      'HundredGigE0/0/0/1':{
         'IFOut':'21745109350690',
         'IFIn':'2097912539416',
         'IFinError':'141969',
         'IFoutError':'0'
      },
      'MgmtEth0/RSP0/CPU0/0':{
         'IFOut':'28634356',
         'IFIn':'3629770681',
         'IFinError':'0',
         'IFoutError':'0'
      },
      'MgmtEth0/RSP0/CPU0/1':{
         'IFOut':'0',
         'IFIn':'0',
         'IFinError':'0',
         'IFoutError':'0'
      },
      'HundredGigE0/0/0/5':{
         'IFOut':'0',
         'IFIn':'1108583',
         'IFinError':'138581',
         'IFoutError':'0'
      },
   }
}