0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【業務自動化】Linuxでdf -kのディスク使用状況を週1メール送信して自動化した(cron+sh+sendmail)

Posted at

※紹介するディレクトリや名前などは例なので自分用に置き換えてください

背景と目的

システム運用の現場で、「サーバの空き容量チェックを毎日にしてるけど、手動で毎日やるのは面倒だな…」と思っていました。
そこで今回は、Linuxのdf -kを毎朝自動取得し、その結果をメールで送信する仕組みを作ってみました。

cron+sh+sendmailの組み合わせで、ログの生成とメール送信まで完全自動化しています。

ディレクトリ構成と処理の概要

/home/username/scripts/
              ├── df_report.sh        ← cronで実行されるsh
              ├── send_mail.sh
              └── logs/
              └── df_report.log     ← 日付付きで保存されるdf結果ログ

df_report.sh の中身

取得した日付とディスク使用量がdf_report.logに記載される

df_report.sh
#!/bin/bash

LOG_DIR="/home/username/logs"

LOGFILE="$LOG_DIR/df_report.log"

# ログ追記(ログは追記で更新される
{
  echo "=== $(date '+%Y-%m-%d %H:%M:%S') ==="
  df -k
  echo ""
} >> "$LOGFILE"

send_mail.sh

df_report.shで作成したdf_report.logを添付メールとして送信

df_report.sh
#!/bin/bash

TO="someone@example.com"
FROM="yourname@example.com"
SUBJECT="XXXサーバーのディスクログ"
LOGFILE="/home/username/logs/df_report.log"
BOUNDARY="====$(date +%s)===="

# ログファイルが存在すれば送信
if [ -f "$LOGFILE" ]; then
  (
    echo "To: $TO"
    echo "From: $FROM"
    echo "Subject: $SUBJECT"
    echo "MIME-Version: 1.0"
    echo "Content-Type: multipart/mixed; boundary=\"$BOUNDARY\""
    echo
    echo "--$BOUNDARY"
    echo "Content-Type: text/plain; charset=UTF-8"
    echo
    echo "ログを添付いたします。"
    echo
    echo "--$BOUNDARY"
    echo "Content-Type: text/plain; name=\"$(basename "$LOGFILE")\""
    echo "Content-Transfer-Encoding: base64"
    echo "Content-Disposition: attachment; filename=\"$(basename "$LOGFILE")\""
    echo
    base64 "$LOGFILE"
    echo "--$BOUNDARY--"
  ) | /usr/sbin/sendmail -f "$FROM" -t
else
  echo "[INFO] ログファイルが存在しないため送信スキップ:$LOGFILE"
fi

shを使用するには権限をつける(例)

chmod +x df_report.sh
chmod +x send_mail.sh

cronの設定(例)

# 月~金の朝9時にdf_report.logにdf -kの結果を記載
0 9 * * 1-5 /home/username/scripts/df_report.sh

# 月曜日の朝8時にdf_report.logを添付メールとして送信
0 8 * * 1 /home/username/scripts/send_mail.sh

まとめ

ほんのちょっとのシェルスクリプトとcron設定で、日常の確認作業を自動化できました。
小さなことですが少しの楽の積み重ねが大事だと思います

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?