怎樣自定義Ubuntu Trigger規則
在Ubuntu系統中,自定義Trigger規則本質是通過事件監聽-條件判斷-動作執行的邏輯實現自動化任務。以下是幾種常見且實用的自定義方法,覆蓋不同場景需求:
inotify是Linux內核提供的文件系統事件監控機制,適合需要實時響應文件變化的場景(如文件創建、修改、刪除)。
inotify-tools
包,獲取inotifywait
命令(用于監控事件)。sudo apt-get install inotify-tools
/home/user/file_monitor.sh
),定義監控目錄、觸發條件及動作。示例腳本監控/home/user/documents
目錄,當創建包含“report”的文件時,輸出日志并發送郵件(需提前配置mail
命令):#!/bin/bash
WATCH_DIR="/home/user/documents"
TRIGGER_STRING="report"
LOG_FILE="/var/log/inotify_report.log"
inotifywait -m -r -e create --format '%w%f' "$WATCH_DIR" | while read FILE; do
if [[ "$FILE" == *"$TRIGGER_STRING"* ]]; then
echo "$(date): File $FILE created with trigger string." >> "$LOG_FILE"
echo "New report file detected: $FILE" | mail -s "Report Alert" user@example.com
fi
done
chmod +x /home/user/file_monitor.sh
nohup /home/user/file_monitor.sh &
此時,當指定目錄下創建符合條件的文件時,腳本會自動觸發預設動作。Systemd是Ubuntu的服務管理核心,可通過服務單元文件和觸發器文件實現系統啟動、服務狀態變化等事件的觸發。
/etc/systemd/system/my_trigger.service
:[Unit]
Description=Custom Trigger Service
After=network.target # 可選:設置依賴(如網絡就緒后執行)
[Service]
Type=oneshot # 一次性執行(非持續運行)
ExecStart=/home/user/custom_script.sh # 替換為實際腳本路徑
RemainAfterExit=yes # 標記服務為“active”狀態
start
操作),路徑為/etc/systemd/system/my_trigger.trigger
:[Trigger]
Operation=start # 觸發事件(如systemctl start my_trigger.trigger)
ExecStart=/bin/systemctl start my_trigger.service # 觸發后執行的操作
sudo systemctl daemon-reload # 重新加載Systemd配置
sudo systemctl enable my_trigger.trigger # 開機自啟觸發器
sudo systemctl start my_trigger.trigger # 手動觸發
此方法適合需要系統級集成的觸發場景(如服務啟動后自動備份)。cron是Ubuntu的定時任務工具,適合需要按固定周期(如每分鐘、每小時、每天)觸發任務的場景。
crontab -e
命令,添加一行定時規則。示例:每5分鐘執行一次/home/user/backup.sh
腳本:*/5 * * * * /home/user/backup.sh
chmod +x /home/user/backup.sh
cron會自動按設定時間觸發腳本,適合周期性維護任務(如日志清理、數據同步)。若需要復雜條件判斷(如數據庫查詢、網絡請求)或動態邏輯,可使用Python編寫觸發器腳本。
/home/user/python_trigger.py
,示例代碼監控文件大小,超過100MB時壓縮:import os
import time
from datetime import datetime
TARGET_DIR = "/home/user/large_files"
SIZE_LIMIT = 100 * 1024 * 1024 # 100MB
def compress_file(file_path):
os.system(f"tar -czf {file_path}.tar.gz {file_path}")
os.remove(file_path)
print(f"Compressed {file_path} at {datetime.now()}")
while True:
for root, _, files in os.walk(TARGET_DIR):
for file in files:
file_path = os.path.join(root, file)
if os.path.getsize(file_path) > SIZE_LIMIT:
compress_file(file_path)
time.sleep(60) # 每分鐘檢查一次
chmod +x /home/user/python_trigger.py
nohup python3 /home/user/python_trigger.py &
此方法適合需要定制化邏輯的場景(如結合API調用、數據庫操作的觸發)。若業務規則復雜(如多條件組合、動態規則更新),可使用Gengine(Go語言實現的規則引擎)構建自定義規則系統。
go get github.com/hyperjumptech/gengine
rules.drl
文件,編寫DSL規則(如“當用戶年齡大于18且狀態為active時,發送歡迎郵件”):package rules
import "github.com/hyperjumptech/gengine/builder"
import "fmt"
rule "WelcomeAdultUser" "Send welcome email to adult active users"
when
User.Age > 18 && User.Status == "active"
then
fmt.Println("Welcome email sent to user:", User.Name)
end
package main
import (
"fmt"
"github.com/hyperjumptech/gengine/builder"
"github.com/hyperjumptech/gengine/context"
)
type User struct {
Name string
Age int
Status string
}
func main() {
dataContext := context.NewDataContext()
dataContext.Add("User", &User{Name: "Alice", Age: 20, Status: "active"})
ruleBuilder := builder.NewRuleBuilder(dataContext)
drls := `
package rules
rule "WelcomeAdultUser" "Send welcome email to adult active users"
when
User.Age > 18 && User.Status == "active"
then
fmt.Println("Welcome email sent to user:", User.Name)
end
`
err := ruleBuilder.BuildRuleFromResource([]byte(drls))
if err != nil {
panic(err)
}
engine := ruleBuilder.GetEngine()
engine.FireRules()
}
此方法適合企業級復雜規則管理(如權限控制、業務流程自動化)。以上方法覆蓋了Ubuntu系統中從簡單到復雜的自定義Trigger需求,可根據具體場景選擇合適的方式。例如,實時文件監控選inotify,系統級事件選Systemd,周期性任務選cron,復雜邏輯選Python,企業級規則選Gengine。