Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
shell: quick linux scripts for showing network bandwidth or packets-per-second
#!/bin/bash
if [ -z "$1" ]; then
echo
echo usage: $0 network-interface
echo
echo e.g. $0 eth0
echo
echo shows packets-per-second
exit
fi
IF=$1
while true
do
R1=`cat /sys/class/net/$1/statistics/rx_packets`
T1=`cat /sys/class/net/$1/statistics/tx_packets`
sleep 1
R2=`cat /sys/class/net/$1/statistics/rx_packets`
T2=`cat /sys/class/net/$1/statistics/tx_packets`
TXPPS=`expr $T2 - $T1`
RXPPS=`expr $R2 - $R1`
echo "tx $1: $TXPPS pkts/s rx $1: $RXPPS pkts/s"
done
#!/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
@joemiller
Copy link
Author

joemiller commented Oct 1, 2019

@nicdnepr You could try the nethogs utility for that

@mdobrzyn
Copy link

mdobrzyn commented Jan 7, 2020

@joemiller in netspeed.sh you should use kB/s instead kb/s

@joemiller
Copy link
Author

joemiller commented Jan 7, 2020

@mdobrzyn Yep! thanks for pointing that out. Updated.

@joemiller
Copy link
Author

joemiller commented Jan 7, 2020

@nicnepr I came across this new (to me, at least) tool written in Rust that will show network usage by application. It's also cross-platform. Might want to check it out.

https://github.com/imsnif/bandwhich

@venomone
Copy link

venomone commented Feb 24, 2022

My version of the script:

#!/bin/bash

# shellcheck disable=SC2034
i=$1
c=$2
e=1

if [ -z "$1" ] || [ -z "$2" ]; then
  echo
  echo usage: "$0" network-interface checkrepeats
  echo e.g. "$0" eth0 10
  echo
  exit
fi

while [ "$e" -le "$c"  ]
do
  # Network Interface Load:
  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)
  # CPU Load:
  CPU_LOAD=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}') # percentage of CPU in use
  MEM_LOAD=$(free | grep Mem | awk '{print $3/$2 * 100.0}') # percentage of Memory in use
  echo "$1 tx: $TKBPS kB/s rx: $RKBPS kB/s, $(nproc) CPUs @ $CPU_LOAD load, $MEM_LOAD% Memory in use"
  (( e++ ))
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment