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

applescriptNetworkwifi

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.

Best Answer

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...