Paramiko not closing SSH connections - Multithread
<p>I am using <code>paramiko</code> to initiate <code>ssh</code> connections. It would appear that when running my script that once the connections have been made, they do not get closed. Instead, it takes until <code>TIME_WAIT</code> runs out before the connections are terminated. I understand that <code>TIME_WAIT</code> represents waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request. </p>

<p>Here is my code:</p>

<pre><code>#!/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()
</code></pre>

<p>Perhaps this is normal behavior but I wanted to be certain. When running this over hundreds of IP addresses, there are a ton of sockets that stay open on the server for several minutes after the script is done.</p>

<p>What confuses me is that the sockets get <code>ESTABLISHED</code> when connecting, and go to <code>TIME_WAIT</code> after - even if I don't call the <code>close()</code> method. Is this expected behavior? Should I not even bother with calling the <code>close()</code> method? Is there "better" way to do this?</p>