-
-
Save un1tz3r0/c53a1d4f4ccbd2151484207604cf2fb2 to your computer and use it in GitHub Desktop.
Example code that demonstrates how to listen to journald using Python 3 + asyncio.
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/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() |
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=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