Monitoring network traffic in Linux

From Leo's Notes
Last edited on 30 December 2021, at 01:41.

On a bare system without nice tools like vnstat, use the following script to monitor your network usage on a Linux box.

#!/bin/bash

Delay=1
Device=$1

if [ -z "$Device" ] ||  ! grep -qw $Device /proc/net/dev ; then
        echo "Usage: $0 interface"
        echo "Error: Invalid device '$Device'."
        grep ":" /proc/net/dev | awk -F: '{print $1}' | sed s@\ @@g
        exit 1
fi

function format (){
        if [ $1 -gt 1048576 ] ; then
                echo $(( $1 / 1024 / 1024 )) "MB/s"
        elif [ $1 -gt 1024 ] ; then
                echo $(( $1 / 1024 )) "KB/s"
        else
                echo $1 "B/s"
        fi
}

Rx=-1
Tx=-1

while true; do
        LINE=`grep $1 /proc/net/dev`;
        Rxn=`echo $LINE | awk '{print $2}'`
        Txn=`echo $LINE | awk '{print $10}'`

        if [ $Rx -ge 0 ] ; then
                Rx_b=$((($Rxn - $Rx) / $Delay))
                Tx_b=$((($Txn - $Tx) / $Delay))
                Sum_b=$(($Rx_b+$Tx_b))

                printf "In: %18s | Out: %18s | Total: %18s\n" "`format $Rx_b`" "`format $Tx_b`" "`format $Sum_b`"

        fi

        Rx=$Rxn
        Tx=$Txn

        sleep $Delay
done