Last active
November 10, 2021 23:04
-
-
Save fxthomas/abeaf26aeefe2f2eb960f767470fd9d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 = '[email protected]' | |
recipient = '[email protected]' | |
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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