Itertool的Python内存错误

时间:2019-01-20 18:38:38

标签: python-3.x performance memory optimization itertools

我有一个小的Bruteforce计划要上学。 我已经编写了一个程序,但是当我运行代码时,出现“内存错误” ... 这是我的IDE发出的消息:

  

passwords = [''.join(word)for itertools.product中的单词(字母,重复= CharLength)]   MemoryError

我想大多数错误是由于我如何使用循环号? 作为菜鸟,我永远不会遇到这种类型的错误...我给了您1条信息,我正在Windows上运行我的代码

如何优化我的代码以及如何修复?     这是我的代码:

import hashlib
import itertools


#possible characters in user password
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@")
#minimum password value
CharLength = 6

#getting passwords and username from shadow file
with open("shadow_test", "r") as ins:
    array = []
    users = []
    passwd = []
    #getting everyline from shadow file into an array
    for line in ins:
        array.append(line)
    #saving only username and passwords
    for pw in array:
        str(pw)
        r= pw.split(":")
        users.append(r[0])
        passwd.append(r[1])

    list = []
    #removing passowrd with * or !
    for mdp in passwd:
        if mdp != '*' and mdp != '!':
            str(mdp)
            list.append(mdp)
            # trying to Bruteforce
            for _ in range(12):
                passwords = [''.join(word) for word in itertools.product(Alphabet, repeat=CharLength)]

                print(*passwords)
                for pswd in passwords:
                    hash_object = hashlib.md5(str.encode(pswd)).hexdigest()
                    # hash_object.update(*passwords.encode('utf-8'))
                    generatedpassword = '$1$' + hash_object

                    for compare in list:
                        for user in users:
                            #print('on cherche le Mot de passe : ' + compare +' pour ' +user)
                            #print('mot de passe MD5 généré : ' +generatedpassword)
                            #print('mot de passe clair généré : ' +pswd)


                            if generatedpassword == list:
                                print('Le Mot de passe pour' + user + ' est : ' + compare)

2 个答案:

答案 0 :(得分:1)

passwords = [''.join(word) for word in itertools.product(Alphabet, repeat=CharLength)]

您在这里创建的列表长度超过50 ** 6。当然,您会遇到内存错误。改用发电机:

passwords = (''.join(word) for word in itertools.product(Alphabet, repeat=CharLength))

答案 1 :(得分:0)

password列表本身将有大约1000亿个条目,因此您将需要1 TB以上的内存才能容纳它。与其将其作为列表,不如将其作为生成器以供以后循环使用:

passwords = (''.join(word) for word in itertools.product(Alphabet, repeat=CharLength))

(尽管有1000亿个条目,您可能会等待一会儿。)