多线程蛮力脚本python

时间:2019-12-15 15:08:27

标签: python python-3.x multithreading python-multithreading brute-force

因此,我正在python3中编写此蛮力脚本,它工作正常,但运行起来非常缓慢,这两者都是因为python不太适合此功能,并且因为我不知道如何实现多线程。我之所以创建这个脚本,是因为我对道德黑客感兴趣,并且我想看看多线程如何使其更好。 因此,代码的有趣部分是:

def bruto(charset1, maxlength1):
   return(''.join(candidate) for candidate in  chain.from_iterable(product(charset, repeat=i) for i in range(1, maxlength + 1)))

for guess1 in bruto(charset,maxlength):
    guess_hash1 = getattr(hashlib, algorithm)(bytes(guess1, 'utf-8')).hexdigest()

如何实现多线程?在此先感谢您,并感谢您的无礼

1 个答案:

答案 0 :(得分:1)

将线程与cpu绑定的任务一起使用将使您的应用程序变慢,原因是 global interpreter lock。您应该改用multiprocessing

最简单的方法是使用ProcessPoolExecutor计算哈希值

from concurrent.futures.process import ProcessPoolExecutor

def get_hash(guess):
    return guess, getattr(hashlib, algorithm)(bytes(guess, "utf-8")).hexdigest()

with ProcessPoolExecutor(max_workers=4) as executor:
    guesses = bruto(charset, maxlength)
    all_hashes = executor.map(get_hash, guesses)

请记住,由于IPC开销,这也可能会使您的应用程序:)变慢。如果单个get_hash太快,则可以在executor.map(chunksize=100)

中设置更大的块大小

Python并行性充满了惊奇:)