Real-time Bandwidth Monitoring
Real-time Bandwidth Monitoring
David "DeMO" Martínez Oliveira

Some time ago, I have to do some network bandwidth analysis. I was using iptraf to monitor the real-time bandwidth usage and that was fine. At some point I have a need to record the values to produce a report with nice plots. At that time I couldn't find a simple tool to do that just tools to monitor traffic on server. So I wrote a small script to produce those plots.
The easiest way I found to produce those graphs was using the command-line tool ifstat. This tool dumps in the console the average bandwidth for all network interfaces (unless a list is provided) for a given period of time. It looks like the right thing to use.

Capturing Real-Time Bandwidth Usage

So, I wrote a pretty simple bash script with some awk magic to filter out the ifstat output. This is how it does look like:


(while true; do (ifstat -i $1 1 1 | awk 'NR>2{print $1, $2}'); done) 

The script accepts as parameter the interface to monitor. It dumps the data to the console so it can be easily redirected to a file for later plotting. Yes, that is it.

In addition to the interface to monitor, ifstat takes two more parameters. The first one is the delay. This is the time used to calculate the used bandwidth. In this case we are setting it to 1 sec so this is our granularity. The second parameter is a counter, it indicates to ifstat how many measurements it has to take. We are also setting this to 1. Therefore, the command above prints out the average bandwidth used for a given interface for one second.

Now, just leave the script running for the duration of your test

gnuplot magic

Now that we have the data in the text file we can easily produce a plot using gnuplot. Just launch gnuplot and type:

gnuplot> set grid ytics lc rgb "#000" lw 1 lt 0
gnuplot> set style fill solid
gnuplot> set boxwidth 0.8
gnuplot> plot "filename" using 1 with boxes

This will plot a nice bar graph showing the bandwidth usage. Changing using 1 to using 2, will show the outgoing bandwidth plot... Yep, we are retrieving both figures.

The plot below shows a sample of the output for the script. You can see some web browsing after circa 10 seconds since monitoring started, and then two big transfers (actually that is the download of the linux kernel) one around 40 secs and another one aroung 105 secs.

We can also produce images out of the plots without having to capture the screen. Just type the following command before you configure and plot your data:

gnuplot> set terminal png
gnuplot> set output "/tmp/bwplot.png"

An this is the kind of image you will get. Check the help for set terminal to adjust the output image parameters.

This is it. Very simple and straightforward