2

I'm having trouble trying to close a Paramiko SFTP connection. Even though I call close the connection is still hanging, I check by running netstat (Windows):

netstat -an | find ":22"

and the python code:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy() )
ftp = ssh.open_sftp()
time.sleep(5)
ftp.close()

What is the proper way to close Paramiko SFTP connection that works?

thanks

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
RollRoll
  • 8,133
  • 20
  • 76
  • 135

2 Answers2

3

SSHClient.open_sftp opens a virtual SFTP channel within a SSH connection. You can have multiple channels in a single SSH connection. Hence closing a single channel, won't close whole SSH connection.

You need to call SSHClient.close to close the physical SSH connection (it takes all channels down with it, if any are still open).

ssh.close()

Obligatory warning: Do not use MissingHostKeyPolicy to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks.

For a correct (and secure) approach, see: Paramiko "Unknown Server".

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

This is the correct way to go about it

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect()

ftp = ssh.open_sftp()

ftp.close()
ssh.close()

You need to close the ssh instance as well as the sftp.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
ltd9938
  • 1,444
  • 1
  • 15
  • 29