Сравнить две копии
Показывает файлы, которые есть только слева, только справа или отличаются по размеру и хешу.
Что делает скрипт
Скрипт обходит две папки и строит относительные списки файлов и ссылок. По умолчанию сравнивает размеры, а с флагом --hash пересчитывает SHA-256. Отчёт выводится в терминал или сохраняется в новый JSON.
Быстрый старт
python compare_backups.py --left /mnt/backup/old --right /mnt/backup/new --hash
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python compare_backups.py --left /mnt/backup/old --right /mnt/backup/new --hashpython compare_backups.py --left /mnt/backup/old --right /mnt/backup/new --json diff.json
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
compare_backups.py
#!/usr/bin/env python3
"""Сравнение двух каталогов бэкапа без изменения файлов."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
from pathlib import Path
def file_digest(path: Path, chunk_size: int = 1024 * 1024) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while block := handle.read(chunk_size):
digest.update(block)
return digest.hexdigest()
def scan(root: Path, with_hash: bool) -> dict[str, tuple]:
result: dict[str, tuple] = {}
for current, dirs, files in os.walk(root):
dirs.sort()
for name in sorted(files):
path = Path(current, name)
relative = path.relative_to(root).as_posix()
if path.is_symlink():
result[relative] = ("link", os.readlink(path))
continue
if not path.is_file():
continue
try:
size = path.stat().st_size
digest = file_digest(path) if with_hash else ""
except OSError as error:
result[relative] = ("error", str(error))
continue
result[relative] = ("file", size, digest)
return result
def main() -> int:
parser = argparse.ArgumentParser(description="Сравнить две папки бэкапа")
parser.add_argument("--left", type=Path, required=True)
parser.add_argument("--right", type=Path, required=True)
parser.add_argument("--hash", action="store_true", help="Сравнивать SHA-256")
parser.add_argument("--json", type=Path, help="Сохранить отчёт в новый JSON")
args = parser.parse_args()
left = args.left.expanduser().resolve()
right = args.right.expanduser().resolve()
if not left.is_dir():
parser.error(f"Левая папка не найдена: {left}")
if not right.is_dir():
parser.error(f"Правая папка не найдена: {right}")
left_files = scan(left, args.hash)
right_files = scan(right, args.hash)
only_left = sorted(set(left_files) - set(right_files))
only_right = sorted(set(right_files) - set(left_files))
different = []
for name in sorted(set(left_files) & set(right_files)):
if left_files[name] != right_files[name]:
different.append(name)
for name in only_left:
print(f"только слева: {name}")
for name in only_right:
print(f"только справа: {name}")
for name in different:
print(f"отличается: {name}")
print(f"Слева: {len(left_files)}, справа: {len(right_files)}")
print(f"Только слева: {len(only_left)}, только справа: {len(only_right)}, отличий: {len(different)}")
if args.json:
target = args.json.expanduser().resolve()
if target.exists():
print(f"Отчёт уже существует: {target}", file=sys.stderr)
return 2
payload = {
"only_left": only_left,
"only_right": only_right,
"different": different,
}
target.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Отчёт: {target}")
return 0
if __name__ == "__main__":
sys.exit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.