#!/usr/bin/env python3 """Инвентаризация macOS без серийных номеров и персональных данных.""" from __future__ import annotations import argparse import json import platform import re import shutil import subprocess from pathlib import Path def run(command: list[str]) -> str: try: result = subprocess.run(command, capture_output=True, text=True, check=False, timeout=30) except (OSError, subprocess.TimeoutExpired): return "" return result.stdout.strip() def storage() -> list[dict]: output = run(["df", "-kP"]) volumes = [] for line in output.splitlines()[1:]: fields = line.split() if len(fields) < 6: continue mount = " ".join(fields[5:]) if not mount.startswith(("/", "/System/Volumes/Data")): continue try: total = int(fields[1]) * 1024 used = int(fields[2]) * 1024 available = int(fields[3]) * 1024 except ValueError: continue volumes.append({"mount": mount, "total": total, "used": used, "available": available}) return volumes def displays() -> list[str]: output = run(["system_profiler", "SPDisplaysDataType"]) result = [] current = "" for line in output.splitlines(): stripped = line.strip() if stripped.endswith(":") and not stripped.startswith(("Chipset", "Type", "Bus", "VRAM", "Vendor", "Device")): if len(line) - len(line.lstrip()) <= 8: current = stripped[:-1] if "Resolution:" in stripped: result.append(f"{current}: {stripped.split('Resolution:', 1)[1].strip()}") return result def main() -> int: parser = argparse.ArgumentParser(description="Инвентаризация Mac") parser.add_argument("--json", type=Path) parser.add_argument("--markdown", type=Path) args = parser.parse_args() applications = len(list(Path("/Applications").glob("*.app"))) brew = shutil.which("brew") brew_output = run([brew, "--version"]) if brew else "" brew_version = brew_output.splitlines()[0] if brew_output else "" brew_formulas = len(run([brew, "list", "--formula"]).splitlines()) if brew else 0 swift_output = run(["swift", "--version"]) if shutil.which("swift") else "" report = { "os": { "name": "macOS", "version": run(["sw_vers", "-productVersion"]), "build": run(["sw_vers", "-buildVersion"]), "kernel": platform.release(), }, "hardware": { "model": run(["sysctl", "-n", "hw.model"]), "arch": platform.machine(), "cpu_count": run(["sysctl", "-n", "hw.ncpu"]), "memory_bytes": int(run(["sysctl", "-n", "hw.memsize"]) or 0), }, "storage": storage(), "displays": displays(), "applications": applications, "homebrew": {"installed": bool(brew), "version": brew_version, "formulas": brew_formulas}, "developer": { "xcode_path": run(["xcode-select", "-p"]), "swift": swift_output.splitlines()[0] if swift_output else "", }, } if args.json: args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") if args.markdown: memory_gb = report["hardware"]["memory_bytes"] / 1024 ** 3 lines = [ "# Инвентаризация Mac", "", f"- macOS: {report['os']['version']} ({report['os']['build']})", f"- Модель: {report['hardware']['model']}", f"- Архитектура: {report['hardware']['arch']}", f"- CPU: {report['hardware']['cpu_count']} логических ядер", f"- Память: {memory_gb:.1f} ГБ", f"- Приложений в /Applications: {applications}", f"- Homebrew: {brew_version or 'не установлен'}", f"- Формул Homebrew: {brew_formulas}", "", "## Диски", "", ] for volume in report["storage"]: lines.append(f"- {volume['mount']}: {volume['used'] / 1024 ** 3:.1f} из {volume['total'] / 1024 ** 3:.1f} ГБ") lines.extend(["", "## Дисплеи", ""]) lines.extend(f"- {item}" for item in report["displays"]) args.markdown.write_text("\n".join(lines) + "\n", encoding="utf-8") memory_gb = report["hardware"]["memory_bytes"] / 1024 ** 3 print(f"macOS: {report['os']['version']} ({report['os']['build']})") print(f"Модель: {report['hardware']['model']}, {report['hardware']['arch']}") print(f"Ядер: {report['hardware']['cpu_count']}, память: {memory_gb:.1f} ГБ") print(f"Приложений: {applications}. Homebrew: {brew_version or 'не установлен'}.") print(f"Дисков в отчёте: {len(report['storage'])}. Дисплеев: {len(report['displays'])}.") return 0 if __name__ == "__main__": raise SystemExit(main())