本文介绍了使用 pysftp,如何为连接指定超时值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 pysftp,我看到了如何在您已经连接后为任何命令设置超时,但我没有看到如何为连接本身设置超时.我觉得我在某处丢失了一些东西.只是为了尝试一下,我尝试将 timeout=3 添加到 Connection 方法并出现错误,并尝试使用 cnopts.timeout=3 和那什么都没做.作为记录,我在 Windows 上使用 Python 3,如果这会影响任何事情的话.

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.

这里有一些简单的测试代码,您可以尝试一下,如果有帮助的话.(按原样,连接在大约 30 秒后超时.)

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

推荐答案

pysftp 似乎不允许设置连接超时.

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

您可以直接使用 Paramiko(pysftp 只是 Paramiko 的包装器).

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

Paramiko SSHClient.connect 方法有超时参数.

Paramiko SSHClient.connect method has timeout parameter.

ssh = paramiko.SSHClient()
ssh.connect(host, username=username, password=password, timeout=timeout)
sftp = ssh.open_sftp()

这篇关于使用 pysftp,如何为连接指定超时值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 08:02