Shell Script To Report Network Usage, bytes/sec
In distributed apps it is often important to know the current network throughput speed on a particular server to help balance file serving requests etc.
Installing MRTG or other software is not always desirable or possible. I created the shell script below to output the eth0 outbound transfer rate in bytes/second. To calculate megabits per second simply divide the output by 131072.
You could post the data to a remote URL (e.g. a master health server) or write it to an xml file for reading by remote server or app, etc.
The speed returned is the average throughput over a 55 second period, you can adjust this as needed. Tested on CentOS 5.
#!/bin/bash
txfirst=`ifconfig eth0 | grep “TX bytes:” | cut -d “:” -f3 | cut -d ” ” -f1`
datefirst=`date +%s`
loop=1
while [ loop=1 ]
do
txnew=`ifconfig eth0 | grep “TX bytes:” | cut -d “:” -f3 | cut -d ” ” -f1`
datenew=`date +%s`if [ $txnew -gt $txfirst ]
then
transferred=$((txnew-txfirst))
timelapsed=$((datenew-datefirst))
if [ $x > 0 ]
then
bytessec=$(($transferred/$timelapsed))
echo “$bytessec bytes/sec”
fi
txfirst=$((txnew))
datefirst=$((datenew))
else
txfirst=$((txnew))
datefirst=$((datenew))fi
sleep 55
x=$(($x+1))
done
