在Ubuntu系統中,觸發器(Trigger)的核心作用是在特定事件(如系統啟動、文件變化、定時到達)或時間條件滿足時,自動執行預定義的操作(如運行腳本、啟動服務、發送通知)。以下是幾種主流的實現方式,覆蓋不同場景需求:
Systemd是Ubuntu的默認服務管理工具,其服務單元(.service)用于定義具體操作,定時器單元(.timer)用于設置觸發條件(時間或事件),適合需要精準調度或系統級集成的場景(如系統啟動后備份、每日定時清理)。
/etc/systemd/system/
下創建.service
文件(如backup.service
),內容示例如下:[Unit]
Description=Daily Document Backup
[Service]
Type=oneshot # 一次性執行(非持續運行)
ExecStart=/usr/local/bin/backup_script.sh # 替換為實際腳本路徑
/etc/systemd/system/
下創建.timer
文件(如backup.timer
),內容示例如下:[Unit]
Description=Run backup daily at 2 AM
[Timer]
OnCalendar=*-*-* 02:00:00 # 每天凌晨2點觸發
Persistent=true # 若錯過時間,下次啟動時補執行
[Install]
WantedBy=timers.target # 關聯到系統定時器目標
sudo systemctl daemon-reload # 重新加載Systemd配置
sudo systemctl enable --now backup.timer # 開機自啟并立即啟動
通過systemctl list-timers
可查看定時器狀態,確認是否生效。inotify是Linux內核提供的文件系統事件監控機制,可實時響應文件的創建、修改、刪除、移動等事件,適合需要即時自動化的場景(如文件上傳后自動處理、日志更新后發送通知)。
sudo apt-get update && sudo apt-get install inotify-tools
/usr/local/bin/file_monitor.sh
),內容示例如下:#!/bin/bash
WATCH_DIR="/path/to/your/directory" # 監控的目錄
TRIGGER_STRING="report" # 觸發條件(如文件名包含"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 /usr/local/bin/file_monitor.sh
nohup /usr/local/bin/file_monitor.sh & # 后臺運行(避免終端關閉后停止)
此時,當指定目錄下創建符合條件的文件時,腳本會自動觸發預設動作。cron是Ubuntu傳統的定時任務工具,適合按固定周期(如每分鐘、每小時、每天、每周)執行任務的場景(如日志清理、數據同步、報表生成)。
crontab -e
cron
語法(* * * * * command
)添加任務,示例如下:
0 3 * * * /usr/local/bin/backup_script.sh
*/5 * * * * df -h >> /var/log/disk_usage.log
grep CRON /var/log/syslog
可查看cron日志,確認任務是否執行。/usr/bin/df
而非df
)。對于復雜觸發邏輯(如網絡請求、數據庫查詢、多步驟操作),可使用Python編寫靈活的觸發器腳本,結合time.sleep()
實現輪詢或threading
實現異步監控。
import time
import subprocess
LOG_FILE = "/var/log/python_trigger.log"
def check_logs():
result = subprocess.run(['grep', 'error', '/var/log/syslog'],
capture_output=True, text=True)
if result.stdout:
with open(LOG_FILE, 'a') as f:
f.write(f"[{time.ctime()}] Error found in syslog:\n{result.stdout}\n")
if __name__ == "__main__":
while True:
check_logs()
time.sleep(60) # 每分鐘檢查一次
chmod +x /path/to/your_script.py
nohup /path/to/your_script.py &
此時,腳本會持續運行,當系統日志中出現“error”時,自動記錄到指定文件。若偏好圖形界面,可使用Gnome Scheduler(GNOME桌面環境)或KDE System Guard(KDE桌面環境)等工具,通過可視化界面安排任務(如定時運行腳本、啟動應用程序),無需手動編輯配置文件。
sudo apt-get install gnome-schedule
/path/to/script.sh
)。以上方法覆蓋了Ubuntu系統中系統級調度、實時事件響應、周期性任務、復雜邏輯及新手友好等不同場景的自動化需求。選擇時需根據任務的具體要求(如觸發條件、執行頻率、復雜度)進行匹配。