2012-07-25

如何利用 script 來自動切換 OSX 的網路位置

OSX 有個很方便的功能,可以針對不同的網路環境設定位置 profile,利用切換網路位置來快速調整網路設定。雖然說很方便,但是,每次都要進到網路設定去改,還是有點麻煩。

還好 OSX 有指令可以用來調整,因此我們可以利用指令取得目前使用的無線網路 SSID 來辨斷要切換到哪個網路位置去:

#!/bin/bash
# 先取得 SSID
ssid=$(networksetup -getairportnetwork en1 | cut -c 24-)
# 依 SSID 決定要用哪個 location ,可利用 scselect 指令來列出所有的 location
if [ $ssid = "ScottAP" ]
then
location="Work"
else
location="Automatic"
fi
# 更新 location
newloc=`/usr/sbin/scselect ${location} | sed 's/^.*(\(.*\)).*$/\1/'`
echo ${newloc}
# 辨斷是否正確來回撌值
if [ ${location} != ${newloc} ]
then
exit 1
fi
exit 0
view raw autolocation.sh hosted with ❤ by GitHub
參考:
http://hints.macworld.com/article.php?story=2005010613401823
http://stackoverflow.com/questions/4481005/get-wireless-ssid-through-shell-script-on-mac-os-x