我有一个主机列表和端口列表。我想运行X线程,每次都会抓住一个主机并尝试连接到这些端口。我覆盖了连接部件,我的问题是如何进行线程。当我进行一些研究时,我在螺纹,多销术和异步方面感到非常困惑。最佳和/或简单库是什么?
现在我的伪代码没有线程代码是:
def getHosts():
hosts = open("hostList.txt").read().splitlines()
return hosts
def getPorts():
ports = open("portList.txt").read().splitlines()
hosts = getHosts()
ports = getPorts()
for host in hosts
for port in ports
---the connection code---
我认为我的总体想法是列出列表的长度,除以线程数,并创建一个将从thread_number*result_of_divide运行的线程,直到(thread_number 1(*result_of_divide。
threadpoolexecutor。
import concurrent.futures
MAX_THREAD_COUNT = 10
def read_text_file(filename):
with open(filename, "r") as f:
return f.read().splitlines()
def check_port(host, port):
pass
hosts = read_text_file("hostList.txt")
ports = read_text_file("portList.txt")
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREAD_COUNT) as executor:
results = {}
for host in hosts:
for port in ports:
results[executor.submit(check_port, host, port)] = "{}:{}".format(host, port)
for result in concurrent.futures.as_completed(results):
host_and_port = results[result]
try:
returned_data = result.result()
except Exception as e:
print(""{}" exception have been caused while checking {}".format(e, host_and_port))
else:
print("Checking of {} returned {}".format(host_and_port, returned_data))
P.S。代码可能不是100%正确的,我没有在"行动"中检查它。