讓 Ubuntu 伺服器在需要重新啟動系統時傳送郵件

讓 Ubuntu 伺服器在需要重新啟動系統時傳送郵件

當安裝了需要重新啟動伺服器的更新時,Ubuntu 伺服器 20.04 LTS 是否有可能向特定電子郵件地址發送郵件

例如,當檔案 /var/run/reboot-required.pkgs 確實存在時,它會向管理員發送一封郵件,以便他們可以重新啟動?

我已經瀏覽了谷歌,但找不到一個簡單的教程

答案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";

這實際上是最簡單的部分。接下來,我們必須建立一個輕量級郵政系統,將電子郵件從伺服器發送給您。

這是一種方法:

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

謝謝,我已經按照教程進行了操作,並為此編輯了一個 cronjob,因此事實上,作為用戶 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 檔案時,它會向我發送一封電子郵件以通知我重新啟動

相關內容