RouterOS 定时重启完整教程|每 3 天自动重启并记录日志(适配 v7.x)

0
82

RouterOS 定时重启 — 思与行(增强版)

适用版本:RouterOS v7.x(含 7.18+)

目标:实现 RouterOS 每隔固定时间自动重启,并在日志中记录重启前后状态。


一、基础思路

RouterOS 可以通过 /system scheduler 设置周期性任务来执行脚本。我们在这里分为两个部分:

  1. 定时重启任务 — 每 3 天执行一次 /system reboot
  2. 开机检测任务 — 检查上次是否为计划重启,并写入日志。

这样我们可以在日志中完整看到 “重启前 → 重启后” 的链路。


二、配置 NTP 与时区

为了保证定时任务准确触发,首先设置正确的时区与时间同步:

/system clock set time-zone-name=Asia/Shanghai
/system ntp client set enabled=yes
/system ntp client servers add address=cn.pool.ntp.org
/system ntp client servers add address=ntp.aliyun.com

可以通过以下命令确认同步状态:

/system ntp client print
/system clock print

三、创建定时重启任务(每 3 天一次)

/system scheduler add name=auto-reboot-3days start-date=oct/26/2025 start-time=02:55:00 interval=3d \
  on-event=":log info \"[auto] Scheduled reboot\"; \
  :local ts ( [/system clock get date].\" \".[/system clock get time]); \
  :local f [/file find name=\"last_reboot.flag\"]; \
  :local content (\"scheduled|\".\$ts); \
  if ([:len \$f]=0) do={/file add name=\"last_reboot.flag\" contents=\$content} else={/file set \$f contents=\$content}; \
  :delay 5s; /system reboot" \
  policy=reboot,read,write,policy

说明:

  • 写入日志 [auto] Scheduled reboot
  • 创建标记文件 last_reboot.flag,用于开机后识别。
  • 延迟 5 秒后执行 /system reboot

确认任务已启用:

/system scheduler print where name="auto-reboot-3days"

四、创建开机检测任务(boot-ack)

用于在系统启动后检查是否由计划重启触发。

/system scheduler add name=boot-ack start-time=startup \
  on-event=":local f [/file find name=\"last_reboot.flag\"]; \
  if ([:len \$f]>0) do={:local c [/file get \$f contents]; \
  /log info (\"[auto] Boot complete after scheduled reboot (\".\$c.\")\"); \
  /file remove \$f;}" \
  policy=read,write,policy

说明:boot-ack 无需设置时间(保持 start-time=startup 即可)。系统每次开机都会自动运行。


五、启用持久化日志(重启后仍能查看)

默认日志只保存在内存中,重启后会丢失。为了长期保留日志,我们可将脚本输出写入磁盘文件:

/system logging action add name=disklog target=disk disk-file-name=auto-reboot.log disk-lines-per-file=2000
/system logging add topics=script action=disklog

这样每次重启都会将 “[auto] Scheduled reboot” 和 “[auto] Boot complete after scheduled reboot” 写入磁盘文件 auto-reboot.log,即使重启后也能查看。


六、验证

查看任务是否正常:

/system scheduler print where name~"reboot|boot"
/system scheduler print detail where name="auto-reboot-3days"
/system scheduler print detail where name="boot-ack"

查看日志:

/log print where message~"Scheduled reboot|Boot complete"
/file print where name~"auto-reboot.log"

七、常见问题与补充建议

  • ⚠️ 脚本显示 “I – invalid”: 说明命令中存在非法换行或字符,请使用 { } 包裹脚本,或手动重新键入。
  • ⚙️ run-count 未增加: 因系统在重启前来不及写入计数,属正常现象,请以日志为准。
  • 🌍 时区与 NTP: 如果设备部署在国外,请根据当地设置 time-zone-name 并验证 NTP 是否同步。
  • 🧠 安全提示: 若设备在生产环境,请避免高峰期重启,可增加通知机制(如 Telegram / Email 告警)。

八、总结

通过以上配置,RouterOS 可以:

  1. 每隔指定时间自动执行安全重启。
  2. 重启前后自动写日志与时间戳。
  3. 通过磁盘日志持久化保留操作记录。

这套机制简单高效,可广泛用于长时间运行的 RouterBoard、网关服务器或监控设备。


作者注:如果脚本执行日志有重复条目,请检查是否存在多个 startup 任务(如 boot_ack 与 boot-ack 重叠),只保留一个即可。

发布回复

请输入评论!
请输入你的名字