Paramiko 不关闭 SSH 连接 - 多线程
Paramiko not closing SSH connections - Multithread
我正在使用 paramiko
启动 ssh
连接。看起来 运行 我的脚本一旦建立连接,它们就不会关闭。相反,直到 TIME_WAIT
在连接终止之前用完。我理解 TIME_WAIT
表示等待足够的时间过去以确保远程 TCP 收到其连接终止请求的确认。
这是我的代码:
#!/usr/local/bin/python2.7
import sys, os, string, threading
import paramiko
paramiko.util.log_to_file("paramiko.log")
cmd = "hostname"
outlock = threading.Lock()
def workon(host):
ssh = paramiko.SSHClient()
key = paramiko.RSAKey.from_private_key_file("./key")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='user', pkey=key)
stdin, stdout, stderr = ssh.exec_command(cmd)
with outlock:
result = stdout.readlines()
print "{0}".format(hostname[0])
ssh.close()
def main():
with open('./ip_list') as ip:
hosts = ip.read().splitlines()
threads = []
for h in hosts:
t = threading.Thread(target=workon, args=(h,))
t.start()
threads.append(t)
for t in threads:
t.join()
if __name__ == "__main__":
main()
也许这是正常行为,但我想确定一下。当 运行 这超过数百个 IP 地址时,脚本完成后有大量套接字在服务器上保持打开状态几分钟。
让我感到困惑的是套接字在连接时得到 ESTABLISHED
,然后转到 TIME_WAIT
- 即使我不调用 close()
方法。这是预期的行为吗?我什至不应该调用 close()
方法吗?有 "better" 方法吗?
TIME_WAIT
是您作为客户端在完全关闭连接时应该进入的状态。因此,你应该等待以确保对方'saw'你的FIN/ACK
。如果您没有调用 close()
就突然退出,清理时也会发生同样的情况。
直接使用套接字,您可以关闭连接并 'immediately' 释放资源(如果这是您想要的),但根据 documentation 不推荐这样做。实际上发生的是在套接字上调用 close()
并没有真正关闭套接字而是等待 GC 清理它。结果 RST/ACK
数据包被发送到另一端。因此它将继续使用资源,直到被 GC 关闭并且连接将无法正确关闭。
我正在使用 paramiko
启动 ssh
连接。看起来 运行 我的脚本一旦建立连接,它们就不会关闭。相反,直到 TIME_WAIT
在连接终止之前用完。我理解 TIME_WAIT
表示等待足够的时间过去以确保远程 TCP 收到其连接终止请求的确认。
这是我的代码:
#!/usr/local/bin/python2.7
import sys, os, string, threading
import paramiko
paramiko.util.log_to_file("paramiko.log")
cmd = "hostname"
outlock = threading.Lock()
def workon(host):
ssh = paramiko.SSHClient()
key = paramiko.RSAKey.from_private_key_file("./key")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='user', pkey=key)
stdin, stdout, stderr = ssh.exec_command(cmd)
with outlock:
result = stdout.readlines()
print "{0}".format(hostname[0])
ssh.close()
def main():
with open('./ip_list') as ip:
hosts = ip.read().splitlines()
threads = []
for h in hosts:
t = threading.Thread(target=workon, args=(h,))
t.start()
threads.append(t)
for t in threads:
t.join()
if __name__ == "__main__":
main()
也许这是正常行为,但我想确定一下。当 运行 这超过数百个 IP 地址时,脚本完成后有大量套接字在服务器上保持打开状态几分钟。
让我感到困惑的是套接字在连接时得到 ESTABLISHED
,然后转到 TIME_WAIT
- 即使我不调用 close()
方法。这是预期的行为吗?我什至不应该调用 close()
方法吗?有 "better" 方法吗?
TIME_WAIT
是您作为客户端在完全关闭连接时应该进入的状态。因此,你应该等待以确保对方'saw'你的FIN/ACK
。如果您没有调用 close()
就突然退出,清理时也会发生同样的情况。
直接使用套接字,您可以关闭连接并 'immediately' 释放资源(如果这是您想要的),但根据 documentation 不推荐这样做。实际上发生的是在套接字上调用 close()
并没有真正关闭套接字而是等待 GC 清理它。结果 RST/ACK
数据包被发送到另一端。因此它将继续使用资源,直到被 GC 关闭并且连接将无法正确关闭。