Mac OSX Shell Script to automate connecting to WiFi network

I have a Mac laptop running ‘Snow Leopard’ that occasionally will not connect to my home WiFi, even though other devices are connected to the network just fine.

I wrote a small shell script that uses the networksetup command to reset AirPort. If WiFi is still not connected, the script tries to assign the AirPort WiFi network directly. If that doesn’t work, it just resets AirPort again.

#!/bin/bash

AIRPORT="en1"; #may be en0, use networksetup -listallhardwareports to check
WIFI_NETWORK_NAME="network-name"
WIFI_PASSWORD="password"

networksetup -setairportpower $AIRPORT off
networksetup -setairportpower $AIRPORT on
sleep 2

if networksetup -getairportnetwork $AIRPORT | grep -i -a $WIFI_NETWORK_NAME ;
then
    echo 'Connected!';
    exit 0
fi

if networksetup -setairportnetwork $AIRPORT $WIFI_NETWORK_NAME $WIFI_PASSWORD | grep -i -a "Failed" ;
then
    echo 'Failed to connect, just restarting...';
    networksetup -setairportpower $AIRPORT off
    networksetup -setairportpower $AIRPORT on
    sleep 1
fi

networksetup -getairportnetwork $AIRPORT

exit 0;

If this script doesn’t work for you, then I suggest looking inside your routers Wireless settings. My router was set to use a default channel, and this seems to be best practice in terms of wireless signal optimization but for some reason, it was not suitable for my setup. I tried enabling the ‘Auto-Channel Select’ and immediately found it easier to find and connect to my network. As I understand it, this setting will continuously move the WiFi to the channel with least interference, supposedly giving the best signal (but I have seen this refuted elsewhere online).

As an aside, I also came across Appify, which will basically turn your shell script into a Mac App… very useful!

By the way, I’m a shell novice, so if anyone has any advice on more efficient code please leave a comment.

5 thoughts on “Mac OSX Shell Script to automate connecting to WiFi network

  1. Hey there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing months
    of hard work due to no data backup. Do you have any methods
    to protect against hackers?

  2. what about if you wanna connect to hard disk enclosure , specific ip ? I have this problem avery time I switch on my mac I have to manually connect to the hard disk

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s