Yanick Girouard Yanick Girouard - 1 year ago 152
Bash Question

Test from shell script if remote TCP port is open

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
echo "Connection to $SERVER on port $PORT succeeded"
exit 0

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

Answer Source

The answer lied with Expect. We wrote a simple script that sends a telnet on the port we needed, with a timeout of 8 seconds. There's plenty of examples to pick from too.

We based ours off this post: http://www.unix.com/shell-programming-scripting/146568-expect-telnet-testing-tacacs-cisco.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download