Skip to content

Instantly share code, notes, and snippets.

@mikehearn
Last active December 4, 2023 11:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehearn/f1db694f24eaa05c753e5a759878772a to your computer and use it in GitHub Desktop.
Save mikehearn/f1db694f24eaa05c753e5a759878772a to your computer and use it in GitHub Desktop.
systemd unit monitoring setup
----------------------------------------------------
#!/usr/bin/env bash
# place in a file called email-unit-status.sh on the PATH
# requires you to have set /etc/admin-email to contain the address to receive the messages
# requires install of ansi2html
#
set -e
dest=$( cat /etc/admin-email )
userflag=
if [[ $HOME == /home/* ]]; then
userflag=--user
fi
html=$(SYSTEMD_COLORS=1 systemctl $userflag status --full "$1" | ansi2html -w -c)
/usr/sbin/sendmail -t <<ERRMAIL
To: $dest
From: systemd <${USER}@${HOSTNAME}>
Subject: SystemD unit failure alert: $1
Content-Transfer-Encoding: 8bit
Content-Type: text/html; charset=UTF-8
Mime-Version: 1.0
$html
ERRMAIL
----------------------------------
# Create in /etc/systemd/email-unit-status@.service
[Unit]
Description=Email status for %i to the admin
After=network.target
[Service]
Type=oneshot
ExecStart=email-unit-status %i
----------------------------------
# Use like this
[Unit]
Description=System Backup
Wants=network-online.target
After=network-online.target
ConditionACPower=true
OnFailure=email-unit-status@%n.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment