温馨提示×

ubuntu触发器设置步骤是什么

小樊
44
2026-01-11 16:23:42
栏目: 智能运维

Ubuntu 触发器的常见实现与步骤

在 Ubuntu 中,“触发器”通常对应由事件驱动的自动化:按时间触发、按系统事件触发、按文件变化触发、按设备插拔触发等。下面按场景给出可直接执行的步骤与示例。

一 按时间触发

  • 使用 Cron(最简便)

    1. 打开当前用户的定时表:crontab -e
    2. 添加规则(五个时间字段:分 时 日 月 周;@reboot 表示开机触发):
      • 每天 06:00 执行:0 6 * * * /path/to/script.sh
      • 5 分钟执行:*/5 * * * * /path/to/script.sh
      • 开机执行:@reboot /path/to/script.sh
    3. 查看/删除:crontab -l / crontab -r
    4. 确保 cron 服务运行:sudo systemctl status cron(如未运行:sudo systemctl start cron && sudo systemctl enable cron)
  • 使用 Systemd Timer(更现代,便于日志与依赖管理)

    1. 创建一次性服务单元:/etc/systemd/system/my_trigger.service
      [Unit]
      Description=My Trigger Service
      [Service]
      Type=oneshot
      ExecStart=/path/to/script.sh
    2. 创建定时器单元:/etc/systemd/system/my_trigger.timer
      [Unit]
      Description=Run my_trigger every 5 minutes
      [Timer]
      OnBootSec=5min
      OnUnitActiveSec=5min
      Persistent=true
      [Install]
      WantedBy=timers.target
    3. 启用并启动:sudo systemctl daemon-reload && sudo systemctl enable --now my_trigger.timer
    4. 查看定时器状态:systemctl list-timers

二 按文件系统事件触发

  • 使用 inotifywait 实时监听目录/文件变化
    1. 安装工具:sudo apt-get install inotify-tools
    2. 编写监控脚本 monitor.sh:
      #!/usr/bin/env bash
      WATCH_DIR=“/path/to/watch”
      inotifywait -m -r -e create,modify,delete --format ‘%w%f’ “$WATCH_DIR” | while IFS= read -r file; do
      /path/to/your_action.sh “$file”
      done
    3. 赋权并后台运行:chmod +x monitor.sh && nohup ./monitor.sh &
    4. 建议将日志输出到文件以便排查(>> /var/log/monitor.log 2>&1)

三 按系统事件或设备插拔触发

  • Systemd 服务随系统事件启动(如开机)

    1. 创建服务:/etc/systemd/system/my_service.service
      [Unit]
      Description=My Service
      After=network.target
      [Service]
      ExecStart=/path/to/script.sh
      Restart=on-failure
      [Install]
      WantedBy=multi-user.target
    2. 启用:sudo systemctl enable --now my_service.service
    3. 说明:也可用 systemd 的 OnCalendar/OnBootSec 等实现时间/启动类触发(见上一节)
  • Udev 设备插拔触发(如插入指定 USB 设备时执行脚本)

    1. 新建规则:/etc/udev/rules.d/99-mydevice.rules
      ACTION==“add”, SUBSYSTEM==“usb”, ATTR{idVendor}==“1234”, ATTR{idProduct}==“5678”, RUN+=“/path/to/script.sh”
    2. 重新加载并触发:sudo udevadm control --reload-rules && sudo udevadm trigger
    3. 提示:idVendor/idProduct 可用 lsusb 获取

四 实践建议与排错要点

  • 给脚本加可执行权限:chmod +x /path/to/script.sh;脚本首行使用 #!/usr/bin/env bash;涉及网络/权限的操作按需使用 sudo
  • 统一日志输出与重定向:在脚本或 crontab/systemd 中加入 >> /var/log/xxx.log 2>&1,便于排查。
  • 前台调试 inotify 脚本(先去掉 nohup/&),确认事件能被捕获后再后台常驻。
  • 使用 Systemd 时记得执行 daemon-reload,并通过 systemctl status/enable/start 管理单元与定时器。
  • 避免重复触发:在 inotify 循环内做好去抖/锁文件;在 cron 中避免重叠执行(可用 flock)。

0