31

I'm looking for a way to set a timeout for this:

transport = paramiko.Transport((host, port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.get(remotepath, localpath)
sftp.close()
transport.close()
Himanshu
  • 31,810
  • 31
  • 111
  • 133
Kukosk
  • 2,892
  • 1
  • 27
  • 30

1 Answers1

65

The connection timeout can be set with the timeout parameter (that indicated the number of seconds for the time out as described here) of the connect function.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password, timeout=10)
sftp = ssh.open_sftp()
sftp.get(remotepath, localpath)
sftp.close()
Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
Kukosk
  • 2,892
  • 1
  • 27
  • 30
  • 3
    @kukosk It would help if you mentioned the unit in which timeout is to be given, I guess its seconds. – manoj prashant k Dec 15 '17 at 11:02
  • 2
    What's the default timeout, I don't think I found it mentioned in the [docs](http://docs.paramiko.org/en/2.4/api/client.html#paramiko.client.SSHClient.connect) either, although they do mention `timeout (float) – an optional timeout (in seconds) for the TCP connect` – jxramos Jul 18 '18 at 21:59
  • Here's some more background, if timeout is not specified the client falls into blocking mode: https://docs.python.org/3/library/socket.html#socket-timeouts – jxramos Jul 19 '18 at 00:21
  • Lots of default timeout definitions pop up at https://github.com/jbouse-debian/paramiko/blob/master/paramiko/transport.py, all given in seconds – jxramos Jul 19 '18 at 00:32
  • 3
    Note that `timeout` parameter sets TCP timeout. There are also `banner_timeout` and `auth_timeout` which you may want to adjust as well. – trozen Apr 08 '19 at 09:41
  • @jxramos are you sure about blocking behavior? When I tested an unreachable address with no timeout argument, the connect timed out after 75 seconds. – chrisinmtown Jun 09 '22 at 11:36