from unrar import rarfile
import os
import itertools as its
import time
from multiprocessing import Pool
import queue
import threading
def get_pwd(file_path, output_path, pwd):
'''
判断密码是否正确
:param file_path: 需要破解的文件路径,这里仅对单个文件进行破解
:param output_path: 解压输出文件路径
:param pwd: 传入的密码
:return:
'''
try:
# 传入被解压的文件路径,生成待解压文件对象
file = rarfile.RarFile(file_path, pwd=pwd)
# 输出解压后的文件路径
out_put_file_path = output_path
# print(file_path,output_path)
file.extractall(output_path)
# 如果发现文件被解压处理,移除该文件
# os.remove(out_put_file_path)
# 说明当前密码有效,并告知
print('Find password is "{}"'.format(pwd))
return True, pwd
except Exception as e:
# 密码不正确
print('"{}" is not correct password!'.format(pwd))
# print(e)
return False, pwd
def get_password(min_digits, max_digits, words):
"""
密码生成器
:param min_digits: 密码最小长度
:param max_digits: 密码最大长度
:param words: 密码可能涉及的字符
:return: 密码生成器
"""
while min_digits <= max_digits:
pwds = its.product(words, repeat=min_digits)
for pwd in pwds:
yield ''.join(pwd)
min_digits += 1
if __name__ == "__main__":
file_path = os.path.dirname(os.path.abspath('.'))+'\\rar\\Desktop.rar'
output_path = os.path.dirname(os.path.abspath('.'))+"\\api\\rar\\"
# 密码范围
words = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # 涉及到生成密码的参数
# words = '12345'
pwds = get_password(4, 4, words)
# 开始查找密码
start = time.time()
# judge = []
result = queue.Queue(maxsize=10) # 队列
pool = Pool()
def pool_th():
while True: ##这里需要创建执行的子进程非常多
pwd = next(pwds)
try:
# 进程添加到容器
result.put(pool.apply_async(get_pwd, args=(file_path, output_path, pwd)))
except:
break
def result_th():
while True:
# 容器中获取子进程返回值
a = result.get().get()
print(a)
if a[0]:
# print(pwd)
pool.terminate() # 结束所有子进程
break
'''
利用多线程,同时运行Pool函数创建执行子进程,以及运行获取子进程返回值函数。
'''
t1 = threading.Thread(target=pool_th)
t2 = threading.Thread(target=result_th)
t1.start()
t2.start()
t1.join()
t2.join()
pool.join()
end = time.time()
print('程序耗时{}'.format(end - start))