Reputation:
I am creating a simple brute force script, but I can't quite seem to figure it out. I am using the accepted answer from this question, but I can't get 'attempt' to equal the user password. Below is the code I have used (from the linked question), and changed it a little.
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)
My code just runs until it hits the end of the Cartesian, and never prints the final answer. Not sure what is going on.
Any help would be appreciated!
Upvotes: 1
Views: 3735
Reputation: 227270
itertools.product()
gives you a collection of tuples not strings. So, you may eventually get the result ('h', 'i')
, but this is not the same as 'hi'
.
You need to combine the letters into a single string to compare. Also, you should stop the program once you've found the password.
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
Upvotes: 1