#!/usr/bin/env python3 """Поиск архивов с паролем среди zip и 7z.""" from __future__ import annotations import argparse import json import shutil import subprocess import zipfile from pathlib import Path def check_zip(path: Path) -> tuple[bool, str]: try: with zipfile.ZipFile(path) as archive: encrypted = any(info.flag_bits & 0x1 for info in archive.infolist()) return encrypted, "" except (zipfile.BadZipFile, OSError, RuntimeError) as error: return False, str(error) def check_7z(path: Path, tool: str) -> tuple[bool, str]: result = subprocess.run( [tool, "l", "-slt", "-p", str(path)], capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False, ) output = (result.stdout or "") + (result.stderr or "") lowered = output.lower() if result.returncode != 0: if "password" in lowered or "encrypted" in lowered: return True, "" return False, output.strip().splitlines()[-1] if output.strip() else "7z завершился с ошибкой" return "Encrypted = +" in output, "" def main() -> int: parser = argparse.ArgumentParser(description="Найти архивы с паролем") parser.add_argument("path", type=Path, nargs="?", default=Path("."), help="Папка или файл") parser.add_argument("--recursive", action="store_true", help="Обходить вложенные папки") parser.add_argument("--all", action="store_true", help="Показывать и обычные архивы") parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON") args = parser.parse_args() root = args.path.expanduser().resolve() if not root.exists(): parser.error(f"Путь не найден: {root}") if root.is_file(): files = [root] elif args.recursive: files = sorted(path for path in root.rglob("*") if path.is_file() and not path.is_symlink()) else: files = sorted(path for path in root.iterdir() if path.is_file() and not path.is_symlink()) tool = shutil.which("7z") records = [] found = 0 for path in files: suffix = path.suffix.lower() if suffix not in {".zip", ".7z"}: continue if suffix == ".zip": encrypted, error = check_zip(path) elif tool: encrypted, error = check_7z(path, tool) else: encrypted, error = False, "7z не найден" records.append({"path": str(path), "encrypted": encrypted, "error": error}) if encrypted: found += 1 print(f"С паролем: {path}") elif args.all: print(f"Без пароля: {path}") if error: print(f" Ошибка проверки: {error}") if not records: print("Архивы не найдены.") else: errors = sum(1 for item in records if item["error"]) print(f"Проверено архивов: {len(records)}, с паролем: {found}, ошибок: {errors}") if args.json: args.json.write_text(json.dumps({"records": records}, ensure_ascii=False, indent=2), encoding="utf-8") return 0 if __name__ == "__main__": raise SystemExit(main())