小编典典

来自Linux的Python pysftp get_r在Linux上工作正常,但在Windows上工作不正常

linux

我想使用SFTP递归使用文件和子文件夹将整个目录结构从Linux服务器复制到使用Python 2.7的本地服务器(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'

阅读 351

收藏
2020-06-02

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

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

2020-06-02