ubuntu如何通過觸發器監控系統狀態

ubuntu系統中,你可以使用inotify-tools來監控文件系統的變化,或者使用systemd的watchdog功能來監控系統狀態。以下是兩種方法的詳細步驟:

方法一:使用inotify-tools監控文件系統變化

  1. 安裝inotify-tools

    sudo apt update sudo apt install inotify-tools 
  2. 創建一個腳本來監控特定目錄或文件: 例如,創建一個腳本monitor.sh來監控/etc目錄的變化:

    #!/bin/bash inotifywait -m -r -e modify,attrib,close_write,move,create,delete /etc | while read path action file; do     echo "The file '<span>$file' appeared in directory '$path' via '$action'"</span> done 
  3. 賦予腳本執行權限

    chmod  x monitor.sh 
  4. 運行腳本

    ./monitor.sh 

方法二:使用systemd的watchdog功能監控系統狀態

  1. 創建一個systemd服務單元文件: 例如,創建一個服務單元文件/etc/systemd/system/my-watchdog.service:

    [Unit] Description=My System Watchdog Service  [Service] ExecStart=/usr/local/bin/my-watchdog.sh Restart=always RestartSec=5  [Install] WantedBy=multi-user.target 
  2. 創建一個腳本來監控系統狀態: 例如,創建一個腳本/usr/local/bin/my-watchdog.sh來監控CPU使用率:

    #!/bin/bash while true; do     cpu_usage=$(top -bn1 | grep load | awk '{printf("%.2f"), $(NF-2)}')     if (( $(echo "$cpu_usage > 80" | bc) )); then         echo "High CPU usage detected: <span>$cpu_usage%"</span>         # 在這里添加你想要執行的操作,例如發送郵件或重啟服務     fi     sleep 60 done 
  3. 賦予腳本執行權限

    chmod  x /usr/local/bin/my-watchdog.sh 
  4. 重新加載systemd配置

    sudo systemctl daemon-reload 
  5. 啟動并啟用服務

    sudo systemctl start my-watchdog.service sudo systemctl enable my-watchdog.service 

通過這兩種方法,你可以有效地監控Ubuntu系統的狀態和文件系統的變化。選擇哪種方法取決于你的具體需求和應用場景。

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享