来自 Linux 的 Python pysftp get_r 在 Linux 上运行良好,但在 Windows 上运行良好

Posted

技术标签:

【中文标题】来自 Linux 的 Python pysftp get_r 在 Linux 上运行良好,但在 Windows 上运行良好【英文标题】:Python pysftp get_r from Linux works fine on Linux but not on Windows 【发布时间】:2021-09-28 16:55:33 【问题描述】:

我想使用 Python 2.7 使用 SFTP 递归地将包含文件和子文件夹的整个目录结构从 Linux 服务器复制到本地计算机(Windows 和 Linux)。

我可以 ping 服务器并使用 WinSCP 从同一台机器下载文件。

我尝试了以下代码,在 Linux 上运行良好,但在 Windows 上却不行。

我试过\/os.join,都给了我同样的错误,也检查了权限。

import os
import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None    # disable host key checking.
sftp=pysftp.Connection('xxxx.xxx.com', username='xxx', password='xxx', cnopts=cnopts)
sftp.get_r('/abc/def/ghi/klm/mno', 'C:\pqr', preserve_mtime=False)
File "<stdin>", line 1, in <module> File "C:\Python27\lib\site-packages\pysftp_init_.py", line 311, in get_r preserve_mtime=preserve_mtime)
File "C:\Python27\lib\site-packages\pysftp_init_.py", line 249, in get self._sftp.get(remotepath, localpath, callback=callback)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 769, in get with open(localpath, 'wb') as fl: IOError: [Errno 2] No such file or directory: u'C:\\pqr\\./abc/def/ghi/klm/mno/.nfs0000000615c569f500000004' 

【问题讨论】:

【参考方案1】:

确实,pysftp get_r 在 Windows 上不起作用。它对远程 SFTP 路径使用 os.sepos.path 函数,这是错误的,因为 SFTP 路径总是使用正斜杠。

但您可以轻松实现便携式替换。

import os
from stat import S_ISDIR, S_ISREG
def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
    for entry in sftp.listdir_attr(remotedir):
        remotepath = remotedir + "/" + entry.filename
        localpath = os.path.join(localdir, entry.filename)
        mode = entry.st_mode
        if S_ISDIR(mode):
            try:
                os.mkdir(localpath)
            except OSError:     
                pass
            get_r_portable(sftp, remotepath, localpath, preserve_mtime)
        elif S_ISREG(mode):
            sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

像这样使用它:

get_r_portable(sftp, '/abc/def/ghi/klm/mno', 'C:\\pqr', preserve_mtime=False) 

请注意,上面的代码可以很容易地修改为直接使用 Paramiko,以防您不想使用 pysftp。 Paramiko SFTPClient class 也有 listdir_attrget 方法。唯一的区别是 Paramiko 的 get 没有 preserve_mtime 参数/功能(但如果需要,它可以轻松实现)。


可能的代码修改:

Do not download empty folders while downloading from SFTP server using Python Download files from SFTP server that are older than 5 days using Python How to sync only the changed files from the remote directory using pysftp?

有关put_r 的类似问题,请参阅:Python pysftp put_r does not work on Windows


旁注:不要“禁用主机密钥检查”。您正在失去对MITM attacks 的保护。

如需正确解决方案,请参阅Verify host key with pysftp。

【讨论】:

以上是关于来自 Linux 的 Python pysftp get_r 在 Linux 上运行良好,但在 Windows 上运行良好的主要内容,如果未能解决你的问题,请参考以下文章

使用 python pysftp 包,得到“SSHException:来自服务器的错误主机密钥”错误 [重复]

Python - pysftp / paramiko - 使用其指纹验证主机密钥

尽管文件已上传,但 Python pysftp.put 引发“没有此类文件”异常

通过 pip 安装 pysftp 失败(因为有 2 个 python2.x 版本?)

Python pysftp put_r 在 Windows 上不起作用

pysftp vs. Paramiko