Created
April 12, 2018 15:02
-
-
Save pgorczak/8783888429f886fe26a1c03c1bfca3e0 to your computer and use it in GitHub Desktop.
Example for plotting packets/second with scapy and matplotlib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import threading | |
from scapy.all import * | |
import matplotlib as mpl | |
import matplotlib.pyplot as plt | |
import matplotlib.style | |
from matplotlib import animation | |
import numpy as np | |
mpl.style.use('ggplot') # fivethirtyeight | |
WINDOW = 120 | |
FPS = 4 | |
counters = {1: 0, 2: 0} | |
x = (np.arange(-WINDOW, 0, dtype=np.float) + 1)/FPS | |
y = {i: [] for i in counters} | |
def callback(pkt): | |
if IP not in pkt: | |
return | |
subnet = int(pkt[IP].src.split('.')[2]) | |
if subnet in counters: | |
counters[subnet] += 1 | |
def update_plot(i, line1): | |
global y | |
for i in counters: | |
y[i].append(counters[i] * FPS) | |
counters[i] = 0 | |
y[i] = y[i][-WINDOW:] | |
lines[i].set_data([x[-len(y[i]):], y[i]]) | |
return lines.values() | |
if __name__ == '__main__': | |
mpl.rcParams['toolbar'] = 'None' | |
fig = plt.figure(figsize=(10, 4)) | |
lines = {i: plt.plot([],[], lw=2, label='link {}'.format(i))[0] | |
for i in counters} | |
plt.legend(loc='upper left') | |
plt.ylabel('packets/s') | |
plt.xlabel('time [s]') | |
plt.xlim(x[0], x[-1]) | |
plt.ylim(0, 750) | |
plt.tight_layout() | |
ani = animation.FuncAnimation( | |
fig, update_plot, fargs=(lines,), | |
frames=None, interval=int(1000.0/FPS), blit=False) | |
th = threading.Thread( | |
target=sniff, | |
kwargs=dict(prn=callback, filter='tcp and src net 10.45', store=0)) | |
th.daemon = True | |
th.start() | |
plt.show(block=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment