Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Linux 下監控磁碟可用空間的 Shell 腳本範例

對系統管理員或 DBA 來說,監控磁碟剩餘空間是必備的日常工作。下面這份腳本以門檻值為判斷依據,一旦某個分區的使用率超標,就寄出警報郵件,並附上當時的 df 輸出。

腳本內容

#!/bin/bash
# ----------------------------------------------------------------------------+
#  CHECK FILE SYSTEM SPACE BY THRESHOLD
#  Filename: ck_fs_space.sh
#  Desc:     檢查檔案系統使用率,超過門檻即寄發郵件警報
#            以 crontab 部署,例如每 15 分鐘執行一次
#  Usage:    ./ck_fs_space.sh <percent> </filesystem [/filesystem2]>
# ----------------------------------------------------------------------------+

# Set environment here
if [ -f ~/.bash_profile ]; then
    . ~/.bash_profile
fi

export host=`hostname`
export mail_dir=/users/robin/dba_scripts/sendEmail-v1.56
export mail_list='Robinson.cheng@example.com'
export mail_fm='oracle@example.com'
tmpfile=/tmp/ck_fs_space.txt
alert=n

# Check the parameter
max=$1
if [ ! ${2} ]; then
    echo "No filesystems specified."
    echo "Usage: ck_fs_space.sh 90 / /u01"
    exit 1
fi

# Start to check the disk space
while [ "${2}" ]
do
    percent=`df -P ${2} | tail -1 | awk '{print $5 }' | cut -d'%' -f1`
    if [ "${percent}" -ge "${max}" ]; then
        alert=y
        break
    fi
    shift
done

# 若有分區超出門檻,寄出附帶 df 輸出的郵件
if [ ! "${alert}" = 'n' ]; then
    df -h > $tmpfile
    mail_sub="Disk usage beyond the threshold ${max} on ${host}."
    $mail_dir/sendEmail -u ${mail_sub} -f $mail_fm -t $mail_list \
        -o message-file=${tmpfile}
fi

exit

說明

  1. 腳本依賴 sendEmail 工具來發送郵件。
  2. 使用方式為 ck_fs_space.sh 90 / /u01,第一個參數是門檻百分比,其後可接多個檔案系統。
  3. 用一個 while 迴圈配合 shift 逐個檢查所有指定分區,任一超標即跳出。
  4. 超標時把 df -h 的結果寫入暫存檔作為郵件本文,方便收到警報後立刻判斷是哪個分區、還有哪些分區也接近門檻。

部署時建議掛到 crontab,例如每 15 分鐘跑一次;若擔心郵件轟炸,可再加一個狀態檔記錄上次告警時間做節流。

Copyright © Linux教程網 All Rights Reserved