【问题标题】:Is it possible to parallelize this loop in python?是否可以在 python 中并行化这个循环?
【发布时间】:2018-10-16 13:13:27
【问题描述】:

我一直在开发一个程序来获取 rainbow table,使用 crc32 哈希。

程序的主循环如下:

from zlib import crc32
from string import ascii_lowercase
from itertools import product

...

rt = {}
i = 0
for p in product(ascii_lowercase, repeat = 8):
    i += 1
    print('\n%d' % i)
    p = ''.join(p)
    print('\nCurrent password = %s' % p)
    r = bytes(p, 'utf-8')
    h = hex(crc32(r))
    for j in range(2**20):
        h = list(h)
        del h[0]
        del h[0]
        for k in range(0, len(h)):
            if (h[k].isdigit()):
                h[k] = chr(ord(h[k]) + 50)
        h = ''.join(h)
        r = bytes(h, 'utf-8')
        h = hex(crc32(r))
    h = list(h)
    del h[0]
    del h[0]
    h = ''.join(h)
    print('\nFinal hash = %s\n' % h)
    rt[p] = h
    if (i == 2**20):
        break

因此,代码按照我的预期工作,当它退出循环时,它将生成的彩虹表(变量 rt)存储到内存中。好吧,以上面代码中显示的当前迭代次数,完成它的执行需要几天时间,我需要创建这个表,以及通过循环进行不同迭代的其他表,以便对他们。

我认为尝试并行化它是一个好主意,但是在阅读了 multiprocessing 上的文档并潜伏在一些关于它的帖子之后,我仍然无法以正确的方式并行化它。

提前致谢!

【问题讨论】:

  • 将最外层for循环的内容放入一个函数中(除了第一行和最后三行),取p并返回(p, h)。创建一个Pool 并将其map_asyncimap_unorderedproduct(...) 一起用作新创建函数的可迭代输入。
  • 对不起,迈克尔,但根据您的建议,我只能提出以下建议:with Pool(4) as pool: print(pool.map_async(table, (product(ascii_lowercase, repeat = 8)))) 其中 table 是您建议的功能。这样做我只差点让我的机器崩溃,所以我请你给我看一个你的建议的代码示例。谢谢。

标签: python parallel-processing cryptography crc32


【解决方案1】:

试试这个:

from zlib import crc32
from string import ascii_lowercase
from itertools import product
from multiprocessing.pool import Pool

def table(p):
    p = ''.join(p)
    r = bytes(p, 'ascii')
    h = hex(crc32(r))
    for j in range(2**20):
        h = list(h)
        del h[0]
        del h[0]
        for k in range(0, len(h)):
            if (h[k].isdigit()):
                h[k] = chr(ord(h[k]) + 50)
        h = ''.join(h)
        r = bytes(h, 'ascii')
        h = hex(crc32(r))
    h = list(h)
    del h[0]
    del h[0]
    h = ''.join(h)

    return (p, h)

if __name__ == "__main__":
    rt = {}
    i = 0
    with Pool(4) as pool:
        for p, h in pool.imap_unordered(table, product(ascii_lowercase, repeat = 8)):
            print('\n%d' % i)
            print('\nCurrent password = %s' % p)
            print('\nFinal hash = %s\n' % h)
            i += 1
            rt[p] = h
            if i == 2**20:
                break

请注意,由于计算任务的任意顺序,最终中断条件 i == 2**20 可能会不准确。

【讨论】:

  • 它运行得很好,而且速度更快,非常感谢!我的错误在于我如何在 pool.imap_unordered 中传递参数。我真的很感谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多