AppleScript 通过调用 ping 命令检测网络延迟,解析平均值并弹窗提示;支持 LaunchAgent 定时执行、日志记录及多目标轮询,延时1秒避免并发干扰。
用 applescript 实现 macos 网络延迟自动检查,核心是调用系统命令 ping 并解析结果,再通过 applescript 封装成可定时或手动触发的脚本。
基础版:单次 ping 检测并弹窗提示
以下脚本向 google.com 发送 4 个 ICMP 包,提取平均延迟(单位毫秒),并在 macOS 弹窗中显示结果:
set host to "google.com"
set pingResult to do shell script "ping -c 4 " & quoted form of host & " | grep 'avg' | awk -F '/' '{print $5}'"
try
set avgLatency to (pingResult as number)
if avgLatency > 0 and avgLatency < 1000 then
display alert "网络延迟正常" message "平均延迟:" & avgLatency & " ms" as informational
else
display alert "网络延迟偏高" message "平均延迟:" & avgLatency & " ms" as critical
end if
on error
display alert "无法连接" message "无法访问 " & host & ",请检查网络" as warning
end try
增强版:支持自定义目标与阈值告警
将检测目标和延迟阈值设为变量,便于复用。例如检测公司内网服务器,并在超过 50ms 时发出通知:
- 修改
host为你的目标地址(如"192.168.1.1"或"dns.google") - 设置
threshold(单位 ms),默认 50;超过即触发「提醒」而非「警告」 - 使用
display notification静默推送,适合后台运行
set host to "dns.google"
set threshold to 50
<p>set cmd to "ping -c 3 " & quoted form of host & " 2>/dev/null | awk -F '/' '/avg/ {printf \"%.0f\", $5}'"
try
set avgLatency to (do shell script cmd) as number
if avgLatency > threshold then
display notification "延迟偏高:" & avgLatency & " ms" with title "网络监测" subtitle host
else
-- 可选:成功时不提示,或记录日志
end if
on error
display notification "Ping 失败" with title "网络监测" subtitle host
end try
自动化方案:配合 macOS 计划任务定期执行
AppleScript 本身不支持原生定时,但可借助系统工具实现自动运行:
查询 Apple 开发者文档、API 与 2014‑2025 年 WWDC 视频,搜索 SwiftUI、UIKit、Objective‑C、Swift 框架及 watch 会话。
- 将脚本保存为
.scpt文件(如CheckLatency.scpt) - 用
launchd创建 plist 文件,放在~/Library/LaunchAgents/下 - 示例 plist 中设置每 5 分钟运行一次:
<key>StartInterval</key><integer>300</integer> - 加载任务:
launchctl load ~/Library/LaunchAgents/com.user.latencycheck.plist
实用补充:日志记录与多目标轮询
若需长期观察,可在脚本中追加日志行:
set logPath to (path to desktop as text) & "latency-log.txt" set now to (current date) as string set logEntry to now & tab & avgLatency & " ms" & return do shell script "echo " & quoted form of logEntry & ">> " & quoted form of (POSIX path of logPath)
多目标检测只需把 host 列表循环处理,每次 ping 后延时 1 秒避免并发干扰,再汇总判断。

















