Ubuntu Trigger 设置指南
Ubuntu Trigger 是一款用于自动化任务调度的工具,支持基于时间规则(如每天凌晨2点)、系统事件(如系统启动、用户登录)或文件系统变化(如文件创建/修改)触发脚本或命令执行,帮助提升系统管理效率。
在设置触发器前,需先安装工具包。打开终端,依次执行以下命令更新软件包列表并安装:
sudo apt update
sudo apt install ubuntu-trigger
通过ubuntu-trigger create命令创建触发器,需指定名称(--name)、执行的命令/脚本路径(--command),以及触发条件(时间/事件)。
ubuntu-trigger create --name "DailyBackup" --command "/home/user/backup.sh" --every "0 2 * * *"
其中--every参数采用cron语法(分 时 日 月 星期),0 2 * * *表示每天2点整。ubuntu-trigger create --name "StartupCleanup" --command "/home/user/cleanup.sh" --on "startup"
--on参数指定系统事件(如startup表示启动、shutdown表示关机、login表示用户登录)。使用ubuntu-trigger list命令列出所有已创建的触发器,包括名称、状态、触发条件等信息:
ubuntu-trigger list
通过ubuntu-trigger edit命令编辑已有触发器,可修改名称、命令或触发条件:
ubuntu-trigger edit "DailyBackup"
执行后会进入编辑界面,调整参数后保存即可。
使用ubuntu-trigger delete命令删除不再需要的触发器:
ubuntu-trigger delete "StartupCleanup"
对于复杂触发逻辑(如多条件组合),可通过YAML配置文件定义触发器,再用triggertool命令创建。
示例配置文件custom-trigger.yaml:
trigger:
name: "FileModifiedAlert"
description: "Trigger when specific file is modified"
rules:
- id: "rule1"
description: "Monitor /etc/config file changes"
condition:
type: "file"
path: "/etc/config"
event: "modified" # 监听文件修改事件
action:
type: "shell"
command: "echo 'Config file modified!' | mail -s 'Alert' admin@example.com"
执行以下命令创建触发器:
triggertool create --config custom-trigger.yaml
若需实时监控文件/目录变化(如新增、修改、删除),可使用inotify-tools工具包。
sudo apt install inotify-tools
monitor.sh:#!/bin/bash
WATCH_DIR="/path/to/watch" # 监控的目录
TARGET_FILE="important.txt" # 目标文件名
inotifywait -m -e create --format '%w%f' "$WATCH_DIR" | while read FILE
do
if [[ "$FILE" == *"$TARGET_FILE" ]]; then
echo "File $TARGET_FILE created in $WATCH_DIR" | mail -s "New File Alert" admin@example.com
fi
done
chmod +x monitor.sh
./monitor.sh
chmod +x /path/to/script.sh设置。PATH),需在脚本开头声明或在触发器配置中指定。ubuntu-trigger status <触发器名称>查看触发器执行状态,或结合journalctl查看系统日志排查问题。通过以上步骤,可灵活设置Ubuntu Trigger,实现系统任务的自动化执行,适用于备份、监控、清理等多种场景。