Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save schlos/2a5689374b8f6897583030d08ad4f554 to your computer and use it in GitHub Desktop.
Save schlos/2a5689374b8f6897583030d08ad4f554 to your computer and use it in GitHub Desktop.
A handy Bash script to monitor your internet connection, log downtimes, and notify you of changes in connectivity status.
#!/bin/bash
# Default Configurations
DEFAULT_PING_HOSTS=("8.8.8.8" "1.1.1.1")
DEFAULT_CHECK_INTERVAL=10
DEFAULT_LOG_FILE="$(dirname "$0")/internet_downtime.log"
# Initialize Configurations
PING_HOSTS=("${DEFAULT_PING_HOSTS[@]}")
CHECK_INTERVAL=$DEFAULT_CHECK_INTERVAL
LOG_FILE=$DEFAULT_LOG_FILE
# Parse Command Line Arguments
while getopts "h:i:l:" opt; do
case $opt in
h) IFS=',' read -r -a PING_HOSTS <<< "$OPTARG";;
i) CHECK_INTERVAL="$OPTARG";;
l) LOG_FILE="$OPTARG";;
*) echo "Usage: $0 [-h hosts] [-i interval] [-l logfile]"; exit 1;;
esac
done
# Function Definitions
check_internet() {
for host in "${PING_HOSTS[@]}"; do
if /sbin/ping -c 1 "$host" &>/dev/null; then
return 0
fi
done
return 1
}
log_message() {
echo "$(date) - $1" | tee -a "$LOG_FILE"
}
send_notification() {
local message=$1
if [ "$(uname)" == "Darwin" ]; then
/usr/bin/osascript -e "Display notification \"$message\" with title \"Connectivity Alert\""
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
notify-send "Connectivity Alert" "$message"
fi
}
handle_exit() {
log_message "Internet connectivity checker stopped."
exit 0
}
# Trap SIGINT for graceful termination
trap handle_exit SIGINT
# Main Loop
log_message "Internet connectivity checker started."
notification_sent=0
down_times=0
longest_duration=0
downtime_start=0
while true; do
if check_internet; then
if [ "$notification_sent" -eq 1 ]; then
send_notification "Internet is reconnected"
notification_sent=0
downtime_end=$(date +%s)
duration=$((downtime_end - downtime_start))
down_times=$((down_times + 1))
longest_duration=$(($duration > $longest_duration ? $duration : $longest_duration))
fi
echo -ne "\rDowntimes: $down_times | Longest Duration: ${longest_duration}s | Status: \033[32mONLINE\033[0m"
else
if [ "$notification_sent" -eq 0 ]; then
send_notification "Internet is disconnected"
notification_sent=1
downtime_start=$(date +%s)
log_message "Internet down"
fi
echo -ne "\rDowntimes: $down_times | Longest Duration: ${longest_duration}s | Status: \033[31mOFFLINE\033[0m"
fi
sleep "$CHECK_INTERVAL"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment