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

半腔热情 提交于 2021-02-07 20:40:41

问题


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.")

回答1:


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()



回答2:


you can do it with:

Connection.timeout (35000)


来源:https://stackoverflow.com/questions/59062194/with-pysftp-how-can-i-specify-a-timeout-value-for-the-connection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!