Sep 12 2012

python command line bandwidth monitor

Category: pythonerm @ 8:20 pm

In a previous post I wrote a bandwidth monitory in php. It was running about 300k (on my laptop it was < 100k), and figured it was time to test out my python foo. This version also displays a line similar to this at the top of your terminal window: eth0:RX:600b TX:944b Av:77b eth2:RX:0b TX:0b Av:0b

Usage is simple:
$ ./bw.monitor.py & htop

#!/usr/bin/env python
import time, re, copy, sys

ESC = chr(27)
#
def sizeof_fmt(num):
    num = int(num)
    # sizeof_fmt stolen from:
    # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
    for x in ['b','k','m','g','t']:
        if num < 1024.0:
            return "%3.1f%s" % (num, x)
        num /= 1024.0

prog = re.compile("([a-z0-9]+)\:\s+([0-9]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)\s+([\d]+)",re.M + re.S)

numeric = re.compile("^[0-9]+$")

key_map = {
    1: 'RX',
    9: 'TX'
}

last_data = {}
readout = {}
associated = {}
history = {}

while True:
    fp = open('/proc/net/dev','r')
    data = fp.read()
    fp.close()
    matches = prog.findall(data)
    
    for m in matches:
        # print m
        interface = m[0]
        associated[interface] = {}
        for k,v in key_map.iteritems():
            associated[interface][v] = int(m[k])

    for iface, dta in associated.iteritems():
        if not history.has_key(iface):
            history[iface] = []
        if last_data.has_key(iface):
            for k, v in dta.iteritems():
                diff = v - last_data[iface][k]
                if not readout.has_key(iface):
                    readout[iface] = {}
                readout[iface][k] = diff
                history[iface].append(diff)
            history[iface] = history[iface][-20:]
            total = sum(history[iface])
            readout[iface]["Av"] = total / (len(history[iface]) / 2);

    sys.stdout.write(ESC+"[s")
    sys.stdout.write(ESC+"[0;0H")
    sys.stdout.write(ESC+"[K")
   
    for iface in sorted(readout.iterkeys()):
        if iface in("lo",'wlan0'):
            continue
        dta = readout[iface]
        sys.stdout.write(iface+" ")
        for k, v in dta.iteritems():
            sys.stdout.write("%-11s" % ("%s:%s" % (k,sizeof_fmt(v)),))
        sys.stdout.write(" ")

    sys.stdout.write(ESC+"[u")
    sys.stdout.flush()
        
    last_data = copy.deepcopy(associated)
    
    time.sleep(1)


Leave a Reply

You must be logged in to post a comment. Login now.