對系統管理員或 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
ck_fs_space.sh 90 / /u01,第一個參數是門檻百分比,其後可接多個檔案系統。df -h 的結果寫入暫存檔作為郵件本文,方便收到警報後立刻判斷是哪個分區、還有哪些分區也接近門檻。部署時建議掛到 crontab,例如每 15 分鐘跑一次;若擔心郵件轟炸,可再加一個狀態檔記錄上次告警時間做節流。