2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【bash】ディスク容量をチェックして閾値を超えたらアラートメールを送信

Last updated at Posted at 2025-06-14

はじめに

過去に作ったものですが保守のために公開しておきます

これは何ですか

ディスク容量をチェックしてアラートメールを送信するスクリプト

目的

ディスクフルの予兆を事前に察知し障害を回避するため

誰が使う

サーバー管理担当

動作環境

AlmaLinux 9.5
bash 5.1.8

Raspbian 10
bash 5.0.3

コード

dfml.sh

#!/bin/bash
# alart mail for disk usage
export LANG=C

# Thresholds LOW MIDDLE HIGH (%)
TL=70
TM=80
TH=90

# Log Drectory, Filename and Number of rotation
LOGD="/opt/tools/log"
LOGF="${LOGD}/dfml1.log"
ROT=5

# Mail destination address
ADDR="your_account@your.domain.com"

# Rotate logs
for ((i=${ROT}; i > 1; i--)); do
    TRG="${LOGD}/dfml${i}.log"
    SRC="${LOGD}/dfml$((i - 1)).log"
    if [ -e "${SRC}" ]; then
        cp -p "${SRC}" "${TRG}"
    fi
done

# Header
echo "$(uname -n) $(date '+%Y-%m-%d %H:%M:%S') Usage file systems (Sev1>${TH}%, Sev2>${TM}%, Sev3>${TL}%)" > "${LOGF}"

# Check Disk usage, except specified directories, output log
maxlv=$(df -hP | awk -v logfile="${LOGF}" -v tl=$TL -v tm=$TM -v th=$TH '
$6 !~ "^/$" &&
$6 !~ "^/boot" &&
$6 !~ "^/opt/except/dir" {
  us = substr($5, 1, length($5) - 1) + 0;
  if (us > tl) {
    print >> logfile;
    lv = 1;
    if (us > tm) { lv = 2 }
    if (us > th) { lv = 3 }
    if (lv > mx) { mx = lv }
  }
}
END { print (mx > 0 ? mx : 0) }
')

# mail Subject line
SBJ="Warning! disk overused [Sev$((4 - maxlv))]"

# Output log
cat "${LOGF}"

# Send mail if needed
if [ "$(wc -l < "${LOGF}")" -gt 1 ]; then
    echo "Sending email to ${ADDR}..."
    sudo mail -r "foo" -s "${SBJ}" "${ADDR}" < "${LOGF}"
    echo "----" >> "${LOGF}"
    df -hP >> "${LOGF}"
fi

使い方

手動で

chmod +x dfml.sh
./dfml.sh

cronで自動実行

30 07 * * * /your/path/dfml.sh > /dev/null 2>&1

おわりに

夜中に電話で起こされて障害対応
⇒エラーはログの書き込み失敗
⇒ディスク容量を見ると残り僅か

などというケースはできるだけ避けたいものです。
事前にディスク残量を調べておくとよいのでは?
ということで
毎朝始業前に自動チェックしてアラートメールが来たら勤務時間中に対応すると、
楽になるはず

お役に立てば幸いです

参考リンク

df manual

mail manual

github.com/kojimura/shell/blob/main/dfml.sh

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?