1

I have a bash program that checks that a daemon in a given port is working:

nc -z localhost $port > /dev/null
if [ "$?" != "0" ]
then
  echo The server on port $port is not working
  exit
fi

This program works perfectly in CentOS 6. However, it seems that CentOS 7 has changed the underlying implementation for nc command (CentOS 6 seems to use Netcat and CentOS 7 uses another thing called Ncat) and now the -z switch doesn't work:

$ nc -z localhost 8080
nc: invalid option -- 'z'

Looking to the man nc page in CentOS 7 I don't see any clear alternative to -z. Any suggestion on how I should fix my bash program to make it work in CentOS 7?

fgalan
  • 11,732
  • 9
  • 46
  • 89
  • Regarding the close flag that has been raised, let me clarify that the question *is* about programming (bash programming in particular). – fgalan Apr 16 '16 at 13:17
  • 1
    If you don't care about the tool you're using you can probably use the answers at http://stackoverflow.com/questions/4922943/test-from-shell-script-if-remote-tcp-port-is-open – Eric Renouf Apr 16 '16 at 13:48
  • `if [ "$?" != "0" ]` is an antipattern; you want simply `if nc -z localhost $port > /dev/null` – tripleee Apr 18 '16 at 05:58
  • Yes, that could be an improvement. However, the bottom line (and the topic on which my question is focused) is that `-z` doesn't work with the `nc` command (actually a symlink for Ncat) in CentOS 7. – fgalan Apr 18 '16 at 07:44
  • My [answer](http://stackoverflow.com/a/14701003/832230) covers it and has examples too. – Asclepius Oct 18 '16 at 19:57

2 Answers2

2

And a trimmed down version for what you really want:

#!/bin/bash
# Start command: nohup ./check_server.sh 2>&1 &

check_server(){ # Start shell function

checkHTTPcode=$(curl -sLf -m 2 -w "%{http_code}\n" "http://10.10.10.10:8080/" -o /dev/null)

if [ $checkHTTPcode -ne 200 ]
    then
        # Check failed. Do something here and take any corrective measure here if nedded like restarting server
        # /sbin/service httpd restart >> /var/log/check_server.log
        echo "$(date) Check Failed " >> /var/log/check_server.log

    else
        # Everything's OK. Lets move on.
        echo "$(date) Check OK " >> /var/log/check_server.log
fi
}

while true # infinite check
do
# Call function every 30 seconds
check_server
sleep 30

done
mjoao
  • 197
  • 1
  • 5
1

according this post, I used:

nc -w1 localhost $port < /dev/null

( this work on debian too, but it's slower than nc -z )

kyodev
  • 573
  • 2
  • 14