#!/usr/bin/env python3 """Разбор SSH-конфига и проверка файлов ключей.""" from __future__ import annotations import argparse import glob import json import os import shlex import stat import subprocess from dataclasses import asdict, dataclass from pathlib import Path @dataclass class Host: alias: str hostname: str user: str port: str identity: list[str] proxy_jump: str source: str def expand_include(value: str, base: Path) -> list[Path]: pattern = Path(os.path.expanduser(value)) if not pattern.is_absolute(): pattern = base / pattern return [Path(item) for item in sorted(glob.glob(str(pattern)))] def parse_blocks(path: Path, depth: int = 0, seen: set[str] | None = None): if seen is None: seen = set() key = str(path.resolve()) if path.exists() else str(path) if depth > 4 or key in seen: return [] seen.add(key) blocks = [] try: lines = path.read_text(encoding="utf-8", errors="replace").splitlines() except OSError: return blocks patterns: list[str] = [] options: dict[str, object] = {} source = str(path) def flush() -> None: nonlocal patterns, options if patterns: blocks.append((list(patterns), dict(options), source)) patterns = [] options = {} for raw in lines: line = raw.strip() if not line or line.startswith("#"): continue try: tokens = shlex.split(line, comments=True, posix=True) except ValueError: continue if not tokens: continue keyword = tokens[0].lower() if keyword == "host": flush() patterns = tokens[1:] elif keyword == "match": flush() elif keyword == "include": for token in tokens[1:]: for included in expand_include(token, path.parent): blocks.extend(parse_blocks(included, depth + 1, seen)) elif patterns and len(tokens) >= 2: value = " ".join(tokens[1:]) if keyword == "identityfile": current = options.setdefault(keyword, []) if isinstance(current, list): current.append(value) else: options.setdefault(keyword, value) flush() return blocks def key_report(path_text: str, hostname: str, user: str) -> tuple[str, list[str]]: expanded = path_text expanded = expanded.replace("%d", str(Path.home())) expanded = expanded.replace("%h", hostname) expanded = expanded.replace("%r", user) expanded = expanded.replace("%u", os.environ.get("USER", "user")) expanded = os.path.expanduser(expanded) if "%" in expanded: return path_text, ["шаблон в пути ключа, проверка пропущена"] path = Path(expanded) notes: list[str] = [] if not path.exists(): return path_text, ["файл ключа не найден"] try: mode = stat.S_IMODE(path.stat().st_mode) except OSError: return path_text, ["нет доступа к файлу ключа"] if not path.name.endswith(".pub") and mode & 0o077: notes.append(f"слишком открытые права {mode:o}") if subprocess.run(["bash", "-c", "command -v ssh-keygen"], capture_output=True).returncode == 0: result = subprocess.run(["ssh-keygen", "-lf", str(path)], capture_output=True, text=True, check=False) if result.returncode == 0 and result.stdout: notes.append(result.stdout.strip().splitlines()[0]) return path_text, notes def main() -> int: parser = argparse.ArgumentParser(description="Разбор SSH-конфига") parser.add_argument("--config", type=Path, default=Path.home() / ".ssh" / "config") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() config = args.config.expanduser() if not config.is_file(): print(f"SSH-конфиг не найден: {config}") return 0 blocks = parse_blocks(config) defaults: dict[str, object] = {} for patterns, options, _source in blocks: if patterns == ["*"]: for key, value in options.items(): defaults.setdefault(key, value) hosts: list[Host] = [] notes: list[str] = [] for patterns, options, source in blocks: for alias in patterns: if alias == "*" or any(char in alias for char in "*?!") or alias.startswith("!"): continue merged = dict(defaults) merged.update(options) hostname = str(merged.get("hostname", alias)) user = str(merged.get("user", os.environ.get("USER", "user"))) port = str(merged.get("port", "22")) identity_value = merged.get("identityfile", []) identity = identity_value if isinstance(identity_value, list) else [str(identity_value)] proxy = str(merged.get("proxyjump", "")) hosts.append(Host(alias, hostname, user, port, [str(item) for item in identity], proxy, source)) for item in identity: _path, key_notes = key_report(str(item), hostname, user) for note in key_notes: notes.append(f"{alias}: {note}") print(f"{'АЛИАС':<20} {'ХОСТ':<28} {'ПОЛЬЗОВАТЕЛЬ':<14} {'ПОРТ':<6} PROXYJUMP") print("-" * 100) for host in hosts: print(f"{host.alias:<20} {host.hostname:<28} {host.user:<14} {host.port:<6} {host.proxy_jump or '-'}") for item in host.identity: print(f"{'':<20} ключ: {item}") if notes: print("\nЗамечания по ключам:") for note in notes: print(f" - {note}") referenced = set() for host in hosts: for item in host.identity: referenced.add(Path(os.path.expanduser(item.replace("%d", str(Path.home())))).name) ssh_dir = Path.home() / ".ssh" unused = [] if ssh_dir.is_dir(): for path in sorted(ssh_dir.glob("id_*")): if path.name.endswith(".pub"): continue if path.name not in referenced: unused.append(str(path)) if unused: print("\nКлючи вне конфига:") for path in unused: print(f" - {path}") if args.json: args.json.write_text( json.dumps({"hosts": [asdict(host) for host in hosts], "notes": notes, "unused_keys": unused}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"\nJSON сохранён: {args.json}") return 0 if __name__ == "__main__": raise SystemExit(main())