Skip to content

Instantly share code, notes, and snippets.

@Gunni
Created May 4, 2023 18:46
Show Gist options
  • Save Gunni/b38ccefbf6beca26fe76a7ca5abcd08c to your computer and use it in GitHub Desktop.
Save Gunni/b38ccefbf6beca26fe76a7ca5abcd08c to your computer and use it in GitHub Desktop.
How to get systemd service state via dbus in python
#!/usr/bin/env python3
from dataclasses import dataclass
from enum import Enum
from typing import List
from pystemd.systemd1 import Manager
@dataclass
class ServiceActiveState(str, Enum):
active: str = 'active'
reloading: str = 'reloading'
inactive: str = 'inactive'
failed: str = 'failed'
activating: str = 'activating'
deactivating: str = 'deactivating'
@dataclass
class Unit:
# Based on ListUnits() from:
# https://www.freedesktop.org/software/systemd/man/org.freedesktop.systemd1.html
name: str
description: str
load_state: str
active_state: ServiceActiveState
sub_state: str
follower: str
object_path: str
job_id: int
job_type: str
job_object_path: str
def __lt__(self, other: 'Unit') -> bool:
return self.name < other.name
def __str__(self):
return f'{self.name}\n\t{repr(self)}'
with Manager() as manager:
manager.load()
x = [ tuple(element.decode('utf-8') if isinstance(element, bytes) else element for element in unit) for unit in manager.ListUnits() ]
for unit in x:
print(Unit(*unit))
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment