Skip to main content
 首页 » 编程设计

Python:当 for 循环完成多次时,如何打印语句

2025年05月04日9sharpest

我有一些代码主要围绕以下几行:

#! /usr/bin/env python 
 
from crypt import crypt 
import itertools 
from string import ascii_letters, digits 
 
def decrypt(all_hashes, salt, charset=ascii_letters + digits + '-' + '/'): 
    products = (itertools.product(charset, repeat=r) for r in range(10)) 
    chain = itertools.chain.from_iterable(products) 
    for i, candidate in enumerate(chain, 1): 
        if i % 100 == 0: 
            print ('%d th candidate: %s' % (i, candidate)) 
        hash = crypt(''.join(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 

该程序基本上是一种蛮力攻击,因为输出可能需要一段时间,所以我需要知道程序是仍在运行还是已经崩溃,所以我想有一个输出语句来说明有多少字符组合尝试过,也许上次尝试的字符串是什么,但不知道该怎么做。

在此先感谢您的帮助

请您参考如下方法:

使用enumerate 来计算候选人。

for i, candidate in enumerate(chain, 1): 
    if i % 100 == 0: 
        print("%d'th candidate: %s" % (i, candidate)) 
    # perform actual work