【问题标题】:How to manage python memory?如何管理python内存?
【发布时间】:2020-05-19 20:32:21
【问题描述】:

我使用 python3 创建了一个蛮力程序,但在此过程中我总是遇到 MemoryError。一开始用户必须输入一个哈希算法(所有可能的算法都给出),然后用户必须选择一个字符模式并给出最小和最大可能的密码长度。然后代码使用选择的字符模式并尝试任何可能的组合,使用选择的算法对其进行散列,并将散列与用户的给定散列进行比较。如果它们相等,则代码给出使用该模式组合的密码。问题是,我的代码在密码长度为 5 处执行时崩溃。

错误代码:

Traceback (most recent call last):
  File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 122, in <module>
    main()
  File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 116, in main
    bruteforce(min, max, hash, hashfunction)
  File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 91, in bruteforce
    if bf_sha512(_, hash) is not None:
  File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 23, in bf_sha512
    passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)]
  File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 23, in <listcomp>
    passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)]
MemoryError

Process finished with exit code 1

出现错误的代码区域:

def bf_sha512(n, hash, chars):
    print(' ')
    print('Testing all possible passwords with ' + str(n) + ' characters... [' + str(int(chars.__len__())**n) + ']')
    time.sleep(1)
    with tqdm(total=int(chars.__len__())**n) as pbar:
        count = 0
        for password in [functools.reduce(operator.add, p) for p in itertools.product(chars, repeat=n)]:
            count += 1
            pbar.update(1)
            if hashlib.sha512(password.encode()).hexdigest() == hash:
                print('Needed attempts: ' + str(count))
                print(' ')
                print("Hash: " + hash)
                print("Passwort: " + password)
                pbar.close()
                return password
        pbar.close()
        return None

我什至试图删除所有装饰线,如进度条和计数,但它还是崩溃了。

【问题讨论】:

  • 该列表将是巨大的...您需要遍历 itertools.product 的结果而不创建其他列表
  • 您不需要“管理” Python 内存,但您不需要尝试使用代码尝试在内存中创建的数据来占用所有可用的操作系统内存。

标签: python memory memory-management list-comprehension brute-force


【解决方案1】:

导致此错误的行中的问题是从非常节省内存的生成器(一段代码在完成运行之前一次产生一个结果)到使用[] 的列表的转换functools.reduce(operator.add, p) for p in itertools.product(chars, repeat=n) 附近。

通过将其转换为列表,您可以使生成器将其所有值输出到一个列表中,该列表在 32 位机器上不能包含超过 536,870,912 个项目。当列表变大时,您会收到内存错误。

解决方法:删除[]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    相关资源
    最近更新 更多