Last active
July 17, 2021 05:57
-
-
Save MaxMatti/73b7a06b64b683924d1d8125fa0b5182 to your computer and use it in GitHub Desktop.
This script monitors the incoming and outgoing bandwidth of a server on localhost connected to a client on localhost.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
SERVERPORT=$1 | |
PROCESSNAME=$(sudo lsof -n -i :"$SERVERPORT" | grep LISTEN | awk '{print $1}') | |
PID=$(sudo lsof -n -i :"$SERVERPORT" | grep LISTEN | awk '{print $2}') | |
CONNECTEDPORTS=$(sudo netstat -ant | awk -v port="$SERVERPORT" '{if ($6 == "ESTABLISHED" && $4 == "127.0.0.1:" port) {print $5} }' | cut -d":" -f 2) | |
sudo iptables -A INPUT -p tcp --dport "$SERVERPORT" | |
echo "$CONNECTEDPORTS" | xargs -L 1 sudo iptables -A INPUT -p tcp --dport | |
watch -n 1 sudo iptables -n -L -v -Z | |
sudo iptables -D INPUT -p tcp --dport "$SERVERPORT" | |
echo "$CONNECTEDPORTS" | xargs -L 1 sudo iptables -D INPUT -p tcp --dport |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: this measures the bandwidth for each client separately and only for clients that run on localhost. If you just want to measure your servers bandwidth use this script instead.
Usage:
chmod +x monitor-bandwidth.sh
./monitor-bandwidth.sh 25565
Sample output:
How to read the output:
The relevant part is the section labeled
Chain INPUT
, more specifically the first, second and last column of that section.The first column displays the amount of packets and the second column the amount of bytes sent on the port displayed in the last column. So in the sample output the server is running on port
25565
with the client being connected to it via port54884
. The download bandwidth is about812 KiB/s
and the upload bandwidth is92796 B/s
. If more clients were connected, they would each have one line in that section.Explanation:
The script runs the command
sudo iptables -n -L -v -Z
every second. This means that it letsiptables
count the amount of packets and bytes sent via two ports (the server port and the client port) and then resets the counters, so that the output is effectively giving information about packets per second and bytes per second.