如何用AppleScript自动重启FTP传大文件时卡住的WiFi连接?
用AppleScript自动重启WiFi解决FTP上传时的假死问题
基础重启脚本
直接实现禁用并重新启用WiFi的核心代码:
-- 禁用并重新启用WiFi tell application "System Events" tell current location of network preferences -- 替换为你的WiFi服务名称,中文系统通常是"无线局域网" set wifi to service "Wi-Fi" if enabled of wifi then set enabled of wifi to false delay 2 -- 等待2秒确保WiFi完全关闭 set enabled of wifi to true else set enabled of wifi to true end if end tell end tell
脚本说明
- 脚本通过
System Events访问系统网络偏好设置,定位WiFi服务并执行重启操作 - 关键注意:如果你的WiFi服务名称不是
Wi-Fi(比如中文系统显示为「无线局域网」),需要修改service "Wi-Fi"中的名称。可以在「系统设置 → 网络」面板查看当前WiFi的服务名称。
在Script Editor中的操作步骤
- 打开「Script Editor」(Launchpad → 其他 文件夹内)
- 粘贴上述代码
- 点击运行按钮(▶️)测试,系统会弹出权限请求,前往「系统设置 → 隐私与安全性 → 自动化」,允许Script Editor控制「System Events」
- 测试正常后,点击菜单栏「文件 → 导出」,格式选择「应用程序」,生成可直接双击运行的APP,也可添加到Dock快速调用。
进阶:自动检测FTP连接异常后触发重启
如果希望脚本自动检测FTP服务器是否可达,再执行重启,可使用带ping检测的版本:
-- 检测FTP服务器连通性,异常则重启WiFi set targetFtpHost to "ftp.your-server.com" -- 替换为你的FTP服务器地址 set pingStatus to do shell script "ping -c 3 " & targetFtpHost & " | grep '0 received'" -- 如果ping 3次都没收到回应,说明网络假死 if pingStatus is not "" then tell application "System Events" tell current location of network preferences set wifi to service "Wi-Fi" if enabled of wifi then set enabled of wifi to false delay 2 set enabled of wifi to true end if end tell end tell end if
额外提示
- 若延迟2秒不够,可调整
delay后的数值(比如改为3),确保WiFi完全关闭再重启 - 若使用多网络位置,脚本只会操作当前活跃位置的WiFi服务
- 可以通过「自动操作」或
launchd将进阶脚本设置为定时任务,定期检测并自动修复
内容的提问来源于stack exchange,提问作者rikicecchi
相关产品推荐
相关产品推荐

