How to check if a server is running
bash, linux, ping, shell, unix
Solution
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 0
else
# Service is offline or not working correctly
echo "Service is offline or not working correctly"
exit 1
fi
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/null
if [[ $? == 0 ]]
then
# Port is reached
echo "Service is online!"
exit 0
else
# Port is unreachable
echo "Service is offline!"
exit 1
fi
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
Problem
I want to use ping to check to see if a server is up. How would I do the following: ``` ping $URL if [$? -eq 0]; then echo "server live" else echo "server down" fi ``` How would I accomplish the above? Also, how would I make it such that it returns 0 upon the first ping response, or returns an error if the first ten pings fail? Or, would there be a better way to accomplish what I am trying to do above?