Last active
January 9, 2022 07:58
-
-
Save tkshnwesper/88570e63fce8d3f1753e5510a0db4f23 to your computer and use it in GitHub Desktop.
Script to automatically restart a system if there's a problem in connecting to the internet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
HOSTNAME=1.1.1.1 | |
TIMEOUT=150 | |
TEST_INTERVAL=60 | |
ping_host() { | |
ping -c1 "$HOSTNAME" &> /dev/null | |
} | |
reboot_on_timeout() { | |
local start_time=$(date +%s) | |
local attempt_count=0 | |
until ping_host | |
do | |
local end_time=$(date +%s) | |
DIFF=$(( $end_time - $start_time )) | |
if [ "$DIFF" -gt "$TIMEOUT" ] | |
then | |
echo "Rebooting..." | |
reboot | |
break | |
fi | |
(( ++attempt_count )) | |
echo "Retrying $attempt_count/$TIMEOUT time(s)" | |
sleep 1 | |
done | |
echo "Reacquired connection to host!" | |
} | |
while true | |
do | |
ping_host 2>&1 > /dev/null | |
if [ "$?" -ne 0 ] | |
then | |
echo "Could not connect to host... Starting reboot countdown" | |
reboot_on_timeout | |
fi | |
echo "Could connect to host" | |
sleep "$TEST_INTERVAL" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment