システムの再起動が必要な場合に Ubuntu サーバーにメールを送信させる

システムの再起動が必要な場合に Ubuntu サーバーにメールを送信させる

Ubuntuサーバー20.04 LTSは、サーバーの再起動を必要とするアップデートがインストールされたときに、特定のメールアドレスにメールを送信できる可能性がありますか?

たとえば、/var/run/reboot-required.pkgs ファイルが存在する場合、管理者に再起動できるようにメールが送信されますか?

Googleでいろいろ調べたのですが、これに関する簡単なチュートリアルが見つかりません

答え1

/etc/apt/apt.conf.d/50unattended-upgradesを試してください

// Send email to this address for problems or packages upgrades
// If empty or unset then no email is sent, make sure that you
// have a working mail setup on your system. A package that provides
// 'mailx' must be installed. E.g. "[email protected]"
Unattended-Upgrade::Mail "[email protected]";

// Set this value to "true" to get emails only on errors. Default
// is to always send a mail if Unattended-Upgrade::Mail is set
Unattended-Upgrade::MailOnlyOnError "false";

それは実は簡単な部分です。次に、電子メールをサーバーからあなたに送信するための軽量の郵便システムを設定する必要があります。

その方法の 1 つを以下に示します。

sudo apt install msmtp msmtp-mta bsd-mailx

設定ファイル:/root/.msmtprc

account        your_label_here
host           smtp.example.com
port           465
from           root@your_machine.your_domain
user           [email protected] (your email)
password       your_smtp_password
auth           on
tls            on
tls_starttls   off
tls_certcheck  off
logfile        /root/.msmtp.log
account default : your_label_here

テストコマンド:

echo "This is the email body" > /tmp/body.txt && sudo mailx -s "This is the subject" [email protected] < /tmp/body.txt; rm /tmp/body.txt

答え2

ありがとうございます。チュートリアルに従って、cronジョブを編集しました。実際、ユーザーrootとして、設定ファイル/root/.msmtprcを作成しました。

account        your_label_here
host           smtp.example.com
port           465
from           root@your_machine.your_domain
user           [email protected] (your email)
password       your_smtp_password
auth           on
tls            on
tls_starttls   off
tls_certcheck  off
logfile        /root/.msmtp.log
account default : your_label_here

その後、/etc/cron.hourly/reboot-checkにファイルを作成しました。

#!/usr/bin/env bash

if [ -f /var/run/reboot-required ]; then
        echo "A reboot is required following updates to server <TestServer> the machine will auto reboot in 1h" > /tmp/body.txt && sudo mailx -s "Reboot Required" [email protected] < /tmp/body.txt; rm /tmp/body.txt
fi

そして、マシンに再起動を必要とするアップデートがあり、/var/run/reboot-requiredファイルが作成されると、再起動を通知するメールが送信されます。

関連情報