How to Create Bandwidth Usage Script on Linux

Using a tool called iftop we can monitor bandwidth usage via command line on Linux. But here we will create our own shell script to monitor bandwidth usage. The idea is to read rx_bytes and tx_bytes files inside /sys/class/net/[interface]/statistics/ folder.

Create netspeed script in /usr/local/bin/ and copy and paste below script.

# nano /usr/local/bin/netspeed

Script content:

#!/bin/bash
if [ -z '$1' ]; then
echo
echo usage: $0 network-interface
echo
echo e.g. $0 eth0
echo
exit
fi

IF=$1

while true
do
R1=`cat /sys/class/net/$1/statistics/rx_bytes`
T1=`cat /sys/class/net/$1/statistics/tx_bytes`
sleep 1
R2=`cat /sys/class/net/$1/statistics/rx_bytes`
T2=`cat /sys/class/net/$1/statistics/tx_bytes`
TBPS=`expr $T2 - $T1`
RBPS=`expr $R2 - $R1`
TKBPS=`expr $TBPS / 1024`
RKBPS=`expr $RBPS / 1024`
echo 'tx $1: $TKBPS kb/s rx $1: $RKBPS kb/s'
done

Exit nano by typing Ctrl-X and press Y.

Change file mode into executable.

# chmod 775 /usr/local/bin/netspeed

Run the script:

# netspeed eth0

tx eth0: 26 kb/s rx eth0: 849 kb/s
tx eth0: 37 kb/s rx eth0: 1246 kb/s
tx eth0: 33 kb/s rx eth0: 1077 kb/s
tx eth0: 37 kb/s rx eth0: 1250 kb/s
tx eth0: 33 kb/s rx eth0: 1077 kb/s
tx eth0: 31 kb/s rx eth0: 1043 kb/s

 

Source: madmadmod

Comments
  1. superman Reply
  2. superman Reply

Leave a Reply

Your email address will not be published. Required fields are marked *