Skip to content

Instantly share code, notes, and snippets.

@rschmied
Last active November 7, 2017 10:02
Show Gist options
  • Save rschmied/757b5cfd0412af2838cd484692b5a574 to your computer and use it in GitHub Desktop.
Save rschmied/757b5cfd0412af2838cd484692b5a574 to your computer and use it in GitHub Desktop.
interface speed script
#!/bin/bash
[ -z "$1" ] && { echo "usage: $0 interface"; exit; }
[ -d /sys/class/net/$1 ] || { echo "interface $1 doesn't exist."; exit; }
PREFIX=(" " "K" "M" "G" "T")
# update interval in seconds
INTERVAL=5
# use 30 samples for the crude rolling avg
N=30
get_multiplier() {
value=$1
index=0
while [ $value -gt 8192 ]; do
remainder=$(( value % 1024 ))
value=$(( value / 1024 ))
((index++))
done
if [ $remainder > 512 ]; then
((value++))
fi
echo $value ${PREFIX[$index]}
}
rolling_avg() {
avg=$1
new_sample=$2
# first sample?
if [ $avg -gt 0 ]; then
avg=$((avg - avg / N))
avg=$((avg + $new_sample / N))
else
avg=$new_sample
fi
echo $avg
}
IF=$1
LEN=${#IF}
LOOPS=0
ARBPS=-1
ARPPS=-1
ATBPS=-1
ATPPS=-1
while true; do
# packets
RP1=$(cat /sys/class/net/$IF/statistics/rx_packets)
TP1=$(cat /sys/class/net/$IF/statistics/tx_packets)
# bytes
RB1=$(cat /sys/class/net/$IF/statistics/rx_bytes)
TB1=$(cat /sys/class/net/$IF/statistics/tx_bytes)
sleep $INTERVAL
# packets
RP2=$(cat /sys/class/net/$IF/statistics/rx_packets)
TP2=$(cat /sys/class/net/$IF/statistics/tx_packets)
# bytes
RB2=$(cat /sys/class/net/$IF/statistics/rx_bytes)
TB2=$(cat /sys/class/net/$IF/statistics/tx_bytes)
TXPPS=$(( (TP2 - TP1) / INTERVAL))
RXPPS=$(( (RP2 - RP1) / INTERVAL))
TXBPS=$(( (TB2 - TB1) / INTERVAL))
RXBPS=$(( (RB2 - RB1) / INTERVAL))
read TBPS UTBPS <<<$(get_multiplier $TXBPS)
read RBPS URBPS <<<$(get_multiplier $RXBPS)
ATBPS=$(rolling_avg $ATBPS $TXBPS)
ATPPS=$(rolling_avg $ATPPS $TXPPS)
ARBPS=$(rolling_avg $ARBPS $RXBPS)
ARPPS=$(rolling_avg $ARPPS $RXPPS)
read TABPS UATBPS <<<$(get_multiplier $ATBPS)
read RABPS UARBPS <<<$(get_multiplier $ARBPS)
printf "%s: TX %4d %1sBps %6d pps \t Avg: %4d %1sB/s %6d pps\n" \
$IF $TBPS "$UTBPS" $TXPPS $TABPS "$UATBPS" $ATPPS
printf "%*s RX %4d %1sBps %6d pps \t Avg: %4d %1sB/s %6d pps\n" \
$LEN " " $RBPS "$URBPS" $RXPPS $RABPS "$UARBPS" $ARPPS
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment