0

我有一个多线程 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 是如何做到的?

任何帮助表示赞赏。

4

0 回答 0