Bash script for checking remote webserver health status

bashhealthhttp

I have a couple of devices with web-based interfaces that I need to regularly check status of.

A server is considered working (healthy) when it is returning 1xx (continue), 2xx (success) or 3xx (redirect) http status code. It is considered dead when it returns 4xx (client error) or 5xx (server error) codes or when it doesn't respond in a given time.

As for obtaining the status code – I have this covered:

curl -I http://server.domain

How to reliably detect timeout (let's say I consider 5 seconds to be too much, it's plenty of time since this is happening in a LAN with little to no traffic) and kill the curl process if the given time passes and there is no response? Or better yet – how to connect them to have a single script that returns TRUE if the server is healthy, and FALSE if the server returns errors or times out?

Best Answer

I agree with Sven that this is a problem that already has ready-made solutions.

That said, you can use the exit code returned by curl to determine whether or not a timeout occurred.

Here is a script returns FALSE if curl times out or if the server returns a 4xx or 5xx status code:

HEADERS=`curl -Is --connect-timeout ${1-5} http://server.domain/`
CURLSTATUS=$?

# Check for timeout
if [ $CURLSTATUS -eq 28 ]
    then
        echo FALSE
else
    # Check HTTP status code
    HTTPSTATUS=`echo $HEADERS | grep HTTP | cut -d' ' -f2`
    if [ $HTTPSTATUS -le 399 ]
        then
            echo TRUE
    else
        echo FALSE
    fi
fi

This script accepts a timeout argument, but defaults to 5 seconds. I tested this against a live URL with both a 5 second connection timeout and a .01 second timeout to demonstrate:

# sh check_website.sh 5
TRUE
# sh check_website.sh .01
FALSE