2017-03-09 67 views
1

我正在创建一个简单的蛮力脚本,但我似乎无法弄清楚。我正在使用从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) 

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

任何帮助,将不胜感激!

+2

提示:什么是'attempt'的类型? – Kevin

回答

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!

+0

我得到的答案打印出来(谢谢!),但它仍然继续遍历整个笛卡尔,即使在我在末尾包括'break' – Goalieman

+0

@Goalieman:是的,我忘记了2'for'循环(并且你不能在python中使用'break 2')。我修改了一下答案,现在就试试。 –

+0

谢谢!它完美的工作! – Goalieman