Bash Script If Ping Fails Then Automatically Reboot Server

In this article I will show simile bash script if ping fails then reboot Linux server. You can easily modify this script for example if ping fails then send notification to email, or if ping successful then do something.

Create a File

SSH login into your Linux server as root, and create new text file inetmonit.sh using touch command.

# touch inetmonit.sh

Make a File Executable

Now we need make a new created inetmonit.sh bash script file executable.

Just run:

# chmod +x inetmonit.sh

Script If Ping Fails Then …

This script will ping target host 3 times, every 10 min. If responses count equal 0 will write date and time in inetmonit.log log file, then execute system reboot command: shutdown -r 0.

Open inetmonit.sh file with text editor and paste script text:

#!/bin/bash

# Set target host IP or hostname
TARGET_HOST='google.com'

count=$(ping -c 3 $TARGET_HOST | grep from* | wc -l)

if [ $count -eq 0 ]; then
    echo "$(date)" "Target host" $TARGET_HOST "unreachable, Rebooting!" >>/var/log/inetmonit.log
    /sbin/shutdown -r 0

else
    echo "$(date) ===-> OK! " >>/var/log/inetmonit.log
fi

Edit TARGET_HOST if you need.

Save and close file.

Cron Job Setup

Now we need setup cron job for executing our monitoring script every 10 min and ping. To schedule jobs edit crontab file with command:

# crontab -e

Paste this text:

*/10 * * * * /path_to/inetmonit.sh

Then edit path to your inetmonit.sh script location.

If you want to change the checks interval, change 10 min to your value. For check every 5 min:

*/5 * * * *

Save and close text editor.

That’s it! Now this script will check your internet connection every 10 min. and automatically reboot host if connection lost.

inetmonit in GitHub.

Discuss article in ArsTech Forum

   

If you like what you are reading, please:

Buy me a coffeeBuy me a coffee

arstech

Start the discussion at forum.arstech.net