import zipfile
import itertools
from concurrent.futures import ThreadPoolExecutor
def extract(file, password):
if not flag: return
file.extractall(path='.', pwd=''.join(password).encode('utf-8'))
def result(f):
exception = f.exception()
if not exception:
# 如果获取不到异常说明破解成功
print('密码为:', f.pwd)
global flag
flag = False
if __name__ == '__main__':
# 创建一个标志用于判断密码是否破解成功
flag = True
# 创建一个线程池
pool = ThreadPoolExecutor(100)
nums = [str(i) for i in range(10)]
chrs = [chr(i) for i in range(65, 91)]
# 生成数字+字母的6位数密码
password_lst = itertools.permutations(nums + chrs, 6)
# 创建文件句柄
zfile = zipfile.ZipFile("加密文件.zip", 'r')
for pwd in password_lst:
if not flag: break
f = pool.submit(extract, zfile, pwd)
f.pwd = pwd
f.pool = pool
f.add_done_callback(result)
然而,事情并没有那简单……代码跑一会儿,内存爆了!% }3 L: s- ~ c4 y9 R6 g
" V) U u$ } s; }2 Y" M
于是,为了找寻问题所在,我就去查看了一下源码,发现ThreadPoolExecutor默认使用的是**队列。而程序中尝试密码的速度跟不上生产密码的速度,就会把生产任务无限添加到队列中。导致内存被占满。内存直接飙到95:5 B6 u3 W7 x* Q4 E+ X2 m9 D 4 E$ i! Z2 g" ]0 n3 Q4 F 找到病根儿,剩下的就是对症下药了。继承并重写了ThreadPoolExecutor类中的_work_queue属性,将**队列改成有界队列,这样就不会出现内存爆满的问题,看代码: 5 t( ^# ]9 P6 v) w* N+ T1 |* ^6 t! x