A..
A..

Reputation: 375

Brute Force Hacker Concept in Python 3

The code that i currently have will list all possible combinations

from itertools import product

password = "hr"

chars = 'abcdefghijklmnopqrstuvwxyz' #characters to look for, can have letters added

for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
    to_attempt = product(chars, repeat=length)
    for attempt in to_attempt:
        print(''.join(attempt))

What i need it to do is take each tried attempt and compare it with the variable "password", if it matches break out of the for loop else carry on, any ideas?

Upvotes: 1

Views: 221

Answers (1)

furkle
furkle

Reputation: 5059

One thing you could do to solve this would be to move your whole for length in range code block into a function:

def brute_force(chars, password):
    for length in range(1, 3): #only do lengths of 1 + 2 - namely from aa - zz not onto aaa
        to_attempt = product(chars, repeat=length)
        for attempt in to_attempt:
            if ''.join(attempt) == password:
                print("Found the password!")
                return

The problem you're having is that you can only break out of a single loop. There's no built-in solution to say "break out of this loop, and its parent, and nothing else." I find that if you're unable to be using break or continue to move your control flow in the desired direction, just break it off into a function and use return.

This isn't really a problem, necessarily, but chars you're using right now will only ever be able to brute-force an all-letters, all-lower-case string, so it'll go through every single attempt and fail if the password is "Hr".

Upvotes: 1

Related Questions