我应该使用线程处理还是多处理来实现Python的暴力破解?

时间:2019-02-03 09:04:22

标签: python multithreading multiprocessing

前几天,我写了一个ZIP饼干;基于TJ O'Connor的书:暴力Python-黑客,法医分析师,渗透测试人员和安全工程师的食谱

现在,作者使用了线程,但是在Reddit上被告知,使用多处理会更好地实现暴力破解。真的吗?如果是,为什么,如何为该实例实现多重处理?

是否也可以将线程或多进程绑定到GPU而不是CPU?考虑到这样做不会使CPU窒息,并且不会利用GPU的潜力来进行工作,而这会缩短破解时间和每分钟尝试的时间,那么这样做会更加高效和有效。

我的代码如下(自从作者也使用线程以来,我一直在这里使用线程)

import argparse
from threading import Thread
import zipfile

parser = argparse.ArgumentParser(description="Unzips a password protected .zip by performing a brute-force attack using either a word list, password list or a dictionary.", usage="BruteZIP.py -z zip.zip -f file.txt")
parser.add_argument("-z", "--zip", metavar="", required=True, help="Location and the name of the .zip file.")  # Creates -z arg
parser.add_argument("-f", "--file", metavar="", required=True, help="Location and the name of the word list/password list/dictionary.")  # Creates -f arg
args = parser.parse_args()


def extract_zip(zip_file, password):
    try:
        zip_file.extractall(pwd=password)
        print("[+] Password for the .zip: {0}".format(password.decode("utf-8")) + "\n")
    except:
        pass  # If a password fails, it moves to the next password without notifying the user. If all passwords fail, it will print nothing in the command prompt.


def main(zip, file):
    if (zip == None) | (file == None):
        print(parser.usage)  # If the args are not used, it displays how to use them to the user.
        exit(0)
    zip_file = zipfile.ZipFile(zip)
    txt_file = open(file, "rb")  # Opens the word list/password list/dictionary in "read binary" mode.
    for line in txt_file:
        password = line.strip()
        t = Thread(target=extract_zip, args=(zip_file, password))
        t.start()


if __name__ == '__main__':
    main(args.zip, args.file)  # BruteZIP.py -z zip.zip -f file.txt.

总而言之,对于暴力破解而言,线程是更好还是多进程更好?是否可以将其中一个绑定到GPU而不是CPU?

1 个答案:

答案 0 :(得分:3)

我不知道如何将任务绑定到GPU而不是CPU。但是对于其他查询threadingmultiprocessing而言,您100%希望使用multiprocessing

强行强制是受CPU约束的任务,由于python有一个称为Global Interpreter Lock的东西,它仅允许一个受CPU约束的线程运行一次,因此您的应用程序将无法使用可能产生的多个线程。

但是,Multiprocessing并非如此,因为它同时启动了多个python解释器实例,您可以有效地将一个大任务分解为一堆较小的任务,并让每个python解释器实例运行该任务,然后再组合这些结果。

您可以通过运行一些CPU基准测试任务来自己测试一下,您会发现与顺序执行相比,线程根本没有任何区别,在多核系统中,线程甚至可能使性能恶化。

但是,通过多处理,您将清楚看到差异。

我故意不提供有关GIL的任何参考链接,因为有关该主题的文章有数百篇,您很可能会浏览其中的多篇文章,以了解GIL的工作原理以及它的好处以及后果。

尽管您可以查看David Beazly和Larry Hastings在此主题上进行的Pycon谈话,他们对这个主题有很好的见解。

相关问题