Проверить контрольные суммы
Проверяет файлы по manifest или списку sha256sum и показывает совпадения, ошибки и пропавшие файлы.
Что делает скрипт
Скрипт читает JSON manifest, созданный make_manifest.py, или обычный текстовый список вида hash и путь. Для каждого файла заново считается SHA-256, путь берётся относительно базы или из корня manifest. Проверка только читает файлы, итоговый код возврата ненулевой при расхождениях.
Быстрый старт
python verify_checksums.py --manifest manifest.json
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python verify_checksums.py --manifest manifest.jsonpython verify_checksums.py --manifest SHA256SUMS --base ./backup --json result.json
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
verify_checksums.py
#!/usr/bin/env python3
"""Проверка файлов по контрольным суммам SHA-256."""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
def file_hash(path: Path, chunk_size: int = 1024 * 1024) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while chunk := handle.read(chunk_size):
digest.update(chunk)
return digest.hexdigest()
def load_entries(path: Path) -> tuple[list[tuple[str, str]], Path | None]:
text = path.read_text(encoding="utf-8", errors="replace")
if path.suffix.lower() == ".json" or text.lstrip().startswith("{"):
data = json.loads(text)
suggested = Path(data["root"]) if data.get("root") else None
entries = []
for item in data.get("files", []):
relative = item.get("path")
digest = item.get("sha256") or item.get("hash")
if relative and digest:
entries.append((str(relative), str(digest).lower()))
return entries, suggested
entries = []
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split(None, 1)
if len(parts) != 2 or len(parts[0]) != 64:
continue
digest, name = parts
if name.startswith("*"):
name = name[1:]
entries.append((name, digest.lower()))
return entries, None
def main() -> int:
parser = argparse.ArgumentParser(description="Проверить контрольные суммы")
parser.add_argument("--manifest", type=Path, required=True, help="JSON manifest или список sha256sum")
parser.add_argument("--base", type=Path, help="Базовая папка для относительных путей")
parser.add_argument("--json", type=Path, help="Сохранить результат в JSON")
args = parser.parse_args()
manifest = args.manifest.expanduser().resolve()
if not manifest.is_file():
parser.error(f"Manifest не найден: {manifest}")
try:
entries, suggested = load_entries(manifest)
except (OSError, ValueError, json.JSONDecodeError) as error:
parser.error(f"Не удалось прочитать manifest: {error}")
if not entries:
parser.error("В manifest не найдено ни одной записи с SHA-256")
if args.base:
base = args.base.expanduser().resolve()
elif suggested:
base = suggested.expanduser().resolve()
else:
base = manifest.parent
if not base.is_dir():
parser.error(f"Базовая папка не найдена: {base}")
checked = 0
failed = 0
missing = 0
failures = []
for relative, expected in entries:
path = Path(relative)
if not path.is_absolute():
path = base / path
if not path.is_file():
missing += 1
failures.append({"path": str(path), "status": "missing"})
print(f"НЕТ ФАЙЛА: {path}")
continue
try:
actual = file_hash(path)
except OSError as error:
failed += 1
failures.append({"path": str(path), "status": "unreadable", "error": str(error)})
print(f"ОШИБКА ЧТЕНИЯ: {path}: {error}")
continue
checked += 1
if actual == expected:
print(f"OK: {path}")
else:
failed += 1
failures.append({"path": str(path), "status": "mismatch", "expected": expected, "actual": actual})
print(f"НЕ СОВПАЛО: {path}")
print(f"\nПроверено: {checked}, ошибок: {failed}, пропущено: {missing}")
if args.json:
output = args.json.expanduser()
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(
json.dumps(
{"manifest": str(manifest), "base": str(base), "checked": checked, "failures": failures},
ensure_ascii=False,
indent=2,
) + "\n",
encoding="utf-8",
)
print(f"Отчёт сохранён: {output}")
return 1 if failed or missing else 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.