Test if remote TCP port is open from a shell script

portshellsolaristcptelnet

I'm looking for a quick and simple method for properly testing if a given TCP port is open on a remote server, from inside a Shell script.

I've managed to do it with the telnet command, and it works fine when the port is opened, but it doesn't seem to timeout when it's not and just hangs there…

Here's a sample:

l_TELNET=`echo "quit" | telnet $SERVER $PORT | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
  echo "Connection to $SERVER on port $PORT failed"
  exit 1
else
  echo "Connection to $SERVER on port $PORT succeeded"
  exit 0
fi

I either need a better way, or a way to force telnet to timeout if it doesn't connect in under 8 seconds for example, and return something I can catch in Shell (return code, or string in stdout).

I know of the Perl method, which uses the IO::Socket::INET module and wrote a successful script that tests a port, but would rather like to avoid using Perl if possible.

Note: This is what my server is running (where I need to run this from)

SunOS 5.10 Generic_139556-08 i86pc i386 i86pc

Best Answer

As pointed by B. Rhodes, nc (netcat) will do the job. A more compact way to use it:

nc -z <host> <port>

That way nc will only check if the port is open, exiting with 0 on success, 1 on failure.

For a quick interactive check (with a 5 seconds timeout):

nc -z -v -w5 <host> <port>