How Can I Divide Work Read From A File To Threads?
I have a list of hosts and a list of ports. I want to run X threads that will grab a single host every time and try to connect to these ports. I got the connection part covered, my
Solution 1:
import concurrent.futures
MAX_THREAD_COUNT = 10defread_text_file(filename):
withopen(filename, "r") as f:
return f.read().splitlines()
defcheck_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. Code could be not 100% correct, I've not checked it "in action".
Post a Comment for "How Can I Divide Work Read From A File To Threads?"