Log host up- or downtime bash script


I recently had the need to troubleshoot a server that kept losing connection. It was important to log the date and time, as well as the host I was pinging. At the same time I wanted to log it to a file, to easily check up on when the server had lost connection. Of course this is not 100% fail safe, but pinging Cloudflare at 1.1.1.1 or Google at 8.8.8.8 are pretty safe bets of telling whether you’re online.

No need to invent the wheel twice, so let’s dumb it down a bit, and base it on this script: https://gist.github.com/brunobraga/7259197

 

Log server downtime only

If you, like me, just want to log the downtime of the server, you can use the following script.

#!/bin/bash

#Put whichever host you want to ping to below - Here's Cloudflare
host=1.1.1.1

while :; do
    result=`ping -W 1 -c 1 $host | grep 'bytes from '`
    if [ $? -gt 0 ]; then
        echo -e "`date +'%Y/%m/%d %H:%M:%S'` - $host is down"
    fi
done

 

Log both server up- and downtime

If you want to log both when the server is online, and when it is offline, you can do so with the following script.

#!/bin/bash

#Put whichever host you want to ping to below - Here's Cloudflare
host=1.1.1.1

while :; do
    result=`ping -W 1 -c 1 $host | grep 'bytes from '`
    if [ $? -gt 0 ]; then
        echo -e "`date +'%Y/%m/%d %H:%M:%S'` - $host is down"
    else
        echo -e "`date +'%Y/%m/%d %H:%M:%S'` - $host is up -`echo $result | cut -d ':' -f 2$"
        sleep 1
    fi
done

 

Sure I have the script, but what do I do with it?!

In order to run the script:

  1. Copy either script above.
  2. nano or vi to create a file, eg:
    nano pingdowntime.sh
  3. Now paste the script copied above, and save.
  4. To give the file permission to run, type:
    chmod +x pingdowntime.sh
  5. Time to run it! Running it in the background while logging to a file, you can still follow added content live, with tail -f downtime.log command afterwards:
    ./pingdowntime.sh > downtime.log 2>&1 &
  6. Remember to type the jobs command if the job is owned by your session. If you SSH’d to the server, the job will also close when you close the SSH session, so also type
    disown

 

Over’n’out!

Add a Comment

Your email address will not be published.