How to check if a server is running How to check if a server is running shell shell

How to check if a server is running


I'ld recommend not to use only ping. It can check if a server is online in general but you can not check a specific service on that server.

Better use these alternatives:

curl

man curl

You can use curl and check the http_response for a webservice like this

check=$(curl -s -w "%{http_code}\n" -L "${HOST}${PORT}/" -o /dev/null)if [[ $check == 200 || $check == 403 ]]then    # Service is online    echo "Service is online"    exit 0else    # Service is offline or not working correctly    echo "Service is offline or not working correctly"    exit 1fi

where

  • HOST = [ip or dns-name of your host]

  • (optional )PORT = [optional a port; don't forget to start with :]

  • 200 is the normal success http_response

  • 403 is a redirect e.g. maybe to a login page so also accetable and most probably means the service runs correctly

  • -s Silent or quiet mode.

  • -L Defines the Location

  • -w In which format you want to display the response
    -> %{http_code}\n we only want the http_code

  • -o the output file
    -> /dev/null redirect any output to /dev/null so it isn't written to stdout or the check variable. Usually you would get the complete html source code before the http_response so you have to silence this, too.


nc

man nc

While curl to me seems the best option for Webservices since it is really checking if the service's webpage works correctly,

nc can be used to rapidly check only if a specific port on the target is reachable (and assume this also applies to the service).

Advantage here is the settable timeout of e.g. 1 second while curl might take a bit longer to fail, and of course you can check also services which are not a webpage like port 22 for SSH.

nc -4 -d -z -w 1 &{HOST} ${PORT} &> /dev/nullif [[ $? == 0 ]]then    # Port is reached    echo "Service is online!"    exit 0else    # Port is unreachable    echo "Service is offline!"    exit 1fi

where

  • HOST = [ip or dns-name of your host]

  • PORT = [NOT optional the port]

  • -4 force IPv4 (or -6 for IPv6)

  • -d Do not attempt to read from stdin

  • -z Only listen, don't send data

  • -w timeout
    If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed. (In this case nc will exit 1 -> failure.)

  • (optional) -n If you only use an IP: Do not do any DNS or service lookups on any specified addresses, hostnames or ports.

  • &> /dev/null Don't print out any output of the command


You can use something like this -

serverResponse=`wget --server-response --max-redirect=0 ${URL} 2>&1`if [[ $serverResponse == *"Connection refused"* ]]then    echo "Unable to reach given URL"    exit 1fi


Use the -c option with ping, it'll ping the URL only given number of times or until timeout

if ping -c 10 $URL; then    echo "server live"else    echo "server down"fi