Ubuntu系統監控觸發器與告警實現指南
在Ubuntu系統中,“觸發器”通常指系統狀態異常(如服務宕機、資源超閾值、文件變化等)的檢測條件,而“告警”是將異常信息通過指定渠道(郵件、短信、界面通知等)發送給管理員的過程。以下是常用監控與告警方法,覆蓋命令行、圖形界面及企業級工具:
命令行工具適合快速檢查系統狀態,通過腳本結合cron
可實現基礎告警:
實時查看日志(tail -f)
用于監控系統/應用日志的實時變化(如Nginx錯誤日志),當出現關鍵字(如“error”“failed”)時可手動觸發告警。
示例:tail -f /var/log/nginx/error.log | grep --line-buffered "error" | while read line; do echo "$(date): $line" | mail -s "Nginx Error Alert" admin@example.com; done
說明:實時讀取日志文件,匹配“error”關鍵字后發送郵件。
監控文件系統變化(inotifywait)
用于監控指定目錄/文件的創建、修改、刪除等事件(如/etc
目錄下的配置文件變更),觸發告警。
示例:inotifywait -m -e modify,create,delete /etc | while read path action file; do echo "$(date): File $file in $path was $action" | mail -s "File Change Alert" admin@example.com; done
說明:-m
表示持續監控,-e
指定事件類型。
定期檢查觸發器狀態(cron + 腳本)
通過cron
定時運行腳本,檢查系統指標(如CPU使用率、服務狀態),超過閾值則發送告警。
示例腳本(/usr/local/bin/check_trigger.sh
):
#!/bin/bash
CPU_THRESHOLD=80
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
if (( $(echo "$CPU_USAGE > $CPU_THRESHOLD" | bc -l) )); then
echo "$(date): CPU usage is ${CPU_USAGE}%, exceeding threshold ${CPU_THRESHOLD}%" | mail -s "CPU High Alert" admin@example.com
fi
添加cron
任務(每5分鐘運行一次):crontab -e
→ */5 * * * * /usr/local/bin/check_trigger.sh
說明:使用top
獲取CPU使用率,通過bc
計算是否超過閾值。
圖形界面工具適合日常運維,無需記憶命令,支持實時可視化:
Glances(跨平臺實時監控)
支持CPU、內存、磁盤、網絡、傳感器(溫度)等指標監控,閾值告警(如CPU超過80%變紅),可通過Web界面或客戶端遠程查看。
安裝與配置:
sudo apt install glances # Ubuntu 16.04+可直接安裝
sudo pip install glances # 舊版本可能需要pip安裝
啟動:glances
(默認終端運行),按c
排序CPU、m
排序內存,按q
退出;
遠程監控:服務器端啟動glances -s
(服務端),客戶端運行glances -c <服務器IP>
。
系統自帶監控工具(System Monitor)
Ubuntu自帶的圖形化工具,實時顯示CPU、內存、磁盤、網絡使用率,支持查看進程詳情,適合快速排查資源瓶頸。
啟動:點擊菜單 → “系統監視器”(或運行gnome-system-monitor
)。
Conky(高度可定制桌面監控)
在桌面直接顯示系統信息(如CPU、內存、磁盤空間、網絡流量),支持自定義腳本(如觸發器狀態),適合個性化需求。
安裝:sudo apt install conky
;
配置:編輯~/.conkyrc
文件,添加如下內容監控CPU:
${color white}CPU Usage:${color} $cpu% (${cpubar})
${color red}High CPU Alert${color} $execi 5 'if [ $(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk "{print 100 - \$1}") -gt 80 ]; then echo "CPU > 80%"; else echo ""; fi'
說明:$execi 5
表示每5秒執行一次腳本,$cpubar
顯示CPU使用率條形圖。
企業級工具支持分布式監控、自定義規則、多渠道告警,適合大規模服務器集群:
Prometheus + Alertmanager(時間序列監控+告警)
node_exporter
監控主機、nginx_exporter
監控Nginx),存儲為時間序列數據;sudo apt install prometheus
,編輯/etc/prometheus/prometheus.yml
添加監控目標(如node_exporter
的localhost:9100
);sudo apt install alertmanager
,編輯/etc/alertmanager/alertmanager.yml
配置郵件通知(SMTP信息);/etc/prometheus/rules.yml
):groups:
- name: node_rules
rules:
- alert: HighCPUUsage
expr: 100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 5m
labels:
severity: warning
annotations:
summary: "High CPU usage on {{ $labels.instance }}"
description: "CPU usage is above 80% for 5 minutes."
sudo systemctl restart prometheus alertmanager
。Zabbix(企業級綜合監控)
支持服務器、網絡設備、應用的全面監控,提供Web界面配置觸發器(如“Nginx服務停止”“磁盤空間剩余10%以下”),支持自動修復(如重啟服務)。
安裝步驟:
sudo apt install zabbix-server-mysql zabbix-frontend-php zabbix-apache-conf zabbix-agent
;http://<服務器IP>/zabbix
),完成初始化配置(如添加主機、配置監控項);Nagios(經典監控系統)
適合傳統運維場景,支持服務可用性監控(如HTTP、FTP、SSH),通過插件擴展功能(如check_disk
檢查磁盤空間、check_load
檢查負載)。
安裝步驟:
sudo apt install nagios3 nagios-plugins
;/etc/nagios3/conf.d/localhost_nagios2.cfg
,添加服務檢查(如HTTP檢查):define service {
use generic-service
host_name localhost
service_description HTTP
check_command check_http
}
/etc/nagios3/contacts_nagios2.cfg
,添加聯系人郵箱,配置通知命令(如notify-by-email
)。對于特殊觸發器(如“某文件內容包含特定關鍵字”“數據庫連接失敗”),可通過Shell/Python腳本實現,結合cron
或systemd
定時運行,觸發告警。
示例(Python腳本監控文件關鍵字):
#!/usr/bin/env python3
import smtplib
from email.mime.text import MIMEText
import time
def send_alert(message):
sender = 'alert@example.com'
receiver = 'admin@example.com'
msg = MIMEText(message)
msg['Subject'] = 'Trigger Alert'
msg['From'] = sender
msg['To'] = receiver
with smtplib.SMTP('smtp.example.com', 587) as server:
server.starttls()
server.login('alert', 'password')
server.sendmail(sender, receiver, msg.as_string())
def check_file():
with open('/path/to/file.log', 'r') as f:
content = f.read()
if 'ERROR' in content:
send_alert('Error found in file!')
while True:
check_file()
time.sleep(60) # 每分鐘檢查一次
說明:腳本每分鐘檢查文件是否包含“ERROR”,若存在則發送郵件告警。
以上方法覆蓋了從基礎到高級的監控與告警需求,可根據系統規模、技術棧、預算選擇合適的方案。例如:
Glances
+ cron
腳本;Prometheus
+ Alertmanager
;Zabbix
或Nagios
。