Skip to content

Instantly share code, notes, and snippets.

@leoluk
Created October 3, 2018 22:19
Show Gist options
  • Save leoluk/fec72d340aaf5354a1936ebd13a8c5c8 to your computer and use it in GitHub Desktop.
Save leoluk/fec72d340aaf5354a1936ebd13a8c5c8 to your computer and use it in GitHub Desktop.
Example code that demonstrates how to listen to journald using Python 3 + asyncio.
#!/usr/bin/python3 -u
import asyncio
import sh
from systemd import journal
from systemd.daemon import notify
GATEWAY_IP = "192.168.10.1"
GATEWAY_MAC = "xx:xx:xx:xx:xx:xx"
loop = asyncio.get_event_loop()
j = journal.Reader()
j.log_level(journal.LOG_INFO)
j.add_match(SYSLOG_IDENTIFIER="kernel")
j.seek_tail()
j.get_previous()
async def process(event):
if event["MESSAGE"].startswith("thinkpad_acpi: docked"):
if sh.arp('-n', GATEWAY_IP).stdout.decode().strip().split('\n')[-1].split()[2] == GATEWAY_MAC:
print("Notified docking")
await asyncio.create_subprocess_exec("/usr/bin/sudo", "/usr/bin/dash", "/root/scripts/unlock_usb.sh")
await asyncio.create_subprocess_exec("/usr/bin/sudo", "/usr/bin/ifconfig", "eth0", "up")
else:
print("Nope")
elif event["MESSAGE"].startswith("thinkpad_acpi: undocked"):
print("Undocked!")
await asyncio.create_subprocess_exec("/usr/bin/sudo", "/usr/bin/ifconfig", "eth0", "down")
def callback():
notify("WATCHDOG=1")
j.process()
for entry in j:
# FIXME: eats exceptions
asyncio.ensure_future(process(entry))
loop.add_reader(j.fileno(), callback)
loop.run_forever()
[Unit]
Description=Journal Reactor
[Service]
ExecStart=/usr/local/bin/journal-reactor.py
Restart=always
RestartSec=0
WatchdogSec=60s
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment