Skip to content

Backends API

AbstractBackend

systemd_client.backends._base.AbstractBackend

Bases: ABC

Abstract base class for systemd backends.

All methods are async. Sync clients wrap these via run_sync().

Source code in src/systemd_client/backends/_base.py
class AbstractBackend(ABC):
    """Abstract base class for systemd backends.

    All methods are async. Sync clients wrap these via run_sync().
    """

    @abstractmethod
    async def list_units(
        self,
        unit_type: str | None = None,
        state: str | None = None,
    ) -> list[UnitInfo]:
        ...

    @abstractmethod
    async def list_unit_files(
        self,
        unit_type: str | None = None,
        state: str | None = None,
    ) -> list[UnitFileInfo]:
        ...

    @abstractmethod
    async def get_unit_status(self, unit_name: str) -> UnitStatus:
        ...

    @abstractmethod
    async def cat(self, unit_name: str) -> str:
        ...

    @abstractmethod
    async def start_unit(self, unit_name: str, no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def stop_unit(self, unit_name: str, no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def restart_unit(self, unit_name: str, no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def reload_unit(self, unit_name: str, no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def try_restart_unit(self, unit_name: str, no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def reload_or_restart_unit(self, unit_name: str, no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def start_units(self, unit_names: list[str], no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def stop_units(self, unit_names: list[str], no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def restart_units(self, unit_names: list[str], no_block: bool = False) -> None:
        ...

    @abstractmethod
    async def enable_unit(self, unit_name: str) -> EnableResult:
        ...

    @abstractmethod
    async def disable_unit(self, unit_name: str) -> EnableResult:
        ...

    @abstractmethod
    async def mask_unit(self, unit_name: str) -> EnableResult:
        ...

    @abstractmethod
    async def unmask_unit(self, unit_name: str) -> EnableResult:
        ...

    @abstractmethod
    async def daemon_reload(self) -> None:
        ...

    @abstractmethod
    async def reset_failed(self, unit_name: str | None = None) -> None:
        ...

    @abstractmethod
    async def get_unit_file_state(self, unit_name: str) -> str:
        ...

    @abstractmethod
    async def is_active(self, unit_name: str) -> bool:
        ...

    @abstractmethod
    async def is_enabled(self, unit_name: str) -> bool:
        ...

    @abstractmethod
    async def is_failed(self, unit_name: str) -> bool:
        ...

    @abstractmethod
    async def show_environment(self) -> dict[str, str]:
        ...

    @abstractmethod
    async def set_environment(self, variables: dict[str, str]) -> None:
        ...

    @abstractmethod
    async def unset_environment(self, names: list[str]) -> None:
        ...

    @abstractmethod
    async def list_sessions(self) -> list[SessionInfo]:
        ...

    @abstractmethod
    async def list_users(self) -> list[UserInfo]:
        ...

    @abstractmethod
    async def terminate_session(self, session_id: str) -> None:
        ...

    @abstractmethod
    async def lock_session(self, session_id: str) -> None:
        ...

    @abstractmethod
    async def set_property(self, unit_name: str, properties: dict[str, str]) -> None:
        ...

    @abstractmethod
    async def get_resource_usage(self, unit_name: str) -> ResourceUsage:
        ...

    @abstractmethod
    async def list_timers(self) -> list[TimerInfo]:
        ...

    @abstractmethod
    async def list_sockets(self) -> list[SocketInfo]:
        ...

    @abstractmethod
    async def list_dependencies(self, unit_name: str) -> list[str]:
        ...

    @abstractmethod
    async def kill_unit(self, unit_name: str, signal: str = "SIGTERM") -> None:
        ...

    @abstractmethod
    async def run_transient(
        self,
        command: list[str],
        *,
        name: str | None = None,
        properties: dict[str, str] | None = None,
        remain_after_exit: bool = False,
        wait: bool = False,
    ) -> TransientResult:
        ...

    @abstractmethod
    async def run_transient_timer(
        self,
        command: list[str],
        *,
        on_calendar: str | None = None,
        on_active: str | None = None,
        name: str | None = None,
    ) -> TransientResult:
        ...

    @abstractmethod
    async def install_unit_file(self, unit_file: UnitFile) -> str:
        """Write a unit file to the appropriate directory. Returns the written path."""
        ...

    @abstractmethod
    async def uninstall_unit_file(self, unit_name: str) -> None:
        """Remove a unit file and daemon-reload."""
        ...

    @abstractmethod
    async def edit_unit_file(
        self,
        unit_name: str,
        overrides: dict[str, dict[str, str]],
    ) -> str:
        """Create a drop-in override file. Returns the written path."""
        ...

    async def close(self) -> None:  # noqa: B027
        """Release backend resources. Override in subclasses that hold connections."""

close() async

Release backend resources. Override in subclasses that hold connections.

Source code in src/systemd_client/backends/_base.py
async def close(self) -> None:  # noqa: B027
    """Release backend resources. Override in subclasses that hold connections."""

edit_unit_file(unit_name, overrides) abstractmethod async

Create a drop-in override file. Returns the written path.

Source code in src/systemd_client/backends/_base.py
@abstractmethod
async def edit_unit_file(
    self,
    unit_name: str,
    overrides: dict[str, dict[str, str]],
) -> str:
    """Create a drop-in override file. Returns the written path."""
    ...

install_unit_file(unit_file) abstractmethod async

Write a unit file to the appropriate directory. Returns the written path.

Source code in src/systemd_client/backends/_base.py
@abstractmethod
async def install_unit_file(self, unit_file: UnitFile) -> str:
    """Write a unit file to the appropriate directory. Returns the written path."""
    ...

uninstall_unit_file(unit_name) abstractmethod async

Remove a unit file and daemon-reload.

Source code in src/systemd_client/backends/_base.py
@abstractmethod
async def uninstall_unit_file(self, unit_name: str) -> None:
    """Remove a unit file and daemon-reload."""
    ...

SubprocessBackend

systemd_client.backends._subprocess.SubprocessBackend

Bases: AbstractBackend

Backend that uses systemctl/journalctl subprocess calls.

Source code in src/systemd_client/backends/_subprocess.py
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
class SubprocessBackend(AbstractBackend):
    """Backend that uses systemctl/journalctl subprocess calls."""

    def __init__(self, scope: SystemdScope = SystemdScope.USER) -> None:
        self._scope = scope

    @property
    def _scope_flag(self) -> str:
        return f"--{self._scope.value}"

    async def _run_systemctl(self, *args: str, check: bool = True) -> tuple[str, str, int]:
        """Run a systemctl command and return (stdout, stderr, returncode)."""
        cmd = ["systemctl", self._scope_flag, *args]
        proc = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout_bytes, stderr_bytes = await proc.communicate()
        stdout = stdout_bytes.decode("utf-8", errors="replace")
        stderr = stderr_bytes.decode("utf-8", errors="replace")
        returncode = proc.returncode or 0

        if check and returncode != 0:
            raise SubprocessError(cmd, returncode, stderr.strip())

        return stdout, stderr, returncode

    async def list_units(
        self,
        unit_type: str | None = None,
        state: str | None = None,
    ) -> list[UnitInfo]:
        args = ["list-units", "--output=json", "--no-pager", "--all"]
        if unit_type:
            args.append(f"--type={unit_type}")
        if state:
            args.append(f"--state={state}")

        stdout, _, _ = await self._run_systemctl(*args)
        data = json.loads(stdout) if stdout.strip() else []

        units: list[UnitInfo] = []
        for entry in data:
            try:
                units.append(UnitInfo(
                    name=unescape_unit_name(entry["unit"]),
                    description=unescape_unit_name(entry.get("description", "")),
                    load_state=LoadState(entry.get("load", "loaded")),
                    active_state=ActiveState(entry.get("active", "inactive")),
                    sub_state=SubState(entry.get("sub", "dead")),
                    unit_file_state=None,
                ))
            except ValueError:
                continue
        return units

    async def list_unit_files(
        self,
        unit_type: str | None = None,
        state: str | None = None,
    ) -> list[UnitFileInfo]:
        args = ["list-unit-files", "--output=json", "--no-pager"]
        if unit_type:
            args.append(f"--type={unit_type}")
        if state:
            args.append(f"--state={state}")

        stdout, _, _ = await self._run_systemctl(*args)
        data = json.loads(stdout) if stdout.strip() else []

        files: list[UnitFileInfo] = []
        for entry in data:
            try:
                files.append(UnitFileInfo(
                    name=unescape_unit_name(entry.get("unit_file", entry.get("unit", ""))),
                    state=UnitFileState(entry.get("state", "disabled")),
                    preset=entry.get("preset") or None,
                ))
            except ValueError:
                continue
        return files

    async def get_unit_status(self, unit_name: str) -> UnitStatus:
        try:
            stdout, _, _ = await self._run_systemctl("show", unit_name, "--no-pager")
        except SubprocessError as exc:
            if "not found" in exc.stderr.lower():
                raise UnitNotFoundError(unit_name) from exc
            raise

        props: dict[str, str] = {}
        for line in stdout.splitlines():
            if "=" in line:
                key, _, value = line.partition("=")
                props[key.strip()] = value.strip()

        if props.get("LoadState") == "not-found":
            raise UnitNotFoundError(unit_name)

        def _parse_timestamp(key: str) -> datetime | None:
            raw = props.get(key, "")
            if not raw or raw == "0" or raw.startswith("n/a"):
                return None
            # systemctl show outputs microseconds since epoch for *USec fields
            usec_key = key + "USec" if not key.endswith("USec") else key
            raw_usec = props.get(usec_key, "")
            if raw_usec and raw_usec != "0":
                try:
                    return datetime.fromtimestamp(int(raw_usec) / 1_000_000, tz=UTC)
                except (ValueError, OSError):
                    pass
            # Try to parse the human-readable timestamp
            raw_ts = props.get(key, "")
            if raw_ts and raw_ts != "n/a":
                try:
                    return datetime.fromisoformat(raw_ts)
                except ValueError:
                    pass
            return None

        def _safe_int(key: str, *, zero_is_none: bool = True) -> int | None:
            """Parse an integer property. zero_is_none=True for PIDs, False for exit codes."""
            raw = props.get(key, "")
            if not raw:
                return None
            try:
                val = int(raw)
                if zero_is_none and val == 0:
                    return None
                return val
            except ValueError:
                return None

        def _safe_enum(enum_cls: type, key: str, default: str) -> object:
            raw = props.get(key, default)
            try:
                return enum_cls(raw)
            except ValueError:
                return enum_cls(default)

        triggered_by = [
            t.strip() for t in props.get("TriggeredBy", "").split() if t.strip()
        ]
        documentation = [
            d.strip() for d in props.get("Documentation", "").split() if d.strip()
        ]

        return UnitStatus(
            name=unescape_unit_name(props.get("Id", unit_name)),
            description=unescape_unit_name(props.get("Description", "")),
            load_state=_safe_enum(LoadState, "LoadState", "loaded"),  # type: ignore[arg-type]
            active_state=_safe_enum(ActiveState, "ActiveState", "inactive"),  # type: ignore[arg-type]
            sub_state=_safe_enum(SubState, "SubState", "dead"),  # type: ignore[arg-type]
            unit_file_state=(  # type: ignore[arg-type]
                _safe_enum(UnitFileState, "UnitFileState", "disabled")
                if props.get("UnitFileState") else None
            ),
            fragment_path=props.get("FragmentPath") or None,
            active_enter_timestamp=_parse_timestamp("ActiveEnterTimestamp"),
            active_exit_timestamp=_parse_timestamp("ActiveExitTimestamp"),
            inactive_enter_timestamp=_parse_timestamp("InactiveEnterTimestamp"),
            inactive_exit_timestamp=_parse_timestamp("InactiveExitTimestamp"),
            main_pid=_safe_int("MainPID"),
            exec_main_status=_safe_int("ExecMainStatus", zero_is_none=False),
            result=props.get("Result") or None,
            triggered_by=triggered_by,
            documentation=documentation,
            properties=props,
        )

    async def cat(self, unit_name: str) -> str:
        try:
            stdout, _, _ = await self._run_systemctl("cat", unit_name)
        except SubprocessError as exc:
            if "not found" in exc.stderr.lower() or "No files found" in exc.stderr:
                raise UnitNotFoundError(unit_name) from exc
            raise
        return stdout

    async def _unit_action(
        self, action: str, unit_name: str, no_block: bool = False,
    ) -> None:
        args = [action]
        if no_block:
            args.append("--no-block")
        args.append(unit_name)
        try:
            await self._run_systemctl(*args)
        except SubprocessError as exc:
            raise UnitOperationError(unit_name, action, exc.stderr) from exc

    async def start_unit(self, unit_name: str, no_block: bool = False) -> None:
        await self._unit_action("start", unit_name, no_block)

    async def stop_unit(self, unit_name: str, no_block: bool = False) -> None:
        await self._unit_action("stop", unit_name, no_block)

    async def restart_unit(self, unit_name: str, no_block: bool = False) -> None:
        await self._unit_action("restart", unit_name, no_block)

    async def reload_unit(self, unit_name: str, no_block: bool = False) -> None:
        await self._unit_action("reload", unit_name, no_block)

    async def try_restart_unit(self, unit_name: str, no_block: bool = False) -> None:
        await self._unit_action("try-restart", unit_name, no_block)

    async def reload_or_restart_unit(self, unit_name: str, no_block: bool = False) -> None:
        await self._unit_action("reload-or-restart", unit_name, no_block)

    async def _batch_action(
        self, action: str, unit_names: list[str], no_block: bool = False,
    ) -> None:
        args = [action]
        if no_block:
            args.append("--no-block")
        args.extend(unit_names)
        try:
            await self._run_systemctl(*args)
        except SubprocessError as exc:
            raise UnitOperationError(
                ", ".join(unit_names), action, exc.stderr,
            ) from exc

    async def start_units(self, unit_names: list[str], no_block: bool = False) -> None:
        await self._batch_action("start", unit_names, no_block)

    async def stop_units(self, unit_names: list[str], no_block: bool = False) -> None:
        await self._batch_action("stop", unit_names, no_block)

    async def restart_units(self, unit_names: list[str], no_block: bool = False) -> None:
        await self._batch_action("restart", unit_names, no_block)

    async def _enable_disable_op(self, operation: str, unit_name: str) -> EnableResult:
        try:
            stdout, _, _ = await self._run_systemctl(operation, unit_name)
        except SubprocessError as exc:
            raise UnitOperationError(unit_name, operation, exc.stderr) from exc

        changes: list[tuple[str, str, str]] = []
        for line in stdout.splitlines():
            line = line.strip()
            if not line:
                continue
            parts = line.split()
            if len(parts) >= 2:
                changes.append((
                    parts[0],
                    parts[1] if len(parts) > 1 else "",
                    parts[-1] if len(parts) > 2 else "",
                ))

        return EnableResult(changes=changes)

    async def enable_unit(self, unit_name: str) -> EnableResult:
        return await self._enable_disable_op("enable", unit_name)

    async def disable_unit(self, unit_name: str) -> EnableResult:
        return await self._enable_disable_op("disable", unit_name)

    async def mask_unit(self, unit_name: str) -> EnableResult:
        return await self._enable_disable_op("mask", unit_name)

    async def unmask_unit(self, unit_name: str) -> EnableResult:
        return await self._enable_disable_op("unmask", unit_name)

    async def daemon_reload(self) -> None:
        await self._run_systemctl("daemon-reload")

    async def reset_failed(self, unit_name: str | None = None) -> None:
        args = ["reset-failed"]
        if unit_name:
            args.append(unit_name)
        await self._run_systemctl(*args)

    async def get_unit_file_state(self, unit_name: str) -> str:
        stdout, _, _ = await self._run_systemctl("is-enabled", unit_name, check=False)
        return stdout.strip()

    async def is_active(self, unit_name: str) -> bool:
        _, _, returncode = await self._run_systemctl("is-active", unit_name, check=False)
        return returncode == 0

    async def is_enabled(self, unit_name: str) -> bool:
        _, _, returncode = await self._run_systemctl("is-enabled", unit_name, check=False)
        return returncode == 0

    async def is_failed(self, unit_name: str) -> bool:
        _, _, returncode = await self._run_systemctl("is-failed", unit_name, check=False)
        return returncode == 0

    # ── Unit file install / uninstall / edit ────────────────────

    # ── Environment management ───────────────────────────────

    async def show_environment(self) -> dict[str, str]:
        stdout, _, _ = await self._run_systemctl("show-environment")
        env: dict[str, str] = {}
        for line in stdout.splitlines():
            if "=" in line:
                k, _, v = line.partition("=")
                env[k] = v
        return env

    async def set_environment(self, variables: dict[str, str]) -> None:
        args = ["set-environment"]
        for k, v in variables.items():
            args.append(f"{k}={v}")
        await self._run_systemctl(*args)

    async def unset_environment(self, names: list[str]) -> None:
        await self._run_systemctl("unset-environment", *names)

    # ── Session management (loginctl) ──────────────────────────

    async def _run_loginctl(self, *args: str) -> str:
        cmd = ["loginctl", *args]
        proc = await asyncio.create_subprocess_exec(
            *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
        )
        stdout_bytes, stderr_bytes = await proc.communicate()
        if proc.returncode and proc.returncode != 0:
            stderr = stderr_bytes.decode("utf-8", errors="replace").strip()
            raise SubprocessError(cmd, proc.returncode, stderr)
        return stdout_bytes.decode("utf-8", errors="replace")

    async def list_sessions(self) -> list[SessionInfo]:
        stdout = await self._run_loginctl("list-sessions", "--no-legend", "--no-pager")
        sessions: list[SessionInfo] = []
        for line in stdout.splitlines():
            parts = line.split()
            if len(parts) >= 2:
                sessions.append(SessionInfo(
                    id=parts[0],
                    uid=int(parts[1]) if parts[1].isdigit() else 0,
                    user=parts[2] if len(parts) > 2 else "",
                    seat=parts[3] if len(parts) > 3 else "",
                    tty=parts[4] if len(parts) > 4 else "",
                    state=parts[-1] if len(parts) > 2 else "",
                ))
        return sessions

    async def list_users(self) -> list[UserInfo]:
        stdout = await self._run_loginctl("list-users", "--no-legend", "--no-pager")
        users: list[UserInfo] = []
        for line in stdout.splitlines():
            parts = line.split()
            if len(parts) >= 2:
                users.append(UserInfo(
                    uid=int(parts[0]) if parts[0].isdigit() else 0,
                    name=parts[1],
                    state=parts[-1] if len(parts) > 2 else "",
                ))
        return users

    async def terminate_session(self, session_id: str) -> None:
        await self._run_loginctl("terminate-session", session_id)

    async def lock_session(self, session_id: str) -> None:
        await self._run_loginctl("lock-session", session_id)

    # ── Resource control + monitoring ─────────────────────────

    async def set_property(self, unit_name: str, properties: dict[str, str]) -> None:
        args = ["set-property", unit_name]
        for k, v in properties.items():
            args.append(f"{k}={v}")
        try:
            await self._run_systemctl(*args)
        except SubprocessError as exc:
            raise UnitOperationError(unit_name, "set-property", exc.stderr) from exc

    async def get_resource_usage(self, unit_name: str) -> ResourceUsage:
        stdout, _, _ = await self._run_systemctl(
            "show", unit_name,
            "-p", "CPUUsageNSec,MemoryCurrent,MemoryPeak,"
            "TasksCurrent,IOReadBytes,IOWriteBytes",
            "--no-pager",
        )
        props: dict[str, str] = {}
        for line in stdout.splitlines():
            if "=" in line:
                k, _, v = line.partition("=")
                props[k.strip()] = v.strip()

        def _val(key: str) -> int | None:
            raw = props.get(key, "")
            if not raw or raw == "[not set]" or raw == "infinity":
                return None
            try:
                v = int(raw)
                return v if v > 0 else None
            except ValueError:
                return None

        return ResourceUsage(
            cpu_usage_nsec=_val("CPUUsageNSec"),
            memory_current=_val("MemoryCurrent"),
            memory_peak=_val("MemoryPeak"),
            tasks_current=_val("TasksCurrent"),
            io_read_bytes=_val("IOReadBytes"),
            io_write_bytes=_val("IOWriteBytes"),
        )

    async def list_timers(self) -> list[TimerInfo]:
        stdout, _, _ = await self._run_systemctl(
            "list-timers", "--output=json", "--no-pager", "--all",
        )
        data = json.loads(stdout) if stdout.strip() else []
        timers: list[TimerInfo] = []
        for entry in data:
            timers.append(TimerInfo(
                name=entry.get("unit", ""),
                time_left=entry.get("left", None),
                unit=entry.get("unit", ""),
                activates=entry.get("activates", None),
            ))
        return timers

    async def list_sockets(self) -> list[SocketInfo]:
        stdout, _, _ = await self._run_systemctl(
            "list-sockets", "--output=json", "--no-pager", "--all",
        )
        data = json.loads(stdout) if stdout.strip() else []
        sockets: list[SocketInfo] = []
        for entry in data:
            sockets.append(SocketInfo(
                name=entry.get("unit", ""),
                listen=entry.get("listen", ""),
                type=entry.get("type", ""),
                unit=entry.get("activates", entry.get("unit", "")),
            ))
        return sockets

    async def list_dependencies(self, unit_name: str) -> list[str]:
        stdout, _, _ = await self._run_systemctl(
            "list-dependencies", unit_name, "--plain", "--no-pager",
        )
        deps: list[str] = []
        for line in stdout.splitlines():
            name = line.strip()
            if name and name != unit_name:
                deps.append(name)
        return deps

    async def kill_unit(self, unit_name: str, signal: str = "SIGTERM") -> None:
        try:
            await self._run_systemctl("kill", unit_name, f"--signal={signal}")
        except SubprocessError as exc:
            raise UnitOperationError(unit_name, "kill", exc.stderr) from exc

    # ── Transient units (systemd-run) ─────────────────────────

    async def _run_systemd_run(self, *args: str) -> tuple[str, str, int]:
        cmd = ["systemd-run", self._scope_flag, *args]
        proc = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout_bytes, stderr_bytes = await proc.communicate()
        stdout = stdout_bytes.decode("utf-8", errors="replace")
        stderr = stderr_bytes.decode("utf-8", errors="replace")
        returncode = proc.returncode or 0
        if returncode != 0:
            raise SubprocessError(cmd, returncode, stderr.strip())
        return stdout, stderr, returncode

    def _parse_transient_result(self, stdout: str, stderr: str) -> TransientResult:
        """Parse systemd-run output for unit name and PID."""
        combined = stdout + stderr
        unit_name = ""
        pid = None
        for line in combined.splitlines():
            if "Running as unit:" in line or "Running timer as unit:" in line:
                unit_name = line.split(":")[-1].strip().rstrip(".")
            elif "as PID" in line:
                for part in line.split():
                    if part.isdigit():
                        pid = int(part)
                        break
        return TransientResult(unit_name=unit_name, pid=pid)

    async def run_transient(
        self,
        command: list[str],
        *,
        name: str | None = None,
        properties: dict[str, str] | None = None,
        remain_after_exit: bool = False,
        wait: bool = False,
    ) -> TransientResult:
        args: list[str] = []
        if name:
            args.extend(["--unit", name])
        if remain_after_exit:
            args.append("--remain-after-exit")
        if wait:
            args.append("--wait")
        if properties:
            for k, v in properties.items():
                args.extend(["--property", f"{k}={v}"])
        args.append("--")
        args.extend(command)
        stdout, stderr, _ = await self._run_systemd_run(*args)
        return self._parse_transient_result(stdout, stderr)

    async def run_transient_timer(
        self,
        command: list[str],
        *,
        on_calendar: str | None = None,
        on_active: str | None = None,
        name: str | None = None,
    ) -> TransientResult:
        args: list[str] = []
        if name:
            args.extend(["--unit", name])
        if on_calendar:
            args.extend(["--on-calendar", on_calendar])
        if on_active:
            args.extend(["--on-active", on_active])
        args.append("--")
        args.extend(command)
        stdout, stderr, _ = await self._run_systemd_run(*args)
        return self._parse_transient_result(stdout, stderr)

    # ── Unit file install / uninstall / edit ────────────────────

    async def install_unit_file(self, unit_file: UnitFile) -> str:
        target_dir = unit_file_dir(self._scope)

        def _write() -> str:
            target_dir.mkdir(parents=True, exist_ok=True)
            path = target_dir / unit_file.name
            path.write_text(unit_file.content, encoding="utf-8")
            return str(path)

        try:
            written = await asyncio.to_thread(_write)
        except OSError as exc:
            raise UnitFileInstallError(unit_file.name, "install", str(exc)) from exc

        await self.daemon_reload()
        return written

    async def uninstall_unit_file(self, unit_name: str) -> None:
        target_dir = unit_file_dir(self._scope)
        unit_path = target_dir / unit_name
        dropin_dir = target_dir / f"{unit_name}.d"

        def _remove() -> None:
            if not unit_path.exists():
                raise FileNotFoundError(unit_name)
            unit_path.unlink()
            if dropin_dir.is_dir():
                shutil.rmtree(dropin_dir)

        try:
            await asyncio.to_thread(_remove)
        except FileNotFoundError as exc:
            raise UnitNotFoundError(unit_name) from exc
        except OSError as exc:
            raise UnitFileInstallError(unit_name, "uninstall", str(exc)) from exc

        await self.daemon_reload()

    async def edit_unit_file(
        self,
        unit_name: str,
        overrides: dict[str, dict[str, str]],
    ) -> str:
        target_dir = unit_file_dir(self._scope)
        dropin_dir = target_dir / f"{unit_name}.d"

        def _write_override() -> str:
            dropin_dir.mkdir(parents=True, exist_ok=True)
            override_path = dropin_dir / "override.conf"
            lines: list[str] = []
            for section, kvs in overrides.items():
                lines.append(f"[{section}]")
                for key, value in kvs.items():
                    lines.append(f"{key}={value}")
                lines.append("")
            override_path.write_text("\n".join(lines), encoding="utf-8")
            return str(override_path)

        try:
            written = await asyncio.to_thread(_write_override)
        except OSError as exc:
            raise UnitFileInstallError(unit_name, "edit", str(exc)) from exc

        await self.daemon_reload()
        return written

get_backend

systemd_client.backends.get_backend(backend_type=BackendType.AUTO, scope=SystemdScope.USER)

Create and return the appropriate backend instance.

Source code in src/systemd_client/backends/__init__.py
def get_backend(
    backend_type: BackendType = BackendType.AUTO,
    scope: SystemdScope = SystemdScope.USER,
) -> AbstractBackend:
    """Create and return the appropriate backend instance."""
    if backend_type == BackendType.SUBPROCESS:
        return SubprocessBackend(scope=scope)

    if backend_type == BackendType.DBUS:
        try:
            from systemd_client.backends._dbus import DBusBackend
            return DBusBackend(scope=scope)
        except ImportError as exc:
            raise BackendNotAvailableError(
                "dbus",
                "dasbus is not installed. Install with: pip install systemd-client[dbus]",
            ) from exc

    # AUTO: try dbus first, fall back to subprocess
    try:
        from systemd_client.backends._dbus import DBusBackend
        return DBusBackend(scope=scope)
    except (ImportError, Exception):
        return SubprocessBackend(scope=scope)