我正在编写用于检查SSH连接的简单脚本,但我不明白为什么它会挂在一个线程上。
class myThread(threading.Thread):
def __init__(self, hostname ):
threading.Thread.__init__(self)
self.hostname = hostname
def run(self):
return self.doSSH(self.hostname)
def doSSH(self,hostname):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, 22))
result = s.recv(1024)
if re.findall(r'^SSH.+?SSH.+',result) :
return "Up"
else :
return "Down"
def main():
q = Queue.Queue()
completeHostlist = ["host1","host2","google.com","host3"]
for hostname in completeHostlist:
thread = myThread(hostname)
thread.daemon = True
q.put_nowait(thread.run())
q.get_nowait()
我不明白为什么该脚本会挂在google.com上?我期望它产生守护程序线程并继续执行host3。一旦完成host3,它必须杀死与Google的线程并返回结果。我做错了什么?
我已经弄清楚了run()和start()。无论如何,这无法按预期工作,在启动所有host [1-3]线程之后,脚本被google困在了线程中,等待其结束。应该在脚本结尾处将其杀死吗?
我应该使用多处理而不是多线程来为每个主机生成单独的进程吗?
不要.run()
为任何线程直接调用方法。正如@Sorin所说,请致电thread.start()
。
您无需定义新的线程类,在这种情况下,一个函数就足够了:
from Queue import Queue
from threading import Thread
def is_ssh_up(result_queue, hostname, port=22):
# try to connect here
# ...
# write results
result_queue.put((hostname, True)) # Up
def main():
q = Queue()
hosts = ["host1", "host2", "google.com", "host3"]
for hostname in hosts: # start worker threads
t = Thread(target=is_ssh_up, args=[q, hostname])
t.daemon = True
t.start()
for _ in hosts: # collect results
hostname, is_up = q.get()
print("%s is %s" % (hostname, "Up" if is_up else "Down"))
或者您可以使用线程池:
from multiprocessing.pool import ThreadPool
def is_ssh_up(hostname, port=22):
# try to connect here
# ...
# return results
return hostname, is_up
hosts = ["host1", "host2", "google.com", "host3"]
pool = ThreadPool(20) # limit number of concurrent connections to 20
for hostname, is_up in pool.imap_unordered(is_ssh_up, hosts):
status = "Up" if is_up else "Down" if is_up is not None else "Unknown"
print("%s status is %s" % (hostname, status))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句