# Linux get single bandwidth usage sample

What I want to do is to write a script that gathers some information (like cpu temperature and bandwidth usage) and logs it into a file.

I can't figure out how to get a single sample of the current used bandwidth: I've found that there's plenty of tools to get this information from command line, but the majority of them are curses based, so I can't take their output to put it into a file. Among these I've found bmon, that has a nice ascii output. The problem is that this output is updated constantly, while what I want is a single "sample" per program call.

Is there a way to get this done with bmon or someone knows another program to accomplish this task?

-

Lucky for you sysstat already exists and already does what you're trying to make.

1 . Install your distro's sysstat package then add the following to /etc/crontab:

*/5 * * * * root /usr/lib/sysstat/sa1 &
5 19 * * * root /usr/lib/sysstat/sa2 -A &


2 . Wait 10 minutes. Use this time to read the sar man page.

3 . Enjoy using sar.

-
intresting program! –  Matteo Ceccarello Aug 28 '11 at 15:13

ifconfig will tell you how much traffic a single interface has handled, e.g.

tony@eightbit:~\$ ifconfig eth0
UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
RX packets:24776 errors:0 dropped:0 overruns:0 frame:0
TX packets:22892 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:19629330 (19.6 MB)  TX bytes:3968336 (3.9 MB)


Also, have a look at netstat -s.

-
thank you. Even if I's not what I was really looking for, because this tells me how many bytes I've downloades since the interface eth0 was turned on, this gave me an idea that I'll post as an answer. So thank you –  Matteo Ceccarello Aug 27 '11 at 19:25
Well, all you do is stick it into rrdtool as a counter, or track it yourself on subsequent runs of your script. I was just pointing out where you can get the raw data. –  EightBitTony Aug 27 '11 at 21:15
that's what I've done :) –  Matteo Ceccarello Aug 27 '11 at 21:33

Out of complete desperation for the lack of such simple tool, some time ago i wrote bwm, a simple bandwidth monitor.

I use it like a daemon in the background that constantly writes to a file the current bandwidth used in a direction (upload/download) on a particular interface.

./bwm --interface wlan0 --upload > /tmp/bandwidth-upload


Whenever I need the current upload bandwidth usage, I just cat the file:

cat /tmp/bandwidth-upload


This works particularly well for monitoring scripts or status bar scripts (for dwm, wmii etc.)

-
thanks.This solution is similar to bmon -o ascii that prints to standard output, and so it can be redirected to a file like you said. Not exactly what I was looking for, but still useful :) thank you –  Matteo Ceccarello Aug 27 '11 at 19:21