批量密码解压zip脚本py

Posted by ... on 2026年11月04日

放在需要解压的zip文件线条目录下,适用于自己密码忘了,但密码比较多不知道哪一个,一个个试太麻烦。把自己知道的密码写到脚本里,批量自动解压

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# -*- coding: utf-8 -*-
"""
ZIP 多密码暴力尝试解压脚本
用法:
  1. 在下面 PASSWORDS_RAW 三引号之间填密码,每行一个,不用引号不用逗号
  2. 直接运行:  python unzip_brute.py
  3. 脚本会自动找当前目录下的 .zip 文件,逐个试密码
  4. 密码对了就自动解压到同名文件夹
"""

import os
import sys
import zipfile

# ============ 在下面两行之间填密码,每行一个,不用引号不用逗号 ============
PASSWORDS_RAW = """
12345678
223366
778899
QWE123
"""
# ==========================================================================

# 自动按行分割成密码列表(去掉空行和首尾空格)
PASSWORDS = [line.strip() for line in PASSWORDS_RAW.strip().splitlines() if line.strip()]


def find_zip_files():
    """查找当前目录下的所有 zip 文件"""
    zips = []
    for f in os.listdir("."):
        if f.lower().endswith(".zip") and os.path.isfile(f):
            zips.append(f)
    return zips


def try_extract(zip_path, password):
    """用指定密码尝试解压,返回 True/False"""
    try:
        with zipfile.ZipFile(zip_path, "r") as zf:
            # 尝试读取第一个文件来验证密码
            first = zf.namelist()[0]
            zf.read(first, pwd=password.encode("utf-8"))
        return True
    except RuntimeError as e:
        # 密码错误会抛 RuntimeError: Bad password
        if "Bad password" in str(e) or "password" in str(e).lower():
            return False
        # 其他错误(比如 AES 加密不支持)
        print(f"  [!] 读取异常: {e}")
        return False
    except Exception as e:
        print(f"  [!] 其他错误: {e}")
        return False


def extract_with_password(zip_path, password):
    """用正确密码解压全部文件"""
    # 解压目录 = zip 文件名去掉 .zip
    out_dir = os.path.splitext(zip_path)[0]
    os.makedirs(out_dir, exist_ok=True)

    with zipfile.ZipFile(zip_path, "r") as zf:
        zf.extractall(path=out_dir, pwd=password.encode("utf-8"))

    return out_dir


def main():
    print("=" * 50)
    print("  ZIP 多密码尝试解压工具")
    print("=" * 50)

    # 找 zip 文件
    zips = find_zip_files()
    if not zips:
        print("[x] 当前目录下没找到 .zip 文件")
        input("按回车退出...")
        return

    print(f"\n找到 {len(zips)} 个 zip 文件:")
    for i, z in enumerate(zips, 1):
        size = os.path.getsize(z) / 1024
        print(f"  {i}. {z}  ({size:.1f} KB)")

    # 选文件
    if len(zips) == 1:
        target = zips[0]
    else:
        choice = input("\n输入要解压的编号(默认 1): ").strip()
        idx = int(choice) if choice.isdigit() and 1 <= int(choice) <= len(zips) else 1
        target = zips[idx - 1]

    print(f"\n目标文件: {target}")
    print(f"密码列表: 共 {len(PASSWORDS)} 个密码")
    print("-" * 50)

    # 逐个试密码
    found = False
    for i, pwd in enumerate(PASSWORDS, 1):
        sys.stdout.write(f"  [{i:>3}/{len(PASSWORDS)}] 尝试: {pwd:<20} ... ")
        sys.stdout.flush()

        if try_extract(target, pwd):
            print(f"✓ 正确!")
            print("-" * 50)
            print(f"[+] 密码正确: {pwd}")

            # 解压
            out = extract_with_password(target, pwd)
            print(f"[+] 已解压到: {out}/")
            found = True
            break
        else:
            print("x 错误")

    print("-" * 50)
    if not found:
        print(f"[x] {len(PASSWORDS)} 个密码都试过了,没对上")
        print("    把新想到的密码加到脚本顶部 PASSWORDS 列表里再跑一次")

    input("\n按回车退出...")


if __name__ == "__main__":
    main()