Search code examples
pythonsshsftpparamiko

Detect connection close event in Python Paramiko


How to detect when the connection closed by any reason? Is there any event/callback to this? Below are my partial working code to connect to SFTP:

def connect(self, Host, Username, Password, Keyfilepath, Keyfiletype, Port=22):
   self.transport = paramiko.Transport((Host, Port))
   self.transport.connect(None, Username, Password, self.key)

If I manually turn off the WiFi during connected state, I receive a log

Socket exception: An existing connection was forcibly closed by the remote host (10054)

However this is the error from the Paramiko library itself. Is there a way I can control it by my code? Thanks

Some background: When user logs in, I will connect them to the SFTP and update a label to "Server Connected". However when the connection drops due to any reason, I do not have a way to update the label to "Disconnected".


Solution

  • Call Transport.is_active() regularly to check, if the connection is still live.


    Ntb, by using low-level Transport class, you are possibly bypassing host key check, what is a security flaw. You better use the high-level SSHClient API.