Бэкап файлов конфигурации
Собирает указанные файлы и папки конфигурации в отдельный каталог с manifest.
Что делает скрипт
Скрипт принимает несколько путей, копирует только обычные файлы и сохраняет понятную структуру в новом каталоге. Символические ссылки пропускаются, существующие копии не перезаписываются. По умолчанию работает предпросмотр, запись включается флагом --apply.
- В конфигурациях могут быть токены и пароли.
Быстрый старт
python backup_configs.py --path ~/.gitconfig --path ~/.config/app --dest /mnt/backup/configs --apply
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python backup_configs.py --path ~/.gitconfig --path ~/.config/app --dest /mnt/backup/configspython backup_configs.py --path /etc/nginx --dest /mnt/backup/configs --apply
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
backup_configs.py
#!/usr/bin/env python3
"""Сбор выбранных файлов конфигурации в отдельный каталог."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import sys
import time
from pathlib import Path
def is_inside(child: Path, parent: Path) -> bool:
try:
child.relative_to(parent)
return True
except ValueError:
return False
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 main() -> int:
parser = argparse.ArgumentParser(description="Копия выбранных конфигураций")
parser.add_argument("--path", type=Path, action="append", required=True, help="Файл или папка")
parser.add_argument("--dest", type=Path, required=True, help="Корень для бэкапов")
parser.add_argument("--apply", action="store_true", help="Выполнить копирование")
args = parser.parse_args()
sources = [path.expanduser().resolve() for path in args.path]
dest = args.dest.expanduser().resolve()
missing = [str(path) for path in sources if not path.exists()]
if missing:
parser.error("Пути не найдены: " + ", ".join(missing))
for source in sources:
if source.is_dir() and is_inside(dest, source):
parser.error(f"Назначение не должно быть внутри источника: {source}")
timestamp = time.strftime("%Y%m%d-%H%M%S")
target_root = dest / f"configs-{timestamp}"
if target_root.exists():
parser.error(f"Каталог уже существует: {target_root}")
planned = 0
copied = 0
skipped = 0
errors = 0
entries = []
for index, source in enumerate(sources, 1):
base = f"{index:02d}-{source.name}"
if source.is_file():
candidates = [(source, Path(base))]
else:
candidates = []
for current, dirs, files in os.walk(source):
dirs[:] = sorted(name for name in dirs if not Path(current, name).is_symlink())
for name in sorted(files):
path = Path(current, name)
if path.is_symlink() or not path.is_file():
continue
relative = path.relative_to(source)
candidates.append((path, Path(base) / relative))
for path, relative in candidates:
planned += 1
target = target_root / relative
if not args.apply:
if planned <= 30:
print(f"Будет скопировано: {relative}")
continue
try:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, target)
copied += 1
entries.append(
{
"source": str(path),
"target": str(target),
"size": target.stat().st_size,
"sha256": file_digest(target),
}
)
except OSError as error:
errors += 1
print(f"Ошибка {path}: {error}")
if args.apply:
target_root.mkdir(parents=True, exist_ok=True)
manifest_path = target_root / "manifest.json"
manifest_path.write_text(
json.dumps({"files": entries}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(f"Manifest: {manifest_path}")
else:
print("Предпросмотр. Для копирования добавьте --apply.")
print(f"Файлов: {planned}, скопировано: {copied}, пропущено: {skipped}, ошибок: {errors}")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.