Bash script to check for open port
Below is a simple bash script to check for a specific open port from an ip address. In this case I am checking for port 22. If after 30 seconds of trying port 22, (when port 22 is closed) the script fails and echos out “port is closed”. If port 22 is open then it echos out “port is open” and then we can perform some action after knowing this such as connect via ssh as we know the port is open (assuming ssh keys are setup).
#check for open port
if nc -zv -w30 $HOSTIP 22 <<< ” &> /dev/null
echo 'Port is open'
#ssh in and restart apache
ssh root@$HOSTIP "/etc/init.d/httpd restart"
echo 'Port is closed'