-1

I'm using this code to break an simple password mycubana, but I want to "pause" the itertools loop so that, after some time, I could resume the loop starting from the last saved itertools.product value. Is there any way to do it without change a lot of the code ?

Code:

import string
from itertools import chain, product

def bruteforce(charset, minlenght, maxlenght):
    return(''.join(candidate) 
          for candidate in chain.from_iterable(product(charset, repeat = i)
          for i in range(minlenght, maxlenght)))

contador = 0
for attempt in bruteforce(string.ascii_lowercase, 8, 9):
    codigo = 'mycubana'
    contador+=1
    if attempt==codigo:
        print(attempt)
        contador=0
Luís Eduardo
  • 52
  • 1
  • 6

1 Answers1

2

Yes, it's actually pretty simple. Using your environment and the definition of bruteforce, the following code will perform two runs of 10 candidates each on the generated sequence:

bf26_8 = bruteforce(string.ascii_lowercase, 8, 9)

count = 0

for c in bf26_8:
    count += 1
    print(c)
    if count == 10:
        break

print("======== PAUSED ========")

for c in bf26_8:
    count += 1
    print(c)
    if count == 20:
        break

The "trick" is to store the result of bruteforce in a variable. That result is a generator, so if you iterate on it, but do not exhaust it (i.e., break the iteration loop), it will give you the continuations values once you start iterating again.

Amitai Irron
  • 1,973
  • 1
  • 12
  • 14
  • But I would like to iterate a list of 26 characters up to length 10 and it will die out of memory before it completes, like this one post: https://stackoverflow.com/questions/11747254/python-brute-force-algorithm – Luís Eduardo May 12 '20 at 18:32
  • 1
    I edited the answer to show you that no explosion will happen. Generators (I added a link in the answer) do not create the entire result sequence upfront, but are a objects enabling the **serial** generation of a sequence, by maintaining the code to generated it and some context (e.g., program instruction pointer and values of local variables). – Amitai Irron May 12 '20 at 18:48