9

我有以下代码:

from crypt import crypt
from itertools import product
from string import ascii_letters, digits

def decrypt(all_hashes, salt, charset=ascii_letters + digits + "-"):
     products = (product(charset, repeat=r) for r in range(8))
     chain = itertools.chain.from_iterable(products)
     for candidate in chain:
         hash = crypt(candidate, salt)
         if hash in all_hashes:
              yield candidate, hash
              all_hashes.remove(hash)
              if not all_hashes:
                 return

all_hashes = ['aaRrt6qwqR7xk', 'aaacT.VSMxhms' , 'aaWIa93yJI9kU',
'aakf8kFpfzD5E', 'aaMOPiDnXYTPE', 'aaz71s8a0SSbU', 'aa6SXFxZJrI7E'
'aa9hi/efJu5P.', 'aaBWpr07X4LDE', 'aaqwyFUsGMNrQ', 'aa.lUgfbPGANY'
'aaHgyDUxJGPl6', 'aaTuBoxlxtjeg', 'aaluQSsvEIrDs', 'aajuaeRAx9C9g'
'aat0FraNnWA4g', 'aaya6nAGIGcYo', 'aaya6nAGIGcYo', 'aawmOHEectP/g'
'aazpGZ/jXGDhw', 'aadc1hd1Uxlz.', 'aabx55R4tiWwQ', 'aaOhLry1KgN3.'
'aaGO0MNkEn0JA', 'aaGxcBxfr5rgM', 'aa2voaxqfsKQA', 'aahdDVXRTugPc'
'aaaLf47tEydKM', 'aawZuilJMRO.w', 'aayxG5tSZJJHc', 'aaPXxZDcwBKgo'
'aaZroUk7y0Nao', 'aaZo046pM1vmY', 'aa5Be/kKhzh.o', 'aa0lJMaclo592'
'aaY5SpAiLEJj6', 'aa..CW12pQtCE', 'aamVYXdd9MlOI', 'aajCM.48K40M.'
'aa1iXl.B1Zjb2', 'aapG.//419wZU']


all_hashes = set(all_hashes)
salt = 'aa'
for candidate, hash in decrypt(all_hashes, salt):
     print 'Found', hash, '! The original string was', candidate

当我去运行它时,我得到以下回溯错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in decrypt
NameError: global name 'itertools' is not defined

并且无法弄清楚为什么会这样。

有人请阐明一下,在此先感谢

4

3 回答 3

17

好像不是进口itertools的。。。

from itertools import product

不算,因为那只会product直接拉入您模块的命名空间(您的模块仍然对其余部分一无所知itertools。只需添加:

import itertools

在脚本的顶部,该错误应该会消失,因为现在您已将itertools命名空间拉入模块的命名空间中,名为itertools. 换句话说,要访问该chain函数,您将使用itertools.chain(正如您在上面的脚本中所做的那样)。

于 2012-11-24T01:26:53.597 回答
4

你想要:

from itertools import chain, product

并使用chainand product,或:

import itertools

并使用itertools.chainitertools.product

于 2012-11-24T01:43:06.167 回答
2
import itertools

from itertools import izip_longest

这帮助我使用itertools然后能够izip_longest用于迭代不均匀长度的数组。

于 2016-03-17T03:04:17.810 回答