Skip to content

Instantly share code, notes, and snippets.

@fxthomas
Last active November 10, 2021 23:04
Show Gist options
  • Save fxthomas/abeaf26aeefe2f2eb960f767470fd9d8 to your computer and use it in GitHub Desktop.
Save fxthomas/abeaf26aeefe2f2eb960f767470fd9d8 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# coding=utf-8
from gi.repository import GObject
import sys
import dbus
import smtplib
import subprocess
from datetime import datetime
from dbus.mainloop.glib import DBusGMainLoop
from email.mime.text import MIMEText
import socket
fromemail = 'root@example.com'
recipient = 'myself@example.com'
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
manager = dbus.Interface(systemd, 'org.freedesktop.systemd1.Manager')
def OnJobRemoved(id, job, unit, result):
print('%d: Job Removed: ' % id, job, unit, result)
if result == "done":
print("%d: Result is done, skipping email." % id)
return
logs = subprocess.check_output(["journalctl", "-u", unit, "--lines=20"])
logs = logs.decode("utf-8")
msg = "Systemd job %s finished execution at %s with result %s.\n\n%s"
msg = MIMEText(msg % (unit, datetime.now(), result, logs))
msg['To'] = recipient
msg['From'] = fromemail
msg['Subject'] = "%s: Job %s finished with result %s" % (socket.getfqdn(), unit, result)
srv = smtplib.SMTP("localhost")
try:
srv.sendmail(fromemail, [recipient], msg.as_string())
print("%d: Sent email: %s" % (id, msg['Subject']))
finally:
srv.quit()
manager.Subscribe()
manager.connect_to_signal('JobRemoved', OnJobRemoved)
loop = GObject.MainLoop()
loop.run()
[Unit]
Description=Systemd email monitoring
After=network.target postfix.service
[Service]
ExecStart=/etc/systemd/system/systemd-monitor-jobs.py
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment