How can I write an AppleScript which when run will connect to a specific WIFI network if available?

The title pretty much sums it up. I want to avoid having to use the trackpad to connect to certain networks. This comes up often when a new network becomes available but I'm already connected to another one.


One way to do this to use the terminal command:

networksetup -setairportnetwork "en1" "name" "password"

from a script. Here's a simple Python script that will do this:

#!/usr/bin/env python

import subprocess
# display current network 
subprocess.call(["networksetup", "-getairportnetwork", "en1"])
# switch to new 
subprocess.call(["networksetup", "-setairportnetwork", "en1", "Airport2", "topsecret"])

and this runs fine from inside Keyboard Maestro or TextExpander after you define a single keystroke to run it.

You can run these commands from AppleScript instead - I just get tired of trying to guess the right syntax for everything...


You can also use ControlPlane:

  1. Enable "Nearby WiFi Network" from the Evidence Sources tab.
  2. Add a nearby WiFi network rule from the Rules tab.
  3. Add a Network Location or Run Shell Script action from the Actions tab.