代码之家  ›  专栏  ›  技术社区  ›  Madushan Vitalii

Python Brute Force算法[已关闭]

  •  29
  • Madushan Vitalii  · 技术社区  · 12 年前

    我需要生成从给定字符集到给定范围的所有可能的组合。 喜欢

    charset=list(map(str,"abcdefghijklmnopqrstuvwxyz"))
    range=10
    

    结果应该是,

    [a,b,c,d..................,zzzzzzzzzy,zzzzzzzzzz]
    

    我知道我可以使用已经在用的库来做到这一点。但我需要知道它们是如何真正工作的。如果有人能给我一个用Python或任何可读编程语言编写的这种算法的注释代码,我将不胜感激。

    10 回复  |  直到 12 年前
        1
  •  60
  •   Martijn Pieters    7 年前

    使用 itertools.product 与…结合 itertools.chain 将各种长度组合在一起:

    from itertools import chain, product
    def bruteforce(charset, maxlength):
        return (''.join(candidate)
            for candidate in chain.from_iterable(product(charset, repeat=i)
            for i in range(1, maxlength + 1)))
    

    演示:

    >>> list(bruteforce('abcde', 2))
    ['a', 'b', 'c', 'd', 'e', 'aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee']
    

    这将有效地使用输入集生成逐渐变大的单词,最大长度可达maxlength。

    尝试在存储器中产生长度为10的26个字符的列表;相反,对生成的结果进行迭代:

    for attempt in bruteforce(string.ascii_lowercase, 10):
        # match it against your password, or whatever
        if matched:
            break
    
        2
  •  26
  •   Rob Volgman    12 年前

    如果你真的想强行使用它,试试这个,但它会花费你荒谬的时间:

    your_list = 'abcdefghijklmnopqrstuvwxyz'
    complete_list = []
    for current in xrange(10):
        a = [i for i in your_list]
        for y in xrange(current):
            a = [x+i for i in your_list for x in a]
        complete_list = complete_list+a
    

    在一个较小的例子中,list=“ab”,我们最多只能到达5,这将打印以下内容:

    ['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']
    
        3
  •  7
  •   Pandora Boz    8 年前

    我发现了另一种使用itertools创建字典的非常简单的方法。

    generator=itertools.combinations_with_replacement('abcd', 4 )
    

    这将遍历“a”、“b”、“c”和“d”的所有组合,并创建总长度为1到4的组合。即a、b、c、d、aa、ab。。。。。。。。。,dddc,dddd。generator是一个itertool对象,您可以像这样正常地循环,

    for password in generator:
            ''.join(password)
    

    每个密码都是元组类型的infact,您可以像往常一样使用它们。

        4
  •  4
  •   Rostan    5 年前

    如果你真的想要一个brueforce算法,不要在你的计算机内存中保存任何大列表,除非你想要一个会因MemoryError而崩溃的慢速算法。

    你可以试着这样使用itertools.product:

    from string import ascii_lowercase
    from itertools import product
    
    charset = ascii_lowercase  # abcdefghijklmnopqrstuvwxyz
    maxrange = 10
    
    
    def solve_password(password, maxrange):
        for i in range(maxrange+1):
            for attempt in product(charset, repeat=i):
                if ''.join(attempt) == password:
                    return ''.join(attempt)
    
    
    solved = solve_password('solve', maxrange)  # This worked for me in 2.51 sec
    

    itertools.product(*iterables) 返回您输入的可迭代项的笛卡尔乘积。

    [i for i in product('bar', (42,))] 退货,例如。 [('b', 42), ('a', 42), ('r', 42)]

    这个 repeat 参数允许您准确地做出您所要求的:

    [i for i in product('abc', repeat=2)]
    

    退货

    [('a', 'a'),
     ('a', 'b'),
     ('a', 'c'),
     ('b', 'a'),
     ('b', 'b'),
     ('b', 'c'),
     ('c', 'a'),
     ('c', 'b'),
     ('c', 'c')]
    

    笔记 以下为:

    你想要一个暴力算法,所以我给了你。现在,当密码开始变大时,这是一个非常长的方法,因为它呈指数级增长(花了62秒才找到“已解决”一词)。

        5
  •  3
  •   ecatmur    12 年前

    itertools 非常适合这样做:

    itertools.chain.from_iterable((''.join(l)
                                   for l in itertools.product(charset, repeat=i))
                                  for i in range(1, maxlen + 1))
    
        6
  •  3
  •   gnj    8 年前

    使用递归的解决方案:

    def brute(string, length, charset):
        if len(string) == length:
            return
        for char in charset:
            temp = string + char
            print(temp)
            brute(temp, length, charset)
    

    用法:

    brute("", 4, "rce")
    
        7
  •  2
  •   user2806040 user2806040    7 年前
    import string, itertools
    
        #password = input("Enter password: ")
    
        password = "abc"
    
        characters = string.printable
    
        def iter_all_strings():
            length = 1
            while True:
                for s in itertools.product(characters, repeat=length):
                    yield "".join(s)
                length +=1
    
        for s in iter_all_strings():
            print(s)
            if s == password:
                print('Password is {}'.format(s))
                break
    
        8
  •  1
  •   Community datashaman    4 年前

    使用itertools和字符串模块的简单解决方案

    # modules to easily set characters and iterate over them
    import itertools, string 
    
    # character limit so you don't run out of ram
    maxChar = int(input('Character limit for password: '))  
    
    # file to save output to, so you can look over the output without using so much ram
    output_file = open('insert filepath here', 'a+') 
    
    # this is the part that actually iterates over the valid characters, and stops at the 
    # character limit.
    x = list(map(''.join, itertools.permutations(string.ascii_lowercase, maxChar))) 
    
    # writes the output of the above line to a file 
    output_file.write(str(x)) 
    
    # saves the output to the file and closes it to preserve ram
    output_file.close() 
    

    我用管道将输出输出到一个文件中以保存ram,并使用输入函数将字符限制设置为“hiiworld”之类的值。下面是相同的脚本,但使用了字母、数字、符号和空格的更流畅的字符集。

    import itertools, string
    
    maxChar = int(input('Character limit for password: '))
    output_file = open('insert filepath here', 'a+')
    
    x = list(map(''.join, itertools.permutations(string.printable, maxChar)))
    x.write(str(x))
    x.close()
    
        9
  •  1
  •   Community datashaman    6 年前
    from random import choice
    
    sl = 4  #start length
    ml = 8 #max length 
    ls = '9876543210qwertyuiopasdfghjklzxcvbnm' # list
    g = 0
    tries = 0
    
    file = open("file.txt",'w') #your file
    
    for j in range(0,len(ls)**4):
        while sl <= ml:
            i = 0
            while i < sl:
                file.write(choice(ls))
                i += 1
            sl += 1
            file.write('\n')
            g += 1
        sl -= g
        g = 0
        print(tries)
        tries += 1
    
    
    file.close()
    
        10
  •  -2
  •   Madushan Vitalii    9 年前

    试试这个:

    import os
    import sys
    
    Zeichen=["a","b","c","d","e","f","g","h"­,"i","j","k","l","m","n","o","p","q­","r","s","­;t","u","v","w","x","y","z"]
    def start(): input("Enter to start")
    def Gen(stellen): if stellen==1: for i in Zeichen: print(i) elif stellen==2: for i in Zeichen:    for r in Zeichen: print(i+r) elif stellen==3: for i in Zeichen: for r in Zeichen: for t in Zeichen:     print(i+r+t) elif stellen==4: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in Zeichen:    print(i+r+t+u) elif stellen==5: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in    Zeichen: for o in Zeichen: print(i+r+t+u+o) else: print("done")
    
    #*********************
    start()
    Gen(1)
    Gen(2)
    Gen(3)
    Gen(4)
    Gen(5)