Monitoring network traffic in Linux: Difference between revisions
From Leo's Notes
This page was last edited on 17 November 2020, at 03:42.
m Leo moved page Network Monitoring to Network Traffic Monitoring without leaving a redirect |
mNo edit summary |
||
| Line 1: | Line 1: | ||
On a bare system without nice tools like [[vnstat]], use the following script to monitor your network usage on a Linux box. | |||
{{Highlight | {{Highlight | ||
Revision as of 03:42, 17 November 2020
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 $3}'`
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