Mac OS X: How to change your network settings based on Wifi SSID

Ever since I’ve seen Mac OS’s Location profiles (I think it was 2007), I’ve been wondering why the hell GNU/Linux didn’t have something like that. It was really convenient.

About a year after (maybe), Ubuntu switched to using NetworkManager which had something better: network profiles tied to the wifi network. Now I’m on Mac, I’ve been wondering why doesn’t Mac do that?

Good thing that the Internet fixes this.

I found this script through this SuperUser question.

Install it via Terminal by:

cd ~
git clone https://github.com/rimar/wifi-location-changer.git
cd wifi-location-changer
cp locationchanger /usr/local/bin
cp LocationChanger.plist ~/Library/LaunchAgents/
launchctl load ~/Library/LaunchAgents/LocationChanger.plist

If you don’t have git, you can copy the scripts below and save them in the paths provided with respective filenames:

LocationChanger.plist, save in ~/Library/LaunchAgents/

< ?xml version="1.0" encoding="UTF-8"?>
< !DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">

Label
locationchanger
ProgramArguments

/usr/local/bin/locationchanger

WatchPaths

/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist
locationchanger.sh, save in /usr/local/bin

#!/bin/bash

# automatically change configuration of Mac OS X based on location

# redirect all IO to /dev/null (comment this out if you want to debug)
# exec 1>/dev/null 2>/dev/null

# get a little breather before we get data for things to settle down
sleep 2

# get various system information
SSID=`/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I\
| grep ‘ SSID:’ | cut -d ‘:’ -f 2 | tr -d ‘ ‘`

# basic pattern matching to get all location names separated by newlines
LOCATION_NAMES=`scselect | tail -n +2 | cut -d “(” -f 2 | cut -d “)” -f 1`
CURRENT_LOCATION=`scselect | grep ” \* ” | cut -d “(” -f 2 | cut -d “)” -f 1`

# no brackets as we the grep will return a status code depending on whether the SSID has an own Location
if echo “$LOCATION_NAMES” | grep -q “$SSID”; then
NEW_LOCATION=”$SSID”
else
# auto does not seem to be working on Mac OS X Lion, but Automatic does
if echo Automatic | grep -q “$LOCATION_NAMES”; then
NEW_LOCATION=Automatic
elif echo auto | grep -q “$LOCATION_NAMES”; then
NEW_LOCATION=auto
else
echo “Automatic location was not found!”
echo “The following locations are known:”
echo “$LOCATION_NAMES”
fi
fi

if [ “x$NEW_LOCATION” != “x” -a “x$NEW_LOCATION” != “x$CURRENT_LOCATION” ]; then
echo “Changing to $NEW_LOCATION”
scselect “$NEW_LOCATION”
fi

Then type in the terminal:
launchctl load ~/Library/LaunchAgents/LocationChanger.plist