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

how to review sudo user access on multiple servers with bash script … i mean need to review each user on server ..
Hi,
the word “icmp” appears both in case of success and failure, therefore the script won’t do as expected.
I’ve replaced “icmp” with “from” and now its okay.
There is no “icmp” in case of failure. But thank you
Hi, with Ubuntu 20.08:
root@mediaserver:~# ping 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
From 192.168.1.6 icmp_seq=1 Destination Host Unreachable
From 192.168.1.6 icmp_seq=2 Destination Host Unreachable
From 192.168.1.6 icmp_seq=3 Destination Host Unreachable
And this is debian 11:
root@monitor-server:~# ping 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
From 192.168.1.4 icmp_seq=1 Destination Host Unreachable
From 192.168.1.4 icmp_seq=2 Destination Host Unreachable
From 192.168.1.4 icmp_seq=3 Destination Host Unreachable
Interesting
Look my ping
# ping -c 3 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
— 192.168.1.1 ping statistics —
3 packets transmitted, 0 received, 100% packet loss, time 2051ms
Any way thank you, i will make your suggested fix in script
I want to invite you to register on our form
https://forum.arstech.net/t/script-to-reboot-ubuntu-if-ping-fail/53