使用 pysftp,如何指定连接的超时值?

Cyb*_*aco 5 python sftp pysftp

使用 pysftp,我了解了如何在连接后为任何命令设置超时,但我不知道如何为连接本身设置超时。我觉得我在某个地方错过了一些东西。只是为了尝试一下,我尝试添加timeout=3到该Connection方法中并收到错误,并尝试使用cnopts.timeout=3,但什么也没做。根据记录,我在 Windows 上使用 Python 3,如果这有什么影响的话。

如果有帮助的话,您可以尝试以下一些简单的测试代码。(实际上,连接在大约 30 秒后超时。)

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.")
Run Code Online (Sandbox Code Playgroud)

Mar*_*ryl 5

pysftp 看起来不允许设置连接超时。

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

ParamikoSSHClient.connect方法有timeout参数。

ssh = paramiko.SSHClient()
ssh.connect(host, username=username, password=password, timeout=timeout)
sftp = ssh.open_sftp()
Run Code Online (Sandbox Code Playgroud)