Mac|VPN 自动重连脚本

VPN 在实际使用当中,由于系统的机制常常导致使用不愉快——切换网络/息屏/睡眠等情况下自动断开

我虽然只是偶尔使用,但是每次使用,难免会遇到以上场景然后断开的情况,接着就得手动去连接,实在是麻烦不已。

于是我就改良了个脚本,让它断开后自动重连

具体步骤如下:

  • 打开系统自带软件:脚本编辑器
  • 新建一个文档,输入代码(见下方)
  • 代码输入后,点击文件-储存-配置如下:
    • 位置:应用程序
    • 文件格式:应用程序
    • 选项:勾选「运行处理程序后保持打开」
  • 保存这个脚本程序,然后去运行即可。如果想要开机启动,可以在 Dock 上右键它-选项-登录时打开

经过测试,切换网络以及息屏后,脚本会在几秒内运行,然后连接上某个可用的 VPN。

这个脚本的好处是,可以省去手动连接的麻烦,如果你有多个可用的 VPN,它可以做到逐个尝试。不妨尝试一下。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
on idle
	tell application "System Events"
		tell current location of network preferences
			
			-- check vpn connection status
			set connected_vpn to get name of every service whose (kind is greater than 10 and kind is less than 17) and connected of current configuration is true
			set connect_status to count of connected_vpn
			
			if connect_status is 0 then
				-- get vpn list
				set vpn_list to get name of every service whose (kind is greater than 10 and kind is less than 17)
				
				-- select random one
				set vpn_count to count of vpn_list
				set selected_serial to random number from 1 to vpn_count
				set selected_vpn to item selected_serial of vpn_list
				
				display notification "Connect to " & selected_vpn & " ..."
				
				-- connect select vpn
				set vpn to the service selected_vpn
				if vpn is not null then
					if current configuration of vpn is not connected then
						connect vpn
					end if
				end if
				
			end if
		end tell
		return 30
	end tell
end idle

如果不需要逐一访问每个 VPN,可使用以下脚本,10s检查一次,只需替换 VPN 名字就好,代码来自好友提供。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
on idle
	set en0 to do shell script "ipconfig getifaddr en0; exit 0"
	if en0 is not "" then
		tell application "System Events"
			tell current location of network preferences
				set vpnConnection to the service "VPN 名字"
				if vpnConnection is not null then
					if current configuration of vpnConnection is not connected then
						connect vpnConnection
					end if
				end if
			end tell
			return 10
		end tell
	end if
end idle
加载评论