Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does paramiko close ssh connection on a non-paramiko exception

I'm debugging some code, which is going to result in me constantly logging in / out of some external sftp servers. Does anyone know if paramiko automatically closes a ssh / sftp session on the external server if a non-paramiko exception is raised in the code? I can't find it in the docs and as the connections have to be made fairly early in each iteration I don't want to end up with 20 open connections.

like image 389
Ben Avatar asked Aug 23 '11 10:08

Ben


People also ask

Does Paramiko use OpenSSH?

Paramiko relies on cryptography for crypto functionality, which makes use of C and Rust extensions but has many precompiled options available. See our installation page for details. SSH is defined in RFC 4251, RFC 4252, RFC 4253 and RFC 4254. The primary working implementation of the protocol is the OpenSSH project.

What does Paramiko do?

Paramiko is a Python library that makes a connection with a remote device through SSh. Paramiko is using SSH2 as a replacement for SSL to make a secure connection between two devices. It also supports the SFTP client and server model.

How do I give a timeout in Paramiko?

banner_timeout (float) – an optional timeout (in seconds) to wait for the SSH banner to be presented. auth_timeout (float) – an optional timeout (in seconds) to wait for an authentication response. disabled_algorithms (dict) – an optional dict passed directly to Transport and its keyword argument of the same name.


2 Answers

SSHClient() can be used as a context manager, so you can do

with SSHClient() as ssh:
   ssh.connect(...)
   ssh.exec_command(...)

and not close manually.

like image 138
Todor Buyukliev Avatar answered Sep 24 '22 15:09

Todor Buyukliev


No, paramiko will not automatically close the ssh / sftp session. It doesn't matter if the exception was generated by paramiko code or otherwise; there is nothing in the paramiko code that catches any exceptions and automatically closes them, so you have to do it yourself.

You can ensure that it gets closed by wrapping it in a try/finally block like so:

client = None
try:
    client = SSHClient()
    client.load_system_host_keys()
    client.connect('ssh.example.com')
    stdin, stdout, stderr = client.exec_command('ls -l')
finally:
    if client:
        client.close()
like image 40
aculich Avatar answered Sep 24 '22 15:09

aculich