script to toggle wifi

hi

Here is a script for toggling wifi on and off. Its the first script I've made (with the help of a friend); i'm sure this could be improved and made more efficient.

Hardware: MacMini OS 10.7.5, RouterBoard 6.7
Software: Growl and GrowlNotify, Automator, Terminal, SSH
Prereqs.: Create a key using ssh-keygen and import it into the Mikrotik Router, using RouterOS - RouterOS - MikroTik Documentation. Also, download and install Growl and GrowlNotify from http://growl.info

The script below, first turns on the WiFi interface on the MacMini, pauses for a few seconds to allow the Mac to connect to my wifi network, extracts the SSID of the connected network, and then uses an If-Then statement to enable wifi on the Mikrotik Router (if it is disabled), or to disable it (if it is enabled). The script then turns off the WiFi interface on the MacMini and an appropriate growl notification is made. The script is made in Automator, and application resides on my desktop. This makes it convenient to either turn on the wifi in my home, or to turn it off. However, my Mac needs to be turned on before the wifi is enabled or disabled.

/bin/bash shell script

turn wifi on from terminal, and pause for 6 seconds

networksetup -setairportpower en1 on && sleep 6

find SSID of current network

SSID=/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | grep -w '<insert-name-of-network-here>' | awk '{print $2}'

if wifi is available, then disable it, and display growl notification

if [ "$SSID" = "" ] ; then ssh -l admin-ssh -i ~/.ssh/id_dsa <insert-IP-of-Mikrotik-Router-here> "interface wireless disable 0" && /usr/local/bin/growlnotify -m "disabled" "WiFi" ; fi

if wifi is unavailable, then enable it, and display growl notification

if [ "$SSID" = "" ] ; then ssh -l admin-ssh -i ~/.ssh/id_dsa <insert-IP-of-Mikrotik-Router-here> "interface wireless enable 0" && /usr/local/bin/growlnotify -m "enabled" "WiFi" ; fi

turn wifi off from terminal:

networksetup -setairportpower en1 off

Already received some feedback on this script from a friend, as follows:

  • if you use hardware growler, you dont’ need to use growlnotify
  • if you still want to use growlnotify, keep in mind that it says “command to switch off” has been sent to router - not a confirmation it actually has been switched off
  • same for enable
  • the script bases the possibility of enabling / disableing the network based on the SSID - you could also use the network location and/or the IP - or the pingability of the router - which may be more flexible