最后更新于
如何在网络出问题时自动重启 OpenClash
家里的路由使用了 OpenWrt,上面运行了 OpenClash 作为代理服务。最近发现网络偶尔会掉线,掉线后国内国外的网络都无法访问,此时查看系统状态,发现 clash 进程的 cpu 占用总是 100%。此时重启 OpenClash 就可以恢复网络,所以写了一个脚本,定期检测网络联通性,如果网络不通则重启 OpenClash。
#!/bin/bash
URL="http://connect.rom.miui.com/generate_204"INTERVAL=5MAX_FAILURES=3
failures=0
while true; do if curl -s -o /dev/null -w "%{http_code}" "$URL" | grep -q "204"; then failures=0 else ((failures++))
if [ $failures -ge $MAX_FAILURES ]; then echo "连续 $MAX_FAILURES 次请求失败,重启 OpenClash" if service openclash restart; then echo "OpenClash 重启成功" else echo "OpenClash 重启失败" fi failures=0 fi fi
sleep $INTERVALdone
将上面的文件保存为 network_monitor.sh
,然后给它添加执行权限
chmod +x /root/network_monitor.sh
然后创建 init 脚本用来自动启动
vi /etc/init.d/network_monitor
#!/bin/sh /etc/rc.common
START=99STOP=15USE_PROCD=1
start_service() { procd_open_instance procd_set_param command /bin/sh "/root/network_monitor.sh" procd_set_param pidfile /var/run/network_monitor.pid procd_set_param stdout 1 procd_set_param stderr 1 procd_close_instance}
stop_service() { kill $(cat /var/run/network_monitor.pid)}
给 init 脚本添加执行权限
chmod +x /etc/init.d/network_monitor
然后启动服务
/etc/init.d/network_monitor enable/etc/init.d/network_monitor start