Skip to content

Instantly share code, notes, and snippets.

@bkbilly
Last active April 23, 2020 10:00
Show Gist options
  • Select an option

  • Save bkbilly/3c264c7d063a7d34e23e15bf124d4ee5 to your computer and use it in GitHub Desktop.

Select an option

Save bkbilly/3c264c7d063a7d34e23e15bf124d4ee5 to your computer and use it in GitHub Desktop.
Scans the SNMP tree for all the interfaces and its packet sizes and for every interface plots it into a diagram.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "bkbilly"
from pysnmp.entity.rfc3413.oneliner import cmdgen
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class PlotSnmpInterfaces():
"""Scans the SNMP tree for all the interfaces
and its packet sizes and for every interface
plots it into a diagram.
I have tested it with Asus router RT-AC56U.
"""
def __init__(self, targetip,
targetport=161,
getcommunity='public',
oidint='1.3.6.1.2.1.2.2.1.2',
oiddown='1.3.6.1.2.1.2.2.1.10',
oidup='1.3.6.1.2.1.2.2.1.16',
divisor=1024):
self.getcommunity = getcommunity
self.targetip = targetip
self.targetport = targetport
self.oidint = oidint
self.oiddown = oiddown
self.oidup = oidup
self.divisor = divisor
self.interfaces = {}
self.timeOld = datetime.now()
self.dataOld = self.getData()
self.fig = plt.figure()
leninterf = len(self.dataOld)
for interf in self.dataOld:
indinterf = list(self.dataOld.keys()).index(interf) + 1
self.interfaces.setdefault(interf, {'up': [], 'down': [], 'ax': None})
self.interfaces[interf]['ax'] = self.fig.add_subplot(leninterf, 1, indinterf)
self.index = []
self.ani = animation.FuncAnimation(self.fig, self.animate, interval=5000)
plt.show()
def getData(self):
datareceived = {}
cmdGen = cmdgen.CommandGenerator()
errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
cmdgen.CommunityData(self.getcommunity),
cmdgen.UdpTransportTarget((self.targetip, self.targetport)),
self.oidint, # Interface
self.oiddown, # Download
self.oidup # Upload
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'
)
)
else:
for varBindTableRow in varBindTable:
interface = str(varBindTableRow[0][1])
download = int(varBindTableRow[1][1])
upload = int(varBindTableRow[2][1])
datareceived.setdefault(interface, {})
datareceived[interface]['download'] = download
datareceived[interface]['upload'] = upload
datareceived[interface]['OID_down'] = str(varBindTableRow[1][0])
datareceived[interface]['OID_up'] = str(varBindTableRow[2][0])
return datareceived
def animate(self, idx):
timeNew = datetime.now()
dataNew = self.getData()
timeDiff = (timeNew - self.timeOld).total_seconds()
print("\n--", str(timeNew))
self.index.append(idx)
for interf in self.dataOld:
downDiff = dataNew[interf]['download'] - self.dataOld[interf]['download']
upDiff = dataNew[interf]['upload'] - self.dataOld[interf]['upload']
downDiff = round((downDiff / self.divisor) / timeDiff, 2)
upDiff = round((upDiff / self.divisor) / timeDiff, 2)
oidUp = dataNew[interf]['OID_up']
oidDown = dataNew[interf]['OID_down']
print("{0:5} {1:8} {2:27} ↓ down".format(interf, downDiff, oidDown))
print(" {0:8} {1:27} ↑ up".format(upDiff, oidUp))
self.interfaces[interf]['down'].append(downDiff)
self.interfaces[interf]['up'].append(upDiff)
self.interfaces[interf]['ax'].set_title(interf, color='green')
self.interfaces[interf]['ax'].set_ylabel('kb/s')
self.interfaces[interf]['ax'].xaxis.set_visible(False)
self.interfaces[interf]['ax'].plot(self.index, self.interfaces[interf]['down'], 'b')
self.interfaces[interf]['ax'].plot(self.index, self.interfaces[interf]['up'], 'r--')
self.timeOld = timeNew
self.dataOld = dataNew
PlotSnmpInterfaces('192.168.2.1', 161, 'public',
'1.3.6.1.2.1.2.2.1.2',
'1.3.6.1.2.1.2.2.1.10',
'1.3.6.1.2.1.2.2.1.16',
1024)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment