为了账号安全,请及时绑定邮箱和手机立即绑定

Python pysftp put_r 在 Windows 上不起作用

Python pysftp put_r 在 Windows 上不起作用

慕盖茨4494581 2022-06-28 10:59:03
我想使用 pysftp 0.2.8 将多个文件从 Windows 目录上传到 SFTP 服务器。我已经阅读了文档,它建议使用put_dorput_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 服务器。
查看完整描述

1 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

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


Pysftp 对远程 SFTP 路径的使用os.sep和os.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) 

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



查看完整回答
反对 回复 2022-06-28
  • 1 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号