1. Preface
有时远端部署的机器人会由于各种外部原因,断开网络,但是之后又没有重新接入网络,直接就失联了,其实就时一个网络重连就可以解决的事情。
2. Solution
1)先查看得到准确的wifi名字,这个很重要。用指令nmcli connection show查询当前系统连接过的wifi,返回如下:
NAME UUID TYPE DEVICE
HKWIFI xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx wifi wlp3s0
下面以HKWIFI为例。
2)创建自动重连脚本
要在根目录下创建:
sudo gedit /usr/local/bin/wifi-reconnect.sh
也可以用你自己熟悉的编辑工具,vim,nano都可以。
然后写入如下内容,记得检查第一行的WIFI_NAME。
#!/bin/bash
WIFI_NAME="HKWIFI"
CHECK_HOST="8.8.8.8"
LOG_FILE="/var/log/wifi-reconnect.log"
echo "$(date '+%F %T') Checking Wi-Fi..." >> "$LOG_FILE"
# 如果指定 Wi-Fi 已连接,并且能 ping 通,则不处理
if nmcli -t -f NAME connection show --active | grep -Fxq "$WIFI_NAME"; then
if ping -c 2 -W 3 "$CHECK_HOST" >/dev/null 2>&1; then
echo "$(date '+%F %T') Wi-Fi is working." >> "$LOG_FILE"
exit 0
fi
fi
echo "$(date '+%F %T') Wi-Fi disconnected or no internet. Reconnecting..." >> "$LOG_FILE"
# 关闭再打开 Wi-Fi
nmcli radio wifi off
sleep 3
nmcli radio wifi on
sleep 5
# 尝试连接指定 Wi-Fi
nmcli connection down "$WIFI_NAME" >/dev/null 2>&1
sleep 2
nmcli connection up "$WIFI_NAME" >> "$LOG_FILE" 2>&1
# 再检查一次
sleep 5
if ping -c 2 -W 3 "$CHECK_HOST" >/dev/null 2>&1; then
echo "$(date '+%F %T') Reconnected successfully." >> "$LOG_FILE"
else
echo "$(date '+%F %T') Reconnect failed." >> "$LOG_FILE"
fi
然后还要给权限:
sudo chmod +x /usr/local/bin/wifi-reconnect.sh
3)创建 systemd 定时服务
先创建service文件
sudo gedit /etc/systemd/system/wifi-reconnect.service
写入:
[Unit]
Description=Reconnect Wi-Fi if disconnected
After=NetworkManager.service
Wants=NetworkManager.service
[Service]
Type=oneshot
ExecStart=/usr/local/bin/wifi-reconnect.sh
然后创建timer文件
sudo gedit /etc/systemd/system/wifi-reconnect.timer
写入:
[Unit]
Description=Run Wi-Fi reconnect check every minute
[Timer]
OnBootSec=30
OnUnitActiveSec=60
Unit=wifi-reconnect.service
[Install]
WantedBy=timers.target
4)启动定时服务
打开terminal,输入:
sudo systemctl daemon-reload
sudo systemctl enable --now wifi-reconnect.timer
输入完之后可以查看这个计时器是否正在执行
systemctl status wifi-reconnect.timer
然后可以看到返回的信息,显示active状态就是启动成功了
● wifi-reconnect.timer - Run Wi-Fi reconnect check every minute
Loaded: loaded (/etc/systemd/system/wifi-reconnect.timer; enabled; vendor pre
Active: active (waiting) since Tue 2026-04-28 15:45:52 HKT; 21min ago
Trigger: Tue 2026-04-28 16:08:08 HKT; 53s left
此外,还能查看它的日志文件:
sudo tail -f /var/log/wifi-reconnect.log
可以手段断开网络,看看是否会重连,如果成功重连就说明生效了,同时查看日志文件,也能看到对应的记录。