Python端口扫描程序,如何确定最佳线程数

时间:2016-06-05 13:29:34

标签: python multithreading port-scanning

我有一个多线程Python端口扫描程序,其中循环中的每个线程从公共队列中获取某些东西(IP地址/端口对),对它做一些工作(连接,握手和抓取服务器的版本)和再次循环。

这是一些部分代码:

import threading, queue, multiprocessing

class ScanProcess(multiprocessing.Process):
    threads = []

    def __init__(self, squeue, dqueue, count):
        self.squeue = squeue
        self.dqueue = dqueue
        self.count = count
        self._init_threads()
        super(ScanProcess, self).__init__()

    def _init_threads(self):
        self.threads = [ScanThread(self.squeue, self.dqueue) for _ in range(0, self.count)]

    def _start_threads(self):
        for thread in self.threads:
            thread.start()

    def _join_threads(self):
        for thread in self.threads:
            thread.join()

    def run(self):
        self._start_threads()
        self._join_threads()

class ScanThread(threading.Thread):
    def __init__(self, squeue, dqueue):
        self.squeue = squeue
        self.dqueue = dqueue
        super(ScanThread, self).__init__()

    def run(self):
        while not self.squeue.empty():
            try:
                target = self.squeue.get(block=False)
                # do the actual work then put the result in dqueue
            except queue.Empty:
                continue

# how many threads/processes
process_count = 2
thread_count = 10

# load tasks from file or network and fill the queues
squeue = multiprocessing.Queue()
dqueue = multiprocessing.Queue()

# create and start everything
processes = [ScanProcess(squeue, dqueue, thread_count) for _ in range(0, process_count)]

for process in processes:
    process.start()

for process in processes:
    process.join()

# enjoy the show!

我遇到的问题是当前手动设置了线程数。我想自动设置它以使网络连接饱和而不丢弃数据包,但我不知道如何开始实现它。任何人都可以总结一下nmap / zmap是如何做到的吗?

感谢任何帮助。

0 个答案:

没有答案