【问题标题】:Python pysftp put_r does not work on WindowsPython pysftp put_r 在 Windows 上不起作用
【发布时间】:2020-02-16 00:47:50
【问题描述】:

我想使用 pysftp 0.2.8 将多个文件从 Windows 目录上传到 SFTP 服务器。我已经阅读了文档,它建议使用 put_dput_r 但两者都给我以下错误:

OSError:路径无效:

sftp_local_path = r'C:\Users\Swiss\some\path'

sftp_remote_path = '/FTP/LPS Data/ATC/RAND/20191019_RAND/XML'

with pysftp.Connection("xxx.xxx.xxx.xxx", username=myUsername, password=myPassword) as sftp:
    with sftp.cd(sftp_remote_path):
        sftp.put_r(sftp_local_path, sftp_remote_path)
        for i in sftp.listdir():
            lstatout=str(sftp.lstat(i)).split()[0]
            if 'd' in lstatout: print (i, 'is a directory')

sftp.close()

我希望能够将所有文件或选定文件从我的本地目录复制到 SFTP 服务器。

【问题讨论】:

    标签: python upload sftp pysftp


    【解决方案1】:

    我无法重现您的确切问题,但确实已知 pysftp 的递归函数的实现方式会使它们在 Windows(或任何不使用 *nix 类路径语法的系统)上失败。

    Pysftp 对远程 SFTP 路径使用 os.sepos.path 函数,这是错误的,因为 SFTP 路径总是使用正斜杠。


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

    import os
    
    def put_r_portable(sftp, localdir, remotedir, preserve_mtime=False):
        for entry in os.listdir(localdir):
            remotepath = remotedir + "/" + entry
            localpath = os.path.join(localdir, entry)
            if not os.path.isfile(localpath):
                try:
                    sftp.mkdir(remotepath)
                except OSError:     
                    pass
                put_r_portable(sftp, localpath, remotepath, preserve_mtime)
            else:
                sftp.put(localpath, remotepath, preserve_mtime=preserve_mtime)    
    

    像这样使用它:

    put_r_portable(sftp, sftp_local_path, sftp_remote_path, preserve_mtime=False) 
    

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


    有关get_r 的类似问题,请参阅:
    Python pysftp get_r from Linux works fine on Linux but not on Windows

    【讨论】:

    • 感谢您的帮助...这行得通。在 Python 中我还有很多东西要学。
    猜你喜欢
    • 2023-03-26
    • 2013-05-02
    • 2015-04-21
    • 2020-07-08
    • 2019-01-23
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多