macos根据wifi自动切换等

date
Jan 27, 2022 08:00 AM
Related to 日程数据 1 (blog)
tags
MAC
Blog
slug
wifi
summary
4
版本11.4.0
notion image
使用脚本编辑器
notion image
使用如下脚本
 
set ssid to do shell script "/usr/local/bin/airport -I | awk -F': ' '/ SSID/{print $NF}'"
#set ssidnum to do shell script "/usr/local/bin/airport -s  |awk {'print $1}' |grep  dd |wc -l"
#display dialog "match ssid number is " & ssid
tell application "System Events"
	tell network preferences
		if ssid is "dd" then
			do shell script "scselect 'home'"
			do shell script "networksetup -setdhcp Wi-Fi"
			do shell script "cd ~/Library/Rime&& /Library/Input*/Squirrel.app/Contents/MacOS/Squirrel --quit  && /Library/Input*/Squirrel.app/Contents/MacOS/rime_dict_manager -s "
			do shell script "networksetup -setdnsservers Wi-Fi 1.1.1.1"
			#do shell script "/opt/homebrew/bin/brew services start syncthing"
			tell application "Resilio Sync"
				activate
				delay 1
				tell application "System Events"
					keystroke "w" using command down
				end tell
			end tell
		else
			do shell script "scselect 'work'"
			do shell script "networksetup -setdhcp Wi-Fi"
			do shell script "networksetup -setdnsservers Wi-Fi Empty"
		end if
	end tell
end tell
if ssid is "AndroidAP4dd3" then
	#do shell script "/opt/homebrew/bin/brew services stop syncthing"
	tell application "Resilio Sync"
		quit
	end tell
	
	#display dialog "match ssid is " & ssid
end if
 
 
依据wife的ssid自动设定网络位置及内部的ip等
依据 特定的Wi-Fi名如计算流量的ssid执行 services syncthing(一款同步工具)的启停
脚本调试正常后
还需要一个触发器来实现自动执行改脚本
添加到自动启动
$ cat ~/Library/LaunchAgents/com.devework.onnetworkchange.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>com.devework.onnetworkchange</string>
	<key>ProgramArguments</key>
	<array>
		<string>/usr/bin/osascript</string>
        <string>/Users/liujg/Documents/wifiauto.scpt</string>
	</array>
    <key>StandardOutPath</key>
    <string>/Users/liujg/onnetworkchange.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/liujg/onnetworkchange.err.log</string>
	<key>WatchPaths</key>
	<array>
		<string>/Library/Preferences/SystemConfiguration/com.apple.wifi.message-tracer.plist</string>
	</array>
</dict>
</plist>
使用命令控制
依次为:
卸载服务
加载服务
开始服务
查看服务
语法检查
  launchctl unload -w ~/Library/Launchagents/com.devework.onnetworkchange.plist
  sudo launchctl load -w ~/Library/LaunchAgents/com.devework.onnetworkchange.plist
  launchctl start com.devework.onnetworkchange
  launchctl list |grep devework
  plutil -lint com.devework.onnetworkchange.plist
重启测试自启动
切换网络环境测试自动切换即可
 

© lewoking 2021 - 2022