Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save laszlomiklosik/9761903 to your computer and use it in GitHub Desktop.
Save laszlomiklosik/9761903 to your computer and use it in GitHub Desktop.
Linux monitor the number of connections on a given port
# below example is a shell script which logs the number of connections every 30 seconds
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Please provide the port number for which you want to monitor the connection count as the one and only argument!"
exit
fi
while true; do
crtDate=`date`
crtConnectionCount=`netstat -a -n | grep "$1" | grep ESTABLISHED | wc -l`
crtLine="$crtDate Connection count: $crtConnectionCount"
echo $crtLine >> connections_port_$1.txt
sleep 30
done
@laszlomiklosik
Copy link
Author

Also useful:
$ netstat -ntlpa
$ ss -tp
$ watch ss -tp
$ netstat -A inet -p
$ sudo lsof -i :3306 |grep ESTABLISHED
$ sudo netstat -ntlpa | grep ESTABLISHED | grep 3306

@laszlomiklosik
Copy link
Author

An even better script:

#!/bin/bash

# provides the connection counts to all ports specified as args in the console and also to file connections_{datetime_of_start}.txt
# to start in background run: ./monitor_connections.sh 18080 28080 3306 1389 27017 &>/dev/null &

if [ "$#" -lt 1 ]; then
        echo "Please provide the port numbers to monitor as args to this shell script!"
        exit
fi

resultsFileName=connections_`date "+%Y%m%d_%H%M%S"`.txt
echo "You can follow the console, but results are also added to: $resultsFileName from the current folder."
while true; do
    crtDate=`date "+%Y%m%d_%H%M%S"`
    logLine="$crtDate%2s"
    for portNumber in "$@"
        do
            allConnections=`sudo lsof -i :"$portNumber" |wc -l | tr -d '[:space:]'`
            activeConnections=`sudo lsof -i :"$portNumber" | grep ESTABLISHED | wc -l | tr -d '[:space:]'`
            logLine="$logLine $portNumber: $allConnections/$activeConnections%*s"
        done
    printf "$logLine\n"
    printf "$logLine\n" >> $resultsFileName
    sleep 5
done

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