Skip to content

Instantly share code, notes, and snippets.

@conqp
Last active May 18, 2021 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conqp/e7794ba64f303849452c706ae2283e92 to your computer and use it in GitHub Desktop.
Save conqp/e7794ba64f303849452c706ae2283e92 to your computer and use it in GitHub Desktop.
Send emails when systemd units fail
#! /usr/bin/env python3
"""Notify admins about failed services."""
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import Iterator, List
from configlib import loadcfg
from emaillib import EMail, Mailer
DESCRIPTION = __doc__
CONFIG_FILE = Path('/usr/local/etc/notify-failed.conf')
SUBJECT = '[Service failure]: {}'
BODY = '''Dear Administrator,
the service unit "{}" has failed just now.
Please look into it.
Kind regards,
The Server
'''
def get_args() -> Namespace:
"""Parses the command line arguments."""
parser = ArgumentParser(description=DESCRIPTION)
parser.add_argument('unit', help='unit that failed')
return parser.parse_args()
def get_emails(unit, sender, recipients: List[str]) -> Iterator[EMail]:
"""Yields emails."""
for recipient in recipients:
yield EMail(SUBJECT.format(unit), sender, recipient,
plain=BODY.format(unit))
def main():
"""Send emails to admins."""
args = get_args()
config = loadcfg(CONFIG_FILE)
recipients = config.get('email', 'recipients').split()
emails = get_emails(args.unit, config.get('email', 'from'), recipients)
mailer = Mailer(
config.get('email', 'host'), config.getint('email', 'port'),
config.get('email', 'user'), passwd=config.get('email', 'passwd')
)
mailer.send(emails)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment