With pysftp, how can I specify a timeout value for the connection?
Asked Answered
F

2

5

With pysftp, I see how to set a timeout for any commands once you're already connected, but I don't see how to set a timeout for the connection itself. I feel like I'm missing something somewhere. Just to try it, I tried adding timeout=3 to the Connection method and got an error, and tried using cnopts.timeout=3 and that did nothing at all. For the record, I'm using Python 3 on Windows, if that affects anything.

Here's some simple test code you can experiment with, if it helps. (As is, the connection times out after about 30 seconds.)

import pysftp

print("\n"*25)
cnopts=pysftp.CnOpts()
# - I know this next line is insecure, it's just for this test program.
cnopts.hostkeys = None

print('Connecting...')
# - 8.8.8.8 is Google's public DNS server. It doesn't respond to sftp requests at all,
# - so it's a good test case for how long a connection timeout takes.
with pysftp.Connection('8.8.8.8', username='anonymous', password='password',
                    cnopts=cnopts) as SFTP:
    print("Wait, how did you get this far?")
print("Done.")
Frangible answered 27/11, 2019 at 2:34 Comment(0)
P
5

It does not look like that pysftp allows setting a connection timeout.

You can use Paramiko directly instead (pysftp is just a wrapper around Paramiko).

Paramiko SSHClient.connect method has timeout parameter.

ssh = paramiko.SSHClient()
ssh.connect(host, username=username, password=password, timeout=timeout)
sftp = ssh.open_sftp()
Pericarditis answered 27/11, 2019 at 6:53 Comment(1)
Dang. I saw the same, but was hoping there was a way around that that I missed somewhere. Hmm, I suppose I'll go put in a feature request for pysftp in the meantime. :-)Frangible
H
0

you can do it with:

Connection.timeout (35000)
Hyetology answered 3/12, 2020 at 13:40 Comment(1)
But you can call that only after you create the Connection, so only after you connect. So does this allow you to set the connection timeout?Pericarditis

© 2022 - 2024 — McMap. All rights reserved.