我想实现的Python一个simpley端口扫描工具。它通过创建大量工作线程来工作,这些工作线程扫描队列中提供的端口。他们将结果保存在另一个队列中。当扫描所有端口时,线程和应用程序应该终止。这里存在的问题是:对于少数端口一切正常,但如果我尝试扫描200个或更多的端口,应用程序将陷入僵局。我不知道为什么。死锁在Python线程
class ConnectScan(threading.Thread):
def __init__(self, to_scan, scanned):
threading.Thread.__init__(self)
self.to_scan = to_scan
self.scanned = scanned
def run(self):
while True:
try:
host, port = self.to_scan.get()
except Queue.Empty:
break
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.close()
self.scanned.put((host, port, 'open'))
except socket.error:
self.scanned.put((host, port, 'closed'))
self.to_scan.task_done()
class ConnectScanner(object):
def scan(self, host, port_from, port_to):
to_scan = Queue.Queue()
scanned = Queue.Queue()
for port in range(port_from, port_to + 1):
to_scan.put((host, port))
for i in range(20):
ConnectScan(to_scan, scanned).start()
to_scan.join()
有没有人看到什么可能是错的?另外,我会欣赏一些tipps如何在Python中调试这种线程问题。
你是对的,tast_done没有被经常调用。原因是如果你尝试连接到一个过滤的端口(即你不会得到任何响应),套接字不会抛出异常,而是永远等待。那是我的僵局。 – j0ker