如何通过并行化加速Python Zip文件密码破解脚本?
Zip密码暴力破解并行化的正确实现方式
问题根源
你之前的并行尝试失败,核心原因有三个:
- 线程池不适合CPU密集型任务:Python的GIL(全局解释器锁)会限制同一时间只有一个线程执行CPU密集型代码,线程池反而会增加上下文切换开销,拖慢速度。
- 密码分配逻辑错误:用全局集合去重不仅存在线程安全问题(竞态条件导致重复判断),还额外消耗资源;且未实现任务分片分配,本质还是单线程生成密码再提交,没发挥并行优势。
- 未及时终止任务:找到密码后没有立即停止所有进程,导致无效计算持续运行。
正确实现方案
核心改进点
- 改用
ProcessPoolExecutor多进程池,绕过GIL充分利用多核CPU - 预先生成按长度分片的密码任务,每个进程独立处理一段密码空间,彻底避免重复尝试
- 实现密码破解成功后的全局终止逻辑,立即停止所有任务
完整代码
import zipfile import itertools import string import concurrent.futures import sys characters = string.ascii_letters + string.digits + '$#&*@' zip_file = "jl_update_file (1)" found_password = None def try_password(password): global found_password # 已找到密码则直接返回,避免无效计算 if found_password is not None: return None try: with zipfile.ZipFile(zip_file, 'r') as zf: # 用testzip()替代extractall(),仅验证密码无需解压,速度更快 zf.testzip(pwd=password.encode()) found_password = password print(f"\nPassword cracked: {password}") return password except Exception: # 取消频繁打印以减少IO开销,可按需添加进度打印逻辑 return None def generate_passwords(length): # 生成指定长度的所有密码组合,作为任务迭代器 return (''.join(comb) for comb in itertools.product(characters, repeat=length)) def crack_zip(): global found_password for length in range(6, 13): if found_password is not None: break print(f"\nTrying passwords of length {length}...") with concurrent.futures.ProcessPoolExecutor() as executor: # 批量提交密码验证任务 futures = [executor.submit(try_password, pwd) for pwd in generate_passwords(length)] # 遍历任务结果,找到密码后立即终止所有剩余任务 for future in concurrent.futures.as_completed(futures): result = future.result() if result is not None: for f in futures: if not f.done(): f.cancel() return if __name__ == "__main__": crack_zip() if found_password is None: print("\nPassword not found in the specified range.")
额外优化建议
- 优先使用字典攻击:如果有常用密码字典,优先遍历字典而非全组合暴力破解,效率提升显著。
- 自定义进程数:
ProcessPoolExecutor(max_workers=N)可指定进程数,建议设置为CPU核心数(os.cpu_count()),过多进程会增加调度开销。 - 进度优化:可添加计数器统计已尝试密码数,定时打印进度,避免频繁IO操作。
内容的提问来源于stack exchange,提问作者D J
相关产品推荐
相关产品推荐

