Avi Freedman's Tech and Biz Topics

on internet plumbing, gadgets, nerd herding, and other related topics

Script for Real-Time Bandwidth Monitoring

Sigh. I know there are tools that easily show bytes/sec but I’m a lazy dumbass and don’t want to multiply by 8 to get bits. So I wrote this hack:

quad3# more /usr/local/bin/bwmon 
#!/usr/bin/perl

while (1)
{
  open(IN, "ifconfig eth0|");
  while (<IN>)
  {
    if (/RX bytes:(\d+).*TX bytes:(\d+)/)
    {
      $rx = $1 - $lastin;
      $tx = $2 - $lastout;

      $tm = time;
      printf "$tm RX: %4d mbits/sec  ", $rx*8/1000000;
      printf "TX: %4d mbits/sec\n", $tx*8/1000000;

      $lastin = $1;  $lastout = $2;
    }
  }

  sleep(1);
}

I generally keep that around just to see bandwidth. I have more complex versions that sniff out which interfaces are in use and show multiple interfaces in parallel as well. (Left as an exercise for the reader since mine are nastyuglyhacks)

One weirdness – some Linux kernel versions only update every other second so I again have to do math but /=2 is easier than *=8 so…

(Edit Sep 9 2010) -

Just saw ifstat. Looks like the tool I want is now here (though I really only care about megabits as a minimum unit) -

root@s09-10:~# ifstat -z -b
       eth8                eth7                eth9       
 KB/s in  KB/s out   KB/s in  KB/s out   KB/s in  KB/s out
    0.29      0.00  13372.15  22247.85      0.29      0.00
    0.41      0.00  11567.76  18173.64      0.41      0.00
    0.53      0.00  13314.24  16444.63      0.53      0.00
    0.35      0.00  12519.52  22200.34      0.35      0.00
    0.70      0.00  13903.69  16952.59      0.70      0.00
    2.05      0.00   9497.29  20794.83      2.05      0.00
    0.47      0.00  12050.75  16702.49      0.47      0.00
    0.64      0.00  10829.07  20628.17      0.64      0.00
^C

And… No shocker. On the kernels that are only reporting every other second, ifstat does as well. More interestingly, it seems to be exactly once every 2 seconds on all of those machines. It isn’t happening on newer kernels so I haven’t bothered to investigate more deeply…