首页 > 解决方案 > 如何在 Python 中使嵌套循环更快更短

问题描述

我正在用 Python 构建一个密码破解程序:

Python

import string

chars = string.ascii_lowercase + string.ascii_uppercase + string.digits

user_passw = input("enter pass")


for char1 in chars:
    for char2 in chars:
        for char3 in chars:
            for char4 in chars:
                for char5 in chars:
                    if (char1 + char2 + char3 + char4 + char5) == user_passw:
                        print("its " + char1 + char2 + char3 + char4 + char5)
                        exit()

我怎样才能使这个 5d 循环更快或更短。我的目标是猜测一个 12 个字符的密码,如果我进行 12d 循环,我的 PC 无法处理,或者速度太慢。

标签: pythonpython-3.xpasswords

解决方案


只需使用 itertools:

import itertools
import string

chars = string.ascii_lowercase + string.ascii_uppercase + string.digits

user_passw = input("Enter Your Password: ")

for password_length in range(1, 9):
    for guess in itertools.product(chars, repeat=1):
        guess = ''.join(guess)
        if guess == user_passw:                
            print('Password Is {}'.format(guess))
            exit()

第一个循环尝试暴力破解长度为 1 到 9 的密码。第二个循环尝试来自字符的每个组合。


推荐阅读