1

I need check port on the remote server in bash script before script will continue. I search here and on the internet, but I can´t find answer which works for me.

I´m using RHEL 7.2 virtual machine so I don´t have -z parameter in nc command or /dev/tcp/ thing. Also nc remote.host.com 1284 < /dev/null don´t work, because every time I get exit code 1.

Basically I need something like that:

/bin/someting host port

if [ $? -eq 0 ]; then
 echo "Great, remote port is ready."
else
 exit 1
fi
Rohlik
  • 1,286
  • 19
  • 28
  • For what it's worth, `nc host.com 1234 < /dev/null` works fine for me. It returns `0` or `1`, depending on connectivity status. Do you have `nmap`? How about `nmap --open -p | grep -q " open "`? – eddiem Nov 17 '16 at 18:38
  • With RHEL7 you can use /dev/tcp. It is not visible with `ls` command. – Cyrus Nov 17 '16 at 19:00
  • @Cyrus: Don´t work for me: `$ /dev/tcp/google.com/80 -bash: /dev/tcp/google.com/80: No such file or directory` @eddiem: `nc remote_server 1313 < /dev/null ; echo $? Ncat: Connection reset by peer. 1` `nc remote_server 1477 < /dev/null ; echo $? Ncat: Connection timed out. 1` – Rohlik Nov 17 '16 at 19:07
  • It is not visible at all. Check this: `exec 3<>/dev/tcp/www.google.com/80; echo -e "GET / HTTP/1.0\r\n" >&3; cat <&3` – Cyrus Nov 17 '16 at 19:09
  • @Rohlik you need to prefix the command with the `: ` shell builtin. See my answer below – Zlemini Nov 17 '16 at 20:33

2 Answers2

3

How about nmap?

SERVER=google.com
PORT=443
state=`nmap -p $PORT $SERVER | grep "$PORT" | grep open`
if [ -z "$state" ]; then
  echo "Connection to $SERVER on port $PORT has failed"
else
  echo "Connection to $SERVER on port $PORT was successful"
  exit 1
fi

Please note You have to install nmap.

yum install nmap #Centos/RHEL
apt-get install nmap #Debian/Ubuntu

Our you can compile and install from source.

Farhad Farahi
  • 35,528
  • 7
  • 73
  • 70
1

You can do this with Bash itself, using it's built-in /dev/tcp device file. The following will throw a connection refused message if a port is closed.

: </dev/tcp/remote.host.com/1284

Can be scripted like this:

(: </dev/tcp/remote.host.com/1284) &>/dev/null && echo "OPEN" || echo "CLOSED"

Details of /dev/tcp in bash reference manual: https://www.gnu.org/software/bash/manual/html_node/Redirections.html

Zlemini
  • 4,827
  • 2
  • 21
  • 23