我正在研究在带有4G内存的Ubuntu机器上运行的Python应用程序的问题.该工具将用于审核服务器(我们更喜欢使用自己的工具).它使用线程连接到许多服务器,并且许多TCP连接失败.但是,如果我在开始每个线程之间添加1秒的延迟,那么大多数连接都会成功.我用这个简单的脚本来调查可能发生的事情:
#!/usr/bin/python
import sys
import socket
import threading
import time
class Scanner(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.status = ""
def run(self):
self.sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sk.settimeout(20)
try:
self.sk.connect((self.host, self.port))
except Exception, err:
self.status = str(err)
else:
self.status = "connected"
finally:
self.sk.close()
def get_hostnames_list(filename):
return open(filename).read().splitlines()
if (__name__ == "__main__"):
hostnames_file = sys.argv[1]
hosts_list = get_hostnames_list(hostnames_file)
threads = []
for host in hosts_list:
#time.sleep(1)
thread = Scanner(host, 443)
threads.append(thread)
thread.start()
for thread in threads: …Run Code Online (Sandbox Code Playgroud)