Skip to content

Instantly share code, notes, and snippets.

@flesch
Last active November 28, 2017 18:19
Show Gist options
  • Save flesch/bbfb7330d95dc33824c8 to your computer and use it in GitHub Desktop.
Save flesch/bbfb7330d95dc33824c8 to your computer and use it in GitHub Desktop.
Reconnect to a Wi-Fi network upon waking up (using SleepWatcher)
#!/bin/sh
# Reconnect to a Wi-Fi network upon waking up.
WIFI_SSID=EDIT_WIFI_SSID
WIFI_PASSWORD=EDIT_WIFI_PASSWORD
airport=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
interface=$(networksetup -listallhardwareports | grep -A1 Wi-Fi | awk '/Device:/ {print $2}')
attempts=0
until [ -n "$($airport -I | awk '/^ *SSID/ {print $2}')" ] || [[ $attempts -gt 10 ]]; do
if [ -n "$($airport -s | grep $WIFI_SSID)" ]; then
networksetup -setairportnetwork "$interface" "$WIFI_SSID" "$WIFI_PASSWORD"
fi
attempts=$((attempts + 1))
sleep 1
done

When Bluetooth is enabled, my Macbook Air loses its Wi-Fi connection when it goes to sleep (see Issue #2 here). I often have to scan for my home network and manually reconnect, so this is quicky and dirty solution to reconnect to my Wi-Fi network when the machine wakes up.

  1. Install SleepWatcher using brew. Make sure to follow the launchd instructions once installed.

    $ brew install sleepwatcher
  2. Create ~/.wakeup (and optionally ~/.sleep), and make them executable. sleepwatcher will run these scripts when the machine wakes/sleeps.

    $ touch ~/.wakeup
    $ chmod +x ~/.wakeup
  3. Copy the contents of .wakeup to the file you just created above. Edit your Wi-Fi network details (EDIT_WIFI_SSID and EDIT_WIFI_PASSWORD). The script will make 10 attempts to connect before giving up.

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