#!/usr/bin/env python3 """Аудит заданий launchd в macOS без изменения их состояния.""" from __future__ import annotations import argparse import json import os import plistlib import re import subprocess from pathlib import Path SOURCES = [ (Path.home() / "Library" / "LaunchAgents", "user-agent", "gui"), (Path("/Library/LaunchAgents"), "local-agent", "gui"), (Path("/Library/LaunchDaemons"), "local-daemon", "system"), (Path("/System/Library/LaunchAgents"), "system-agent", "gui"), (Path("/System/Library/LaunchDaemons"), "system-daemon", "system"), ] DISABLED_RE = re.compile(r'^\s*"([^"]+)"\s*=>\s*(true|false)\s*$') def disabled_labels(domain: str) -> set[str]: result = subprocess.run( ["launchctl", "print-disabled", domain], capture_output=True, text=True, check=False, ) labels: set[str] = set() for line in result.stdout.splitlines(): match = DISABLED_RE.match(line) if match and match.group(2) == "true": labels.add(match.group(1)) return labels def read_plist(path: Path) -> dict: try: with path.open("rb") as handle: data = plistlib.load(handle) except (OSError, plistlib.InvalidFileException, ValueError): return {} return data if isinstance(data, dict) else {} def main() -> int: parser = argparse.ArgumentParser(description="Аудит заданий launchd") parser.add_argument("--third-party", action="store_true", help="Только задания не от Apple") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() system_disabled = disabled_labels("system") gui_disabled = disabled_labels(f"gui/{os.getuid()}") rows: list[dict] = [] for directory, scope, domain in SOURCES: if not directory.is_dir(): continue for path in sorted(directory.glob("*.plist")): data = read_plist(path) label = str(data.get("Label") or path.stem) if args.third_party and label.startswith("com.apple."): continue program = data.get("Program") if not program: arguments = data.get("ProgramArguments") if isinstance(arguments, list) and arguments: program = arguments[0] disabled = label in (system_disabled if domain == "system" else gui_disabled) rows.append( { "label": label, "scope": scope, "path": str(path), "program": str(program or ""), "run_at_load": bool(data.get("RunAtLoad")), "keep_alive": data.get("KeepAlive", False), "disabled": disabled, } ) if args.json: args.json.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"Найдено заданий: {len(rows)}. Отключено: {sum(1 for row in rows if row['disabled'])}.") for row in rows: flags = [] if row["run_at_load"]: flags.append("RunAtLoad") if row["keep_alive"]: flags.append("KeepAlive") if row["disabled"]: flags.append("disabled") suffix = f" [{', '.join(flags)}]" if flags else "" print(f"\n{row['label']}{suffix}") print(f" scope: {row['scope']}") print(f" plist: {row['path']}") if row["program"]: print(f" program: {row['program']}") return 0 if __name__ == "__main__": raise SystemExit(main())