4

I am using nc command in my Linux box like below to check if a port is listening;

This displays success message:

nc -z 192.168.0.2 9000

This displays 0:

echo $?

I have combined it in a shell script .sh file like below;

#!/bin/sh
nc -z 192.168.0.2 9000
echo $?

This displays 1 instead of expected 0. Again, if I modify my script like below, it works;

#!/bin/sh
echo nc -z 192.168.0.2 9000
echo $?

But here the problem is, it displays success message on one like, then displays 0 in next line. I don't want success message, and I am expecting 0. What is wrong here and how can I fix this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Alfred
  • 21,058
  • 61
  • 167
  • 249
  • http://stackoverflow.com/questions/4922943/test-from-shell-script-if-remote-tcp-port-is-open – Dan Feb 21 '17 at 20:47

2 Answers2

3

This small script should do the trick:

#!/bin/bash
SERVER=$1
PORT=$2
nc -z -v -G5 $SERVER $PORT &> /dev/null
result1=$?

#Do whatever you want

if [  "$result1" != 0 ]; then
  echo  port $PORT is closed on $SERVER
else
  echo port $PORT is open on $SERVER
fi

Usage:

./myscript.sh servername portnumber

For example:

./myscript www.google.com 80
www.google.com 80
port 80 is open on www.google.com

Depending on the version of nc you're using, you may need to adjust the -G to -w, so experiment and find which works best for you.

Dan
  • 931
  • 2
  • 18
  • 31
0

Your script works as expected for me. (Using nc 0.7.1 and sh 4.4.12)

Both, on command line as well as a script using #!/bin/sh

Just your last version - echo nc -z 192.168.0.2 9000 - does not execute nc at all but just echoes it out. Try replacing nc with anything, e.g. ncc-1701 and you'll see what i mean.

RuDevel
  • 694
  • 3
  • 14