带有for循环且没有itertools的蛮力脚本

时间:2020-07-01 23:07:23

标签: python loops brute-force

python的新手。在循环上工作。尝试在不使用就绪模块的情况下构建简单的暴力破解。 这是代码:

numbers=[1,2,3]
password_to_guess = [1,3]
x=', '.join(map(str, password_to_guess))
password = [0]
pass_len=3

for n in range (pass_len):  
    for i in numbers:
        password[n] = i
        print (password)
        i+=1
        y=', '.join(map(str, password))

    if x==y:
        print("stop")
        break
    else:
        password[n]=0
        password.append(0)

这是我得到的结果:

[1]
[2]
[3]
[0, 1]
[0, 2]
[0, 3]
[0, 0, 1]
[0, 0, 2]
[0, 0, 3]

无法弄清楚如何解决它,所以它会给我这个:

[1]
[2]
[3]
[1, 1]
[1, 2]
[1, 3]
[2, 1]
[2, 2]
[2, 3]
and so on to the pass_len

预先感谢

3 个答案:

答案 0 :(得分:0)

这是您要寻找的吗?

numbers=[1,2,3]
password = [0]
pass_len = 3

for i in numbers :
    password [0] = i
    print (password)
password.append (0)
for n in range (1, pass_len + 1) :
    password [0] = n
    for i in numbers :
        password [1] = i
        print (password)

答案 1 :(得分:0)

这是我想出的代码。使用生成器采用不同的方法,但是它将自动检查每个可能的解决方案。唯一的导入是sys,以在代码末尾转义嵌套循环。

import sys
numbers = (1,2,3)
password_to_guess = (1,3)

def permutations(iterable, r = None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

def perm_list():
    for i in range(len(numbers)):
        yield permutations(numbers , i)

perm_list = perm_list()

for i in perm_list:
    for j in i:
        if j == password_to_guess:
            print(f"{j} is the password")
            sys.exit()

答案 2 :(得分:0)

简单的朴素深度优先搜索递归函数。对于性能或长密码而言,效果不好。

通过获取列表并使用rec(list+[...each element in numbers])进行调用来工作,因此:
rec([])将依次
调用rec([] + [1]),
调用rec([1] + [1]),
调用rec([1,1] + [1]),
在[1,1,1]之后返回,因为已达到pass_len, 调用rec([1,1] + [2])... etc
如果达到长度,则表示在此分支中未找到密码,因此返回None
如果pwd(s)== x,则找到密码,返回pwd(s),然后一直返回备份树。

def pwd(p):
    return ', '.join(map(str, p))

numbers=[1,2,3]
password_to_guess = [1,3]
x = pwd(password_to_guess)
pass_len = 3

def rec(s):
    if pwd(s)==x: #password found, return password
        return s
    if len(s)==pass_len: #length reached, return Nothing
        return None
    for n in numbers:
        ret = rec(s+[n]) #call myself with n appended
        if ret!=None: #password found, return immediately
            return ret

print(pwd(rec([])))