業務用エアコン関連の技術情報、エラーコード、環境問題対策に関する別サイト「エアコンの安全な修理・適切なフロン回収」

AlmaLinux9.8 : Logwatch , DNS更新 , ディスク使用率チェックスクリプト

Logwatch

①インストール

# dnf -y install logwatch

②設定ファイルの編集

# cat /usr/share/logwatch/default.conf/logwatch.conf >> /etc/logwatch/conf/logwatch.conf

# vi /etc/logwatch/conf/logwatch.conf

51 行目 : コメント
#MailTo = root

52行目 : 追加
MailTo = [メールアドレス]

84行目あたりログ通知の詳細度を設定
#Detail = Low
Detail = High

③Logwatch のレポートを出力

# logwatch --output stdout

下記のようなメッセージが出ます

 ################### Logwatch 7.5.5 (01/22/21) ####################
        Processing Initiated: Fri Jul  3 15:24:25 2026
        Date Range Processed: yesterday
                              ( 2026-Jul-02 )
                              Period is day.
        Detail Level of Output: 10
        Type of Output/Format: stdout / text
        Logfiles for Host: Lepard
 ##################################################################

 --------------------- Kernel Audit Begin ------------------------

  Number of audit daemon starts: 1

  Number of audit initializations: 1

 **Unmatched Entries**
    auditd[760]: audit dispatcher initialized with q_depth=2000 and 1 active plugins: 1 Time(s)

 ---------------------- Kernel Audit End -------------------------

------------------------------------------(Omitted)---------------------------------------------------

 --------------------- Disk Space Begin ------------------------

 Filesystem                  Size  Used Avail Use% Mounted on
 /dev/mapper/almalinux-root   36G  7.1G   28G  21% /
 /dev/nvme0n1p1              960M  462M  499M  49% /boot


 ---------------------- Disk Space End -------------------------


 --------------------- lm_sensors output Begin ------------------------

 No sensors found!
 Make sure you loaded all the kernel drivers you need.
 Try sensors-detect to find out which these are.

 ---------------------- lm_sensors output End -------------------------


 ###################### Logwatch End #########################

④設定したアドレスにレポートが届くかテストを行います。上記の様なログレポートメールが届いているか確認

# /etc/cron.daily/0logwatch

DNS更新

ネットが切断されたり、ルーターが切断再起動したときにおこるグローバルIPの変更の度に、ダイナミックDNSにアクセスしグローバルIPが変更されたことを知らせなくてはいけません。

専用のpythonファイルを作成しCronで定期実行します
今回はValudomainでのDNS設定です

# cd /var/www/system
# vi ddnsset.py

ddnsset.pyの内容

#setddns.py
import requests
import ipaddress
from datetime import datetime
from pathlib import Path

# SETTING DATA
MY_DOMAIN = "example.jp"  ←自ドメイン
MY_PASS = "xxxxxxxxxx" ←パスワード
MY_HOSTNAME = "xxxx" ←ホスト名
OUT_FILE = Path("/tmp/ipadress") ←IPアドレス記録ファイル

def time_msg():
    now = datetime.now()
    return now.strftime("%Y/%m/%d %H:%M:%S")

def is_valid_ip(ip_str):
    try:
        ipaddress.ip_address(ip_str)
        return True
    except ValueError:
        return False

def main():
    # Check Global IP Address
    url_get_ip = "https://dyn.value-domain.com/cgi-bin/dyn.fcg?ip"
    try:
        response = requests.get(url_get_ip, timeout=10)
        response.raise_for_status()
        current_ip = response.text.strip()
    except requests.RequestException as e:
        print(f"{time_msg()} Failed to get IP: {e}")
        return

    # IP check
    mssg = time_msg()
    if not current_ip:
        print(f"{mssg} invalid IP NULL")
        return

    if not is_valid_ip(current_ip):
        print(f"{mssg} invalid IP={current_ip}")
        return

    # Read previous IP
    previous_ip = ""
    if OUT_FILE.exists():
        with open(OUT_FILE, "r") as f:
            previous_ip = f.read().strip()

    if current_ip == previous_ip:
        print(f"{time_msg()} no change IP={current_ip}")
        return
    else:
        print(f"change IP from {previous_ip} to {current_ip}")

    # Update DDNS
    mssg = time_msg()
    print(f"{mssg} access to value-domain")

    url_set_ddns = (
        f"https://dyn.value-domain.com/cgi-bin/dyn.fcg?"
        f"d={MY_DOMAIN}&p={MY_PASS}&h={MY_HOSTNAME}"
    )

    try:
        response = requests.get(url_set_ddns, timeout=10)
        response.raise_for_status()
        # 改行をスペースに変換し、連続するスペースを1つにまとめる
        result = ' '.join(response.text.strip().split())
    except requests.RequestException as e:
        print(f"{time_msg()} Failed to update DDNS: {e}")
        return

    mssg = time_msg()
    print(f"{mssg} {MY_HOSTNAME}.{MY_DOMAIN} {result} IP={current_ip}")

    # DDNS更新が成功した場合のみIPを保存
    if "status=0" in result:
        with open(OUT_FILE, "w") as f:
            f.write(current_ip)
        print(f"{mssg} Successfully saved new IP: {current_ip}")
    else:
        print(f"{mssg} DDNS update failed, IP not saved")

if __name__ == "__main__":
    main()

IPアドレス記録ファイル作成

# touch /tmp/ipadress

定期的に実行

# crontab -e

* 00 * * * /usr/bin/python3 /var/www/system/ddnsset.py >> /var/log/ddns_updater.log 2>&1

ディスク使用率チェックスクリプト

1. スクリプト作成

# cd /var/www/system
# vi disk_capacity_check.sh

disk_capacity_check.shの内容

#!/bin/bash

#通知先メールアドレス指定
MAIL="<your mailaddress>"

DVAL=`/bin/df / | /usr/bin/tail -1 | /bin/sed 's/^.* \([0-9]*\)%.*$/\1/'`

if [ $DVAL -gt 80 ]; then
echo "Disk usage alert: $DVAL %" | mail -s "Disk Space Alert in `hostname`" $MAIL
fi
# chmod 700 disk_capacity_check.sh

2. 実行確認

①現在の使用率を確認

# df -h

次のように表示される

Filesystem                  Size  Used Avail Use% Mounted on
devtmpfs                    1.8G     0  1.8G   0% /dev
tmpfs                       1.8G     0  1.8G   0% /dev/shm
tmpfs                       725M  9.4M  716M   2% /run
/dev/mapper/almalinux-root   36G  7.1G   28G  21% /
/dev/loop0                  128K  128K     0 100% /var/lib/snapd/snap/hello-world/29
/dev/nvme0n1p1              960M  462M  499M  49% /boot
/dev/loop3                   74M   74M     0 100% /var/lib/snapd/snap/certbot/5603
/dev/loop1                   50M   50M     0 100% /var/lib/snapd/snap/snapd/26865
/dev/loop2                  106M  106M     0 100% /var/lib/snapd/snap/core/17292
/dev/loop4                   67M   67M     0 100% /var/lib/snapd/snap/core24/1643
tmpfs                       363M  8.0K  363M   1% /run/user/1000

②使用率80%以上になるようダミーファイルを作成(例ではdummyfile という名前で25G程度)

# dd if=/dev/zero of=dummyfile bs=1M count=25000

③再度確認
下記を実行して80%以上になっていることを確認

# df -h

④ディスク容量チェックスクリプトを実行

# /var/www/system/disk_capacity_check.sh

設定したメールアドレスに本文の内容として「Disk usage alert: 90 %」のように記載のメールが届きます

⑤作成した「dummyfile」を削除

# rm dummyfile

⑥定期実行設定

# crontab -e
下記追加
30 2 * * * /var/www/system/disk_capacity_check.sh