问题原文
原帖链接 · Greg · CC BY-SA 3.0
I have a critical application which is run as a service by systemd.
It is set up to restart as soon as there is a failure.
How to send an email if the application restarts?
已采纳解答
原帖链接 · gxx · CC BY-SA 3.0
First you need two files: an executable for sending the mail and a .service for starting the executable. For this example, the executable is just a shell script using sendmail:
/usr/local/bin/systemd-email:
#!/bin/bash
/usr/bin/sendmail -t <<ERRMAIL
To: $1
From: systemd <root@$HOSTNAME>
Subject: $2
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8
$(systemctl status --full "$2")
ERRMAIL
Whatever executable you use, it should probably take at least two arguments as this shell script does: the address to send to and the unit file to get the status of. The .service we create will pass these arguments:
/etc/systemd/system/status-email-user@.service:
[Unit]
Description=status email for %i to user
[Service]
Type=oneshot
ExecStart=/usr/local/bin/systemd-email address %i
User=nobody
Group=systemd-journal
Where user is the user being emailed and address is that user's email address. Although the recipient is hard-coded, the unit file to report on is passed as an instance parameter, so this one service can send email for many other units. At this point you can start [email omitted] to verify that you can receive the emails.
Then simply edit the service you want emails for and add OnFailure=status-email-user@%n.service to the [Unit] section. %n passes the unit's name to the template.
Source: archlinux wiki: systemd timers MAILTO
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
