Close ssh connections when done with them

Newer paramiko leaks connections if they are not explicitly closed. Add
a finally handler to always close the ssh connections when we are done
with it to avoid leaking these connections.

Change-Id: Ia2e53998d362683a42bda074d82e3a3a75f380b4
This commit is contained in:
Clark Boylan 2018-05-03 13:38:57 -07:00
parent 01a634014e
commit 2de58d560f

View File

@ -396,25 +396,29 @@ class Gerrit(object):
return data return data
def _ssh(self, command): def _ssh(self, command):
client = paramiko.SSHClient() try:
client.load_system_host_keys() client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy()) client.load_system_host_keys()
client.connect(self.hostname, client.set_missing_host_key_policy(paramiko.WarningPolicy())
username=self.username, client.connect(self.hostname,
port=self.port, username=self.username,
key_filename=self.keyfile) port=self.port,
key_filename=self.keyfile)
self.log.debug("SSH command:\n%s" % command) self.log.debug("SSH command:\n%s" % command)
stdin, stdout, stderr = client.exec_command(command) stdin, stdout, stderr = client.exec_command(command)
out = stdout.read() out = stdout.read()
self.log.debug("SSH received stdout:\n%s" % out) self.log.debug("SSH received stdout:\n%s" % out)
ret = stdout.channel.recv_exit_status() ret = stdout.channel.recv_exit_status()
self.log.debug("SSH exit status: %s" % ret) self.log.debug("SSH exit status: %s" % ret)
err = stderr.read() err = stderr.read()
self.log.debug("SSH received stderr:\n%s" % err) self.log.debug("SSH received stderr:\n%s" % err)
finally:
if client:
client.close()
if ret: if ret:
raise Exception("Gerrit error executing %s" % command) raise Exception("Gerrit error executing %s" % command)
return (out, err) return (out, err)