我有一些旧的RAR文件,我知道我经常使用的密码的一般格式,所以我以多种方式生成了一个结合这些单词的字典文件。字典文件是500 to,我编写了一个python程序来使用字典。
问题是,这个程序已经运行了一整晚,而且只有1%的速度。我现在已经将字典文件分割起来,我现在正在运行程序的多个实例,但是每个实例运行得非常慢。
我想听听关于如何提高速度的任何建议。我对Python非常陌生,这在我的代码中是显而易见的(但我真的很喜欢Python)。
import itertools
import sys, traceback
import os
with open('dictionary.txt') as infile:
words = [line.strip() for line in infile]
for word1 in itertools.product(words, repeat=1):
fword = word1[0]
print "Attempting: " + fword
# open unrar and test password
output = os.popen("unrar.exe x protected.rar -p" + fword)
outstring = output.read()
slng = len(outstring)
# unrar.exe returns "All OK" for correct password
validate = outstring.find("All OK", 0, slng)
if validate != -1:
print "Found password: " + fword
with open('correct_password.txt', 'w') as outfile:
outfile.write(fword)
sys.exit(0)
else:
# continue searching
print "invalid password"
raw_input("Password was not in this dictionary!")样本dictionary.txt
FableLand
FableWay
FableTree
FableSpirit
FableApple发布于 2014-04-19 11:23:02
我被认为是一个性能关注点的底线是这样的:
words = [line.strip() for line in infile]您正在生成一个包含dictionary.txt中每个单词的列表。这意味着一个500 MB的字典文件将创建一个类似的大列表(这将是一个巨大的结构)。这也意味着,如果密码在列表的早期,那么整个文件仍然是内存中的一个列表。
后面跟着行
for word1 in itertools.product(words, repeat=1):
fword = word1[0]我不太清楚你为什么要用这种方式表达出来。当您通过itertools.product时,您将得到元组,并且需要取出第一个元素。使用可迭代通常对性能有好处,但问题是首先创建列表,而不是迭代。
如何在Python中逐行读取大文件中的建议在这里很有帮助。考虑将您的文件读取为
with open('dictionary.txt') as f:
for line in f:
# try that line as your password这可能会带来明显的好处。
其他评论:
dictionary.txt获得可迭代密码的代码。例如: def try_password( fword,rar_file):打印“outstring:%s”%fword# open unrar并测试密码输出= os.popen("unrar.exe x %s -p %-p‘% (fword,rar_file)“%(fword,rar_file)),outstring= output.read() # unrar.exe返回"All OK”以获得正确的密码验证= outstring.find("All OK",0,如果验证!= -1:打印“查找密码:%s”% fword返回0:#继续搜索返回1,并打开(‘dictionary.txt’)作为f: for行f: line.strip= try_password(line.strip(),'protected.rar')如果尝试== 0:protected.rar,现在也可以使用相同的代码来处理密码,比如说,一堆加密的ZIP文件。我添加了返回代码0和1,以表示在尝试密码时成功和失败。slng变量代表什么?不管怎么说,它只用了一次,所以我把它移走了。我还做了一些其他的调整,但没什么特别大的。import sys, traceback语句实际上应该分成两行。引用PEP 8的话,Python指南:导入通常应该放在单独的行上raw_input而不是print语句?dictionary.txt到底是从哪里来的?您说是您“生成”了它,所以您是否可以绕过将密码写入文件并直接在生成器中进行尝试的步骤?https://codereview.stackexchange.com/questions/47640
复制相似问题