Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 磁碟空間監控告警腳本(支援多掛載點、郵件通知)

編輯:Linux 教學

腳本功能

  • 檢查所有非虛擬掛載點(排除 tmpfs、devtmpfs、proc、sysfs 等)。
  • 可配置閾值(預設 95%),超標發送郵件告警。
  • 郵件含:伺服器 IP、掛載點、使用率、可用空間、時間戳。
  • 支援多收件人、抄送、自定義發件人。
  • 可納入 cron 定時執行(建議每 5-10 分鐘)。

完整腳本

#!/bin/bash
# disk_monitor.sh
# 依賴: mailx/postfix, df, awk, ip

THRESHOLD=95
EMAIL_TO="ops@example.com"
EMAIL_CC="manager@example.com"
EMAIL_FROM="disk-monitor@$(hostname -f)"
SUBJECT_PREFIX="[DISK ALERT]"

get_main_ip() {
    ip -o -4 addr show scope global | awk '{print $4}' | cut -d/ -f1 | head -1
}

send_alert() {
    local subject="$1"
    local body="$2"
    printf "%s\n" "$body" | mail -s "$subject" -r "$EMAIL_FROM" -c "$EMAIL_CC" "$EMAIL_TO"
}

# 解析 df -P 輸出(POSIX 格式,固定欄位)
df -P -x tmpfs -x devtmpfs -x proc -x sysfs -x cgroup -x overlay | tail -n +2 | while read -r fs blocks used avail capacity mount; do
    usage=${capacity%\%}
    if (( usage >= THRESHOLD )); then
        ip=$(get_main_ip)
        body="Server: $(hostname) ($ip)
Mount: $mount
Filesystem: $fs
Usage: ${usage}%
Used: $((used * 1024 / 1024 / 1024)) GB
Available: $((avail * 1024 / 1024 / 1024)) GB
Time: $(date '+%Y-%m-%d %H:%M:%S')
Action required: Clean up or expand storage immediately."
        send_alert "${SUBJECT_PREFIX} $(hostname): $mount at ${usage}%" "$body"
    fi
done

部署步驟

  1. 存為 /usr/local/sbin/disk_monitor.sh,chmod +x。
  2. 確保郵件系統就緒:yum install -y mailx postfix && systemctl enable --now postfix。
  3. 加入 crontab:
*/5 * * * * /usr/local/sbin/disk_monitor.sh >/dev/null 2>&1

進階增強

總結

這支 <30 行腳本解決了「磁碟滿導致服務宕機」的核心痛點。生產環境建議:告警分級(80% 警告、90% 嚴重、95% 緊急)、去抖動(狀態變化才通知)、多渠道推送、納入監控體系 做長期容量規劃。

Copyright © Windows教程網 All Rights Reserved
需求實現
避免重複告警記錄上次告警狀態檔 /var/tmp/disk_alert_$mount,僅在狀態變化(正常→告警、告警→正常)發送
支援 inode 耗盡告警改用 df -Pi 解析 IUse%
推送至企業微信/釘鈉/Slack替換 send_alert 為 curl -X POST $WEBHOOK -d '{"text":"..."}'
圖形化趨勢配合 Node Exporter + Prometheus + Grafana 監控 node_filesystem_avail_bytes/node_filesystem_size_bytes
自動清理告警腳本中集成 find /var/log -name '*.log' -mtime +30 -delete 等清理邏輯(極謹慎)