Skip to content

Instantly share code, notes, and snippets.

@SunRed
Last active October 6, 2021 09:00
Show Gist options
  • Save SunRed/dacb68d45f4453644c4bd74b3dd059ac to your computer and use it in GitHub Desktop.
Save SunRed/dacb68d45f4453644c4bd74b3dd059ac to your computer and use it in GitHub Desktop.
Send systemd service reports via encrypted multipart email on restart/stop or fail/success

systemd service report via encrypted email

Installation (Example setup)

  • Move systemd-email.sh to /usr/local/bin/ as systemd-email with permissions 755
  • Move systemd-email.conf to /usr/local/etc/systemd-email/
  • Move [email protected] to /etc/systemd/system/
  • Create public keyring for GnuPG in /usr/local/etc/systemd-email/ with gpg --homedir /usr/local/etc/systemd-email/ --no-default-keyring --keyring pubring.gpg --fingerprint and set the permissions on pubring.gpg and trustdb.gpg accordingly or to 644
  • Import your public key with gpg --homedir /usr/local/etc/systemd-email/ --import

Usage

To enable reports for failures on an example service myservice.service edit the unit file with systemctl edit myservice and add

OnFailure=status-email-user@%i

or

OnSuccess=status-email-user@%i

for emails on service stop with exit code 0, or just simply both (useful for services like btrfs-scrub@)


Inspired by this Stackoverflow post and ArchWiki entry

[Unit]
Description=Sends status emails for %i
[Service]
Type=oneshot
ExecStart=/usr/local/bin/systemd-email %i
DynamicUser=yes
SupplementaryGroups=systemd-journal postdrop
ReadWritePaths=/var/spool/postfix
RECIPIENT="[email protected]"
GPG_RECIPIENT="[email protected]"
ENVELOPE_SENDER="root@$HOSTNAME"
SENDER="systemd <$ENVELOPE_SENDER>"
#!/bin/bash
random_string() {
echo "$(openssl rand -base64 24)"
}
BOUNDARY1="$(random_string)"
BOUNDARY2="$(random_string)"
source /usr/local/etc/systemd-email/systemd-email.conf
ENCMSG=$(gpg --homedir /usr/local/etc/systemd-email \
--trust-model always \
--no-permission-warning \
--no-random-seed-file \
-qea -r "${GPG_RECIPIENT}" <<MSG
Subject: Service report for $1
Content-Type: multipart/mixed;
boundary="${BOUNDARY2}";
protected-headers="v1"
--${BOUNDARY2}
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: base64
$(systemctl status --full "$1" | base64)
--${BOUNDARY2}--
MSG
)
/usr/bin/sendmail -r $ENVELOPE_SENDER -t <<MAIL
To: $RECIPIENT
From: $SENDER
Subject: ...
MIME-Version: 1.0
Content-Type: multipart/encrypted;
protocol="application/pgp-encrypted";
boundary="${BOUNDARY1}"
X-Priority: 1 (Highest)
X-MSMail-Priority: High
Importance: High
--${BOUNDARY1}
Content-Type: application/pgp-encrypted
Version: 1
--${BOUNDARY1}
Content-Type: application/octet-stream
$ENCMSG
--${BOUNDARY1}--
MAIL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment