Last active
July 6, 2021 20:50
-
-
Save jsundram/d1f52aba78765763d44f18e9860d615e to your computer and use it in GitHub Desktop.
Internet connection goes down periodically on macos and needs to be restarted by turning wifi on and off again. Sigh.
This file contains hidden or 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 | |
# Adapted from https://stackoverflow.com/questions/6118948/bash-loop-ping-successful. | |
# Network connection mysteriously dies; ping every N seconds, and if ping fails | |
# turn wifi off and on again, which seems to fix it. | |
echo "run this script with sudo!" | |
echo "Starting ..." | |
DOWN=0 | |
while true; do | |
ping -c 3 google.com > /tmp/ping.$ | |
if [ $? -eq 0 ]; then | |
echo -n $(date +"%a, %b %d, %r") "-- " | |
cat /tmp/ping.$ | tail -1 | |
echo -n $(date +"%a, %b %d, %r") "-- " >> netstats.txt | |
cat /tmp/ping.$ | tail -1 >> netstats.txt | |
if [ $DOWN -eq 1 ]; then | |
DOWN=0 | |
say connection restored | |
fi | |
else | |
NET=`networksetup -getairportnetwork en0 | cut -d':' -f2 | xargs` | |
say connection to $NET is down | |
DOWN=1 | |
echo $(date +"%a, %b %d, %r") "-- failed ping; toggling interface" | |
echo -e $(date +"%a, %b %d, %r") "PING FAILED" >> ./network_interruptions.txt | |
echo "Disconnecting from $NET..." | |
# https://www.cyberciti.biz/faq/linux-unix-sleep-bash-scripting/ | |
networksetup -setnetworkserviceenabled Wi-Fi off | |
sleep 5 # Give the wifi time to disconnect. | |
networksetup -setnetworkserviceenabled Wi-Fi on | |
# testing if this leads to faster connect | |
networksetup -setairportnetwork en0 $NET | |
# sleep 10 # Give wifi enough time to connect before rechecking | |
# (need this if sleep at bottom of loop gets too short) | |
fi | |
# Checking ping every N seconds seems fine. | |
sleep 10 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment