Восстановить повреждённый zip
Собирает новый архив из читаемых файлов и умеет вытаскивать данные из битого центрального каталога.
Что делает скрипт
Сначала скрипт пробует штатное чтение zip и переносит уцелевшие элементы в новый архив. Если центральный каталог разрушен, включается сканер локальных заголовков, который восстанавливает файлы, сжатые методами stored и deflate. Повреждённые и зашифрованные элементы пропускаются, исходный файл не изменяется.
- Новый архив создаётся только с флагом --apply.
- Зашифрованные элементы восстановить нельзя.
Быстрый старт
python repair_zip.py broken.zip --apply
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python repair_zip.py broken.zippython repair_zip.py broken.zip --applypython repair_zip.py broken.zip --apply --output recovered.zip
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
repair_zip.py
#!/usr/bin/env python3
"""Восстановление повреждённого zip."""
from __future__ import annotations
import argparse
import mmap
import struct
import zipfile
import zlib
from pathlib import Path, PurePosixPath, PureWindowsPath
LOCAL = b"PK\x03\x04"
CENTRAL = b"PK\x01\x02"
def safe_name(name: str) -> str | None:
normalized = name.replace("\\", "/")
path = PurePosixPath(normalized)
if path.is_absolute() or PureWindowsPath(normalized).drive:
return None
parts = [part for part in path.parts if part not in ("", ".")]
if not parts or any(part == ".." for part in parts):
return None
return "/".join(parts)
def dos_datetime(date: int, time: int) -> tuple[int, int, int, int, int, int]:
year = ((date >> 9) & 0x7F) + 1980
month = (date >> 5) & 0x0F
day = date & 0x1F
hour = (time >> 11) & 0x1F
minute = (time >> 5) & 0x3F
second = (time & 0x1F) * 2
if not (1 <= month <= 12 and 1 <= day <= 31 and hour < 24 and minute < 60 and second < 60):
return (1980, 1, 1, 0, 0, 0)
return (year, month, day, hour, minute, second)
def read_with_zipfile(path: Path) -> tuple[list[tuple[str, bytes, tuple]], list[tuple[str, str]]]:
recovered = []
failed = []
with zipfile.ZipFile(path) as archive:
for info in archive.infolist():
name = safe_name(info.filename)
if name is None:
failed.append((info.filename, "небезопасное имя"))
continue
if info.flag_bits & 0x1:
failed.append((info.filename, "зашифрован"))
continue
try:
if info.is_dir():
recovered.append((name.rstrip("/") + "/", b"", info.date_time))
else:
with archive.open(info) as handle:
recovered.append((name, handle.read(), info.date_time))
except (RuntimeError, zipfile.BadZipFile, OSError) as error:
failed.append((info.filename, str(error)))
return recovered, failed
def scan_local_headers(data, failed: list[tuple[str, str]]) -> list[tuple[str, bytes, tuple]]:
recovered = []
seen = set()
position = 0
while True:
position = data.find(LOCAL, position)
if position < 0 or position + 30 > len(data):
break
fields = struct.unpack_from("<HHHHHIIIHH", data, position + 4)
_, flags, method, mtime, mdate, crc, comp_size, uncomp_size, name_len, extra_len = fields
name_start = position + 30
name_end = name_start + name_len
if name_end + extra_len > len(data):
break
raw_name = bytes(data[name_start:name_end])
try:
name = raw_name.decode("utf-8" if flags & 0x800 else "cp437")
except UnicodeDecodeError:
name = raw_name.decode("utf-8", errors="replace")
start = name_end + extra_len
if flags & 0x1:
failed.append((name, "зашифрован"))
position = start
continue
content = None
consumed = 0
if method == 0:
size = comp_size if comp_size not in (0, 0xFFFFFFFF) else uncomp_size
if start + size > len(data):
break
content = bytes(data[start:start + size])
consumed = size
elif method == 8:
if comp_size not in (0, 0xFFFFFFFF):
raw = bytes(data[start:start + comp_size])
try:
content = zlib.decompress(raw, -15)
consumed = comp_size
except zlib.error:
content = None
else:
bounds = [value for value in (data.find(LOCAL, start), data.find(CENTRAL, start)) if value != -1]
end = min(bounds) if bounds else len(data)
decompressor = zlib.decompressobj(-15)
try:
content = decompressor.decompress(bytes(data[start:end]))
if decompressor.eof:
consumed = (end - start) - len(decompressor.unused_data)
else:
content = None
except zlib.error:
content = None
else:
failed.append((name, f"метод сжатия {method} не поддержан"))
if content is not None:
safe = safe_name(name)
if safe is None:
failed.append((name, "небезопасное имя"))
elif safe not in seen:
seen.add(safe)
if crc and (zlib.crc32(content) & 0xFFFFFFFF) != crc:
failed.append((name, "CRC не совпал, данные сохранены"))
recovered.append((safe, content, dos_datetime(mdate, mtime)))
position = start + consumed if consumed else start
if bytes(data[position:position + 4]) == b"PK\x07\x08":
position += 12
return recovered
def write_archive(entries: list[tuple[str, bytes, tuple]], output: Path) -> None:
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as target:
for name, content, date_time in entries:
info = zipfile.ZipInfo(name, date_time)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o600 << 16
target.writestr(info, content)
def main() -> int:
parser = argparse.ArgumentParser(description="Восстановить повреждённый zip")
parser.add_argument("archive", type=Path, help="Повреждённый zip")
parser.add_argument("--output", type=Path, help="Новый архив")
parser.add_argument("--apply", action="store_true", help="Записать восстановленный архив")
parser.add_argument("--force", action="store_true", help="Перезаписать выходной файл")
args = parser.parse_args()
source = args.archive.expanduser().resolve()
if not source.is_file():
parser.error(f"Файл не найден: {source}")
output = (args.output or source.with_name(f"{source.stem}.repaired.zip")).expanduser().resolve()
if output == source:
parser.error("Выходной файл должен отличаться от исходного")
if output.exists() and not args.force:
parser.error(f"Файл уже существует: {output}. Используйте --force")
failed: list[tuple[str, str]] = []
try:
recovered, failed = read_with_zipfile(source)
mode = "central directory"
except (zipfile.BadZipFile, OSError):
with source.open("rb") as handle:
if source.stat().st_size == 0:
print("Файл пуст.")
return 1
with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as data:
recovered = scan_local_headers(data, failed)
mode = "local headers"
print(f"Режим: {mode}, восстановлено: {len(recovered)}, пропущено: {len(failed)}")
for name, reason in failed[:30]:
print(f" пропуск {name}: {reason}")
if not recovered:
print("Восстановить не удалось.")
return 1
for name, content, _ in recovered[:20]:
print(f" {name} ({len(content)} байт)")
if len(recovered) > 20:
print(f" и ещё {len(recovered) - 20}")
if not args.apply:
print("Режим проверки: добавьте --apply для записи нового архива.")
return 0
write_archive(recovered, output)
with zipfile.ZipFile(output) as check:
bad = check.testzip()
if bad is not None:
print(f"Новый архив не прошёл проверку: {bad}")
return 1
print(f"Готово: {output} ({output.stat().st_size / 1024 / 1024:.1f} МБ)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.