Razgriz
Razgriz

Reputation: 7343

Shell script to find out if a port is being listened to using netstat?

I have a server where a certain port (9999) is being listened to by a PHP socket server. What happens is that devices can connect to the socket and send messages. The code works fine right now, however, I noticed that the socket would sometimes close or die off, and I need to be able to put it back up online automatically without me having to log in and run it again.

What I'm thinking of is writing a Shell script that would check via netstat if there's a process running on port 9999, and if there's none, the script would trigger the PHP socket server to go online again. This Shell script would then be called by Cron every 1 or 2 minutes to check if the PHP socket is running.

I have bare minimum knowledge about Shell scripting, and so far, this was the only other thing I wrote in Shell:

#!/bin/sh

if pidof "my process name here" >/dev/null; then
    echo "Process already running"
else
        echo "Process NOT running!"
        sh /fasterthancron.sh
fi

I think I should be able to reuse this code to some degree but I'm not sure what to replace the if condition with.

I have the idea that I'm supposed to use netstat -tulpn to figure out what processes are running, but I'm not sure how to filter through that list to find if a specific process is running on port 9999.

Upvotes: 2

Views: 4765

Answers (2)

Kalpa Gunarathna
Kalpa Gunarathna

Reputation: 1107

You can use famous netstat -tupln with a simple if/else logic to do this.

if [ -z "$(sudo netstat -tupln | grep 9999)" ];
then
    echo notinuse;
else
    echo inuse;
fi

Upvotes: 1

James Lim
James Lim

Reputation: 13062

If you use netstat -tlpn (or its replacement ss -tpln), you can grep for 9999 and look for processes listening on it under "Local Address".

ss -tpln | awk '{ print $4 }' | grep ':9999'

Alternatively, if you can, use netcat or telnet instead e.g. nc -v localhost 9999.

if echo -n "\cD" | telnet ${host} ${port} 2>/dev/null; then
    ...
fi

Upvotes: 2

Related Questions