Testing remote TCP port using telnet by running a one-line command

You ought to be able to pipe the exit command into STDIN in telnet. Try:

echo 'exit' | telnet {site} {port}

and see if that works. (it seems to work on my web server, but YMMV).


The simplest and easiest method is given below.

 sleep <n> | telnet <server> <port>
  • n - The wait time in seconds before auto exit. It could be fractional like 0.5. Note that some required output may not be returned in the specified wait time. So we may need to increase accordingly.

  • server - The target server IP or hostname.

  • port - Target service port number.

You can also redirect the output to file like this:

sleep 1 | telnet <server> <port> > output.log

In my case this works. (CentOS 7):

while read host port; do
r=$(bash -c 'exec 3<> /dev/tcp/'$host'/'$port';echo $?' 2>/dev/null)
if [ "$r" = "0" ]; then
     echo "$host $port is open"
else
     echo "$host $port is closed"
     exit 1 # To force fail result in ShellScript
fi
done

Tags:

Bash

Telnet