How to test if a remote port is open in UNIX (Linux, AIX, HP-UX, Solaris)

Hi guys,

You may have asked yourself how can you test if a remote port is open and I do not have a third party tool like nmap. The answer is quite simple and it is multi-platform. Let’s take this example. You have 4 IPs and you want to test if port 80 is open. In AIX for example you don’t have nmap by default, what do you do in this case? Here is the solution:

#!/bin/usr/ksh
 exec 2>&-
 PORT=80
 function checkPort
 {
 echo "^]" |telnet $i $PORT > /dev/null 2>&1 &
 }

for i in 172.18.100.100 172.18.100.101 172.18.100.102 172.18.100.103 10.95.205.232
 do
 checkPort
 if [ `sleep 2;sudo ps -efa |grep "telnet $i" |wc -l` -gt 1 ]
 then
 echo "Port $PORT is closed on $i"
 kill -9 `ps -efa |grep "telnet $i" |grep -v grep |awk '{ print $2 }'`
 else
 echo "Port $PORT is open on $i"
 fi
 done

Here is some output from my server:

[root@BumbleBee ~]# sh c.sh
Port 80 is open on 172.18.100.100
Port 80 is closed on 172.18.100.101
Port 80 is closed on 172.18.100.102
Port 80 is closed on 172.18.100.103
Port 80 is open on 10.95.205.232
[root@BumbleBee ~]#