#!/usr/bin/env python3 """Проверка /etc/fstab без монтирования.""" from __future__ import annotations import argparse import json import os import shutil import subprocess from dataclasses import asdict, dataclass from pathlib import Path REMOTE_PREFIXES = ("//", "host:") PSEUDO_FS = {"proc", "sysfs", "tmpfs", "devtmpfs", "devpts", "cgroup", "cgroup2", "securityfs", "debugfs", "tracefs", "pstore", "bpf", "configfs", "fusectl", "mqueue", "hugetlbfs", "autofs", "overlay", "swap"} @dataclass class Finding: level: str line: int message: str def run(argv: list[str]) -> subprocess.CompletedProcess[str] | None: try: return subprocess.run(argv, capture_output=True, text=True, check=False) except FileNotFoundError: return None def unescape(value: str) -> str: return value.replace("\\040", " ").replace("\\011", "\t").replace("\\012", "\n").replace("\\134", "\\") def known_filesystems() -> set[str]: result = run(["cat", "/proc/filesystems"]) filesystems = set(PSEUDO_FS) if result: for line in result.stdout.splitlines(): parts = line.split() if parts: filesystems.add(parts[-1]) filesystems.update({"nfs", "nfs4", "cifs", "smb3", "fuse", "fuse.sshfs"}) return filesystems def resolve_device(spec: str) -> tuple[bool, str]: if spec.startswith("UUID="): value = spec.split("=", 1)[1] link = Path("/dev/disk/by-uuid") / value if link.exists(): return True, f"устройство {link}" result = run(["blkid", "-U", value]) if result and result.returncode == 0 and result.stdout.strip(): return True, result.stdout.strip() return False, f"UUID {value} не найден" if spec.startswith("PARTUUID="): value = spec.split("=", 1)[1] link = Path("/dev/disk/by-partuuid") / value if link.exists(): return True, f"устройство {link}" result = run(["blkid", "-t", f"PARTUUID={value}", "-o", "device"]) if result and result.returncode == 0 and result.stdout.strip(): return True, result.stdout.strip() return False, f"PARTUUID {value} не найден" if spec.startswith("LABEL="): value = spec.split("=", 1)[1] link = Path("/dev/disk/by-label") / value if link.exists(): return True, f"устройство {link}" result = run(["blkid", "-L", value]) if result and result.returncode == 0 and result.stdout.strip(): return True, result.stdout.strip() return False, f"LABEL {value} не найден" if spec.startswith(REMOTE_PREFIXES): return True, "удалённый ресурс, проверка пропущена" if spec.startswith("/"): path = Path(spec) if path.exists(): return True, "устройство существует" return False, f"устройство не найдено: {spec}" return True, "специальный источник, проверка пропущена" def parse_fstab(path: Path) -> tuple[list[dict], list[Finding]]: entries: list[dict] = [] findings: list[Finding] = [] try: lines = path.read_text(encoding="utf-8", errors="replace").splitlines() except OSError as error: findings.append(Finding("error", 0, f"не удалось прочитать {path}: {error}")) return entries, findings for number, raw in enumerate(lines, start=1): line = raw.strip() if not line or line.startswith("#"): continue tokens = line.split() if "#" in tokens: tokens = tokens[:tokens.index("#")] if len(tokens) < 4: findings.append(Finding("error", number, "меньше четырёх полей")) continue spec, mountpoint, fstype, options = tokens[:4] spec = unescape(spec).replace('"', "").replace("'", "") dump = tokens[4] if len(tokens) > 4 else "0" passno = tokens[5] if len(tokens) > 5 else "0" mountpoint = unescape(mountpoint) is_swap = fstype == "swap" or mountpoint in {"none", "swap"} if not is_swap: if not mountpoint.startswith("/"): findings.append(Finding("error", number, f"точка монтирования не абсолютная: {mountpoint}")) elif not Path(mountpoint).exists(): findings.append(Finding("warning", number, f"точка монтирования не существует: {mountpoint}")) entries.append( { "line": number, "spec": spec, "mountpoint": mountpoint, "fstype": fstype, "options": options, "dump": dump, "pass": passno, } ) return entries, findings def main() -> int: parser = argparse.ArgumentParser(description="Проверка /etc/fstab") parser.add_argument("--file", type=Path, default=Path("/etc/fstab"), help="Путь к fstab") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() entries, findings = parse_fstab(args.file) filesystems = known_filesystems() mountpoints: dict[str, int] = {} for entry in entries: number = entry["line"] spec = entry["spec"] if spec not in {"none", "proc", "sysfs", "tmpfs", "devtmpfs"} and not spec.startswith(REMOTE_PREFIXES): ok, message = resolve_device(spec) if not ok: findings.append(Finding("error", number, message)) if entry["fstype"] not in filesystems: findings.append(Finding("warning", number, f"неизвестная файловая система: {entry['fstype']}")) if entry["fstype"] != "swap" and entry["mountpoint"] not in {"none", "swap"}: if entry["mountpoint"] in mountpoints: findings.append(Finding("error", number, f"дубль точки монтирования {entry['mountpoint']} (строка {mountpoints[entry['mountpoint']]})")) else: mountpoints[entry["mountpoint"]] = number if "noauto" not in entry["options"].split(",") and entry["fstype"] not in PSEUDO_FS: if not Path(entry["mountpoint"]).exists(): findings.append(Finding("warning", number, f"для авто-монтирования нужен каталог {entry['mountpoint']}")) if shutil.which("findmnt"): result = run(["findmnt", "--verify", "--tab-file", str(args.file)]) if result and result.returncode != 0: text = (result.stdout + result.stderr).strip() if text: findings.append(Finding("error", 0, "findmnt --verify: " + text.replace("\n", " | ")[:500])) print(f"Файл: {args.file}") print(f"Записей: {len(entries)}") print(f"{'УРОВЕНЬ':<9} {'СТРОКА':>7} СООБЩЕНИЕ") print("-" * 100) for finding in findings: print(f"{finding.level:<9} {finding.line:>7} {finding.message}") if not findings: print("Замечаний нет.") if args.json: args.json.write_text( json.dumps({"entries": entries, "findings": [asdict(item) for item in findings]}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) print(f"\nJSON сохранён: {args.json}") errors = sum(1 for item in findings if item.level == "error") if errors: print(f"\nОшибок: {errors}") return 1 return 0 if __name__ == "__main__": raise SystemExit(main())