mac无法原生按流量阈值自动关机,但可通过launchd+python脚本实现持续高流量(如连续3次超8mb/s)后关机;另支持快捷指令手动触发式流量监控关机。

Mac无法直接基于实时网络流量数值(如“当上传超过500MB时”)触发自动关机,系统原生不提供流量阈值监控能力;但可通过组合终端命令+后台脚本+自动化工具,实现“检测到持续高流量后执行关机”的近似效果。
用launchd创建流量监控后台任务
这一步建立一个每30秒检查一次网络活动的守护进程,一旦发现连续3次网卡收发速率均高于8MB/s,就触发关机。它不依赖用户登录,开机即运行。
第一步:打开终端 → 输入mkdir -p ~/Library/LaunchAgents → 回车创建配置目录。
第二步:执行touch ~/Library/LaunchAgents/com.user.netwatch.plist → 创建空的plist文件。
第三步:用文本编辑器打开该文件:open -e ~/Library/LaunchAgents/com.user.netwatch.plist → 粘贴以下内容并保存:
第四步:创建脚本目录并写入检测逻辑:mkdir -p ~/bin && touch ~/bin/netwatch.py → 用open -e ~/bin/netwatch.py打开 → 粘贴Python脚本(需替换en0为你实际网卡名,可用ifconfig | grep "^[a-z]"确认):
import subprocess, time, os
def get_bytes(iface):
try:
out = subprocess.check_output(['netstat', '-ib'], text=True)
for line in out.split('\n'):
if line.startswith(iface):
parts = line.split()
rx = int(parts[6]) if len(parts) > 6 else 0
tx = int(parts[9]) if len(parts) > 9 else 0
return rx, tx
except: pass
return 0, 0
# 读取上一次统计
log_file = os.path.expanduser('~/tmp/netwatch.state')
last_rx, last_tx, last_time = 0, 0, 0
if os.path.exists(log_file):
with open(log_file) as f:
try:
last_rx, last_tx, last_time = map(float, f.read().strip().split())
except: pass
# 当前统计
now = time.time()
curr_rx, curr_tx = get_bytes('en0')
if last_time == 0 or now - last_time
with open(log_file, 'w') as f:
f.write(f'{curr_rx} {curr_tx} {now}')
exit(0)
# 计算速率(字节/秒)
rx_rate = (curr_rx - last_rx) / (now - last_time)
tx_rate = (curr_tx - last_tx) / (now - last_time)
# 阈值设为8MB/s = 8 * 1024 * 1024
THRESHOLD = 8388608
if rx_rate > THRESHOLD and tx_rate > THRESHOLD:
# 连续三次才关机:写标记文件
flag_file = os.path.expanduser('~/tmp/netwatch.tripped')
if os.path.exists(flag_file):
with open(flag_file) as f:
count = int(f.read().strip() or '0') + 1
if count >= 3:
subprocess.run(['sudo', 'shutdown', '-h', 'now'])
exit(0)
with open(flag_file, 'w') as f:
f.write(str(count))
else:
with open(flag_file, 'w') as f:
f.write('1')
else:
if os.path.exists(flag_file):
os.remove(flag_file)
# 更新状态
with open(log_file, 'w') as f:
f.write(f'{curr_rx} {curr_tx} {now}')
【必须提前给python脚本可执行权限】:在终端中运行chmod +x ~/bin/netwatch.py,否则launchd会静默失败。
用快捷指令+终端命令实现手动触发式流量关机
当你知道某项任务(如大文件上传)即将开始,想让它跑完自动关机,又不愿长期运行后台程序时,这个方法更轻量、可控。
方法一:一键启动监控并关机
打开快捷指令App → 新建快捷指令 → 添加操作“运行脚本” → 类型选“Shell” → 粘贴:
echo '#!/bin/bash' > /tmp/traffic_shutdown.sh
echo 'start_rx=$(netstat -ib | grep en0 | awk "{print \$6}")' >> /tmp/traffic_shutdown.sh
echo 'start_tx=$(netstat -ib | grep en0 | awk "{print \$9}")' >> /tmp/traffic_shutdown.sh
echo 'sleep 60' >> /tmp/traffic_shutdown.sh
echo 'end_rx=$(netstat -ib | grep en0 | awk "{print \$6}")' >> /tmp/traffic_shutdown.sh
echo 'end_tx=$(netstat -ib | grep en0 | awk "{print \$9}")' >> /tmp/traffic_shutdown.sh
echo 'rx_diff=$((end_rx - start_rx))' >> /tmp/traffic_shutdown.sh
echo 'tx_diff=$((end_tx - start_tx))' >> /tmp/traffic_shutdown.sh
echo 'if [ $rx_diff -gt 500000000 ] || [ $tx_diff -gt 500000000 ]; then sudo shutdown -h now; fi' >> /tmp/traffic_shutdown.sh
chmod +x /tmp/traffic_shutdown.sh
/tmp/traffic_shutdown.sh
方法二:仅监控当前流量峰值(不自动关机,供你判断)
添加“运行脚本”操作 → Shell类型 → 粘贴:netstat -ib | grep en0 | awk '{print "RX:", $6/1024/1024 "MB", "TX:", $9/1024/1024 "MB"}' → 这会立刻输出当前网卡总收发量(单位MB),适合快速查看是否已跑满带宽。
验证与调试关键步骤
① 检查网卡名是否正确:ifconfig | grep "^[a-z]" | head -3 → 输出第一行类似en0:的才是你主网卡,脚本里必须用这个名称,否则流量永远读不到。
② 手动测试脚本是否可执行:python3 ~/bin/netwatch.py → 若报错ModuleNotFoundError: No module named 'subprocess',说明路径或语法有误;若无输出,说明逻辑未触发,可临时把THRESHOLD = 1000调低测试。
③ 查看守护进程状态:launchctl list | grep netwatch → 有输出且CODE为0表示已加载;若无输出,运行launchctl load ~/Library/LaunchAgents/com.user.netwatch.plist手动加载。
④ 监控日志:tail -f /tmp/netwatch.log → 可实时看到每次检测结果,便于判断速率计算是否合理。











