Setting preferred wireless networks from the command line.
If you need to set a wireless network in Mac OS X from the command line or with a script, you can do so with the networksetup command. Networksetup has a few options that are specifically geared to working with wireless networks. For me, one of the more useful is the ability to set wireless networks, either manually via the command line or automating it with a script. You can set this using the -addpreferredwirelessnetworkatindex option, with the network port, wireless network name, the index number you want to assign it to (set it to 0 if you don’t know what to set it to, as that’ll bump it to the top of the list), and the security type of the wireless network (OPEN, WEP, WPA, WPA2, WPAE or WPA2E). You can also substitute NONE in place of OPEN in the security type.
For example, you may have a wireless network named HomeNetwork that uses WPA2 encryption with the password of donthackme. It’s the only one in your environment and you want to set your Mac(s) to prefer this wireless network. To set your preferred wireless network, log into your Mac(s) with an admin account, open Terminal and run the following command:
sudo networksetup -addpreferredwirelessnetworkatindex AirPort HomeNetwork 0 WPA2 donthackme
Running this command will add it to the list of your preferred wireless networks in System Preferences: Network: Airport. It will also add a password item to the System keychain for the HomeNetwork wireless network, which will store the donthackme password.
For greater flexibility, you can also script this so that all of the various values after -addpreferredwirelessnetworkatindex are variables which can be set as needed. See below the jump for a script that shows how to do this.
Hat tip to Charles Edge for describing this method in this entry on his blog: http://krypted.com/mac-os-x/pushing-wireless-networks-out/
# Enable the wireless method you need and
# add the correct variables as needed. The
# wireless network name should not contain spaces.
# Set the WIRELESS variable to the wireless
# network port you want to use. (leave it as
# "AirPort" if you do not know what port to use.)
# Set the SSID variable to your wireless network name
# to set the network name you want to connect to.
# Note: Wireless network name cannot contain spaces.
# Set the INDEX variable to the index number you’d like
# it to be assigned to (leave it as "0" if you do not know
# what index number to use.)
# Set the SECURITY variable to the security type of the
# wireless network (NONE, WEP, WPA, WPA2, WPAE or
# WPA2E) Setting it to NONE means that it's an open
# network with no encryption.
# If you've set the SECURITY variable to something other than NONE,
# set the password here. For example, if you are using WPA
# encryption with a password of "thedrisin", set the PASSWORD
# variable to "thedrisin" (no quotes.)
sudo networksetup -addpreferredwirelessnetworkatindex $WIRELESS $SSID $INDEX $SECURITY $PASSWORD