Skip to content

Instantly share code, notes, and snippets.

@samwise4
Last active October 10, 2023 01:23
Show Gist options
  • Save samwise4/fcd123e2c8a230febcba02388750a4f4 to your computer and use it in GitHub Desktop.
Save samwise4/fcd123e2c8a230febcba02388750a4f4 to your computer and use it in GitHub Desktop.
Bash script to monitor internet outages
# return 1 if alive, 0 if dead
ping_success() {
! ping -c1 -W1 8.8.8.8 >/dev/null 2>&1
}
# Spinner taken from https://stackoverflow.com/a/12498395
spinnerindex=0
spinner='-\|/'
sleepy_spinner() {
for (( i=0; i<$(($1 * 2)); i++ ))
do
spinnerindex=$(( (i+1) %4 ))
printf "\r${spinner:$spinnerindex:1} $2"
sleep 0.5
done
}
downstart=$(date +%s);
downend=$(date +%s);
downcount=0
internetstatus=1
while [ 1 ]; do
(ping_success)
pingresult=$?
if ((pingresult==0)) && ((internetstatus==1)); then
((internetstatus=0))
((downcount++))
downstart=$(date +%s);
dt=$(date +%Y-%m-%d" "%H:%M:%S);
printf "\r$dt Internet went down #$downcount\n"
elif ((pingresult==1)) && ((internetstatus==0)); then
((internetstatus=1))
downend=$(date +%s);
dt=$(date +%Y-%m-%d" "%H:%M:%S);
downseconds=$(( ($downstart - $downend) * -1 ))
if ((downseconds < 60)); then
printf "\r$dt Internet alive after being offline for $downseconds seconds\n"
else
downminutes=$(( $downseconds / 60 ))
printf "\r$dt Internet alive after being offline for $downminutes minutes\n"
fi
fi
# Spin spinner so the user knows we're alive
if ((internetstatus==1)); then
(sleepy_spinner 15 "Online")
else
(sleepy_spinner 5 "No connection")
fi
done
@Mario-NTT
Copy link

Thanks, used this for a basic monitoring of my internet connection to see how often it drops out/for how long, from a pi-hole.
Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment