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.
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
What to do with the script?
In order to run the script:
- Copy either script above.
- nano or vi to create a file, eg:
nano pingdowntime.sh
- Now paste the script coped above, and save.
- To give the file permission to run, type:
chmod +x pingdowntime.sh
- 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 &
- 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 your SSH session, hence, to disown the job and allow it to carry on, type:
disown
Comments (0)
No comments yet. Be the first to comment!
Leave a Comment