蛮力脚本

时间:2017-03-09 20:41:52

标签: python-3.x brute-force

我正在创建一个简单的暴力脚本,但我似乎无法弄明白。我正在使用this question中接受的答案,但我无法“尝试”等于用户密码。下面是我使用的代码(来自链接的问题),并稍微改了一下。

from string import printable
from itertools import product

user_password = 'hi' # just a test password
for length in range(1, 10): # it isn't reasonable to try a password more than this length
    password_to_attempt = product(printable, repeat=length)
    for attempt in password_to_attempt:
        if attempt == user_password:
            print("Your password is: " + attempt)

我的代码只运行直到它到达笛卡尔结尾,并且从不打印最终答案。不知道发生了什么。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

itertools.product()为您提供元组的集合,而不是字符串。因此,您最终可能会得到结果('h', 'i'),但这与'hi'不同。

您需要将字母组合成一个字符串进行比较。此外,您应该在找到密码后停止该程序。

from string import printable
from itertools import product

user_password = 'hi' # just a test password
found = False

for length in range(1, 10): # it isn't reasonable to try a password more than this length
    password_to_attempt = product(printable, repeat=length)

    for attempt in password_to_attempt:
        attempt = ''.join(attempt) # <- Join letters together

        if attempt == user_password:
            print("Your password is: " + attempt)
            found = True
            break

    if found:
        break

Try it online!