mac根据wifi切换工作环境

2017/07/11 mac

每次到公司到需要把音量调节到最小,在手动连公司的smb服务器…等等一系列繁琐的操作,能不能够开盖唤醒mac后立刻优雅的办公?

使用launchctl检测wifi名称然后调用相应的applescript完美解决!

先编写shell脚本

先识别出当前的SSID,根据SSID判断工作环境(第一次运行的时候需要给mac_wifi.sh授权安全性与隐私设置),另外在避免每次唤醒的时候重复执行shell脚本。

vim \work\_script\mac_wifi.sh
#/bin/sh
LANG=en_US.UTF-8
export LANG

SSID=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk -F': ' '/ SSID/{print $NF}')

# 调节系统音量
function ChangeVolume(){
    osascript <<EOD
tell application "System Preferences"
    set current pane to pane "com.apple.preference.sound"
end tell

tell application "System Events"
    tell application process "System Preferences"
        set value of value indicator 1 of slider 1 of window "声音" to $1
    end tell
end tell

quit application "System Preferences"
return
EOD
}

# 连接服务器
function ConnectSmb(){
    osascript <<EOD
tell application "Finder"
    open location "$1"
    --activate
end tell
EOD
}

# 右上角消息提示
function Message(){
    osascript <<EOD
   display notification "$1" with title "xiaocai的mac"
EOD
}

# 避免唤醒重复执行shell
if [ ! -f "/tmp/.lastwifi" ]; then
    echo $SSID > /tmp/.lastwifi
fi
LAST_WIFI=`cat /tmp/.lastwifi`
if [ $SSID == $LAST_WIFI ]; then
    exit
fi

# 有连上wifi才记录最后连接的wifi名称
if [ -n "$SSID" ]; then 
    echo $SSID > /tmp/.lastwifi
fi

if [ $SSID == 'BAIDU' ]; then
    # 切换到公司环境
    ChangeVolume 0.1
    if [ ! -d /Volumes/worker_data ]; then
        ConnectSmb smb://worker:xiaocai@10.99.196.55/worker_data
    fi
    if [ ! -d /Volumes/ci_data ]; then
        ConnectSmb smb://sysCI:QAbaidu039@10.99.196.11/ci_data
    fi
    Message '您的mac已切换至办公环境~'
elif [ $SSID = "TP-LINK-XIAOCAI" ] ; then
    # 切换到家庭环境
    ChangeVolume 0.5
    if [ -d /Volumes/worker_data ]; then
        umount /Volumes/worker_data
    fi
    if [ -d /Volumes/ci_data ]; then
        umount /Volumes/ci_data
    fi
    Message '您的mac已切换至家庭环境~'
else
    exit
fi

创建plist配置文件

当wifi发生改变时候/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist文件将产生变化

vim ~/Library/LaunchAgents/xiaocai.crontab.wifi.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>xiaocai.crontab.wifi</string>
  <key>ProgramArguments</key>
  <array>
    <string>/work/_script/mac_wifi.sh</string>
  </array>
  <key>WatchPaths</key>
  <array>
      <string>/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist</string>
  </array>
</dict>
</plist>

将任务加入系统

$ launchctl load ~/Library/LaunchAgents/xiaocai.crontab.wifi.plist
$ launchctl list | grep xiaocai
-	0	xiaocai.crontab.backdisk
-	0	xiaocai.crontab.wifi

Search

    Table of Contents