我想使用 pysftp 0.2.8 将多个文件从 Windows 目录上传到 SFTP 服务器.我已经阅读了文档,它建议使用 put_d
或 put_r
但两者都给我以下错误:
I'd like to upload multiple files from a Windows directory to an SFTP server using pysftp 0.2.8. I've read up the doc and it suggests to use put_d
or put_r
but both give me the following error:
OSError:路径无效:
OSError: Invalid path:
sftp_local_path = r'C:UsersSwisssomepath'
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 服务器.
I'd like to be able to copy all files or selected files from my local directory to the SFTP server.
我无法重现您的确切问题,但确实已知 pysftp 的递归函数的实现方式会使它们在 Windows(或任何系统不使用 *nix-like 路径语法).
I cannot reproduce your exact problem, but indeed the recursive functions of pysftp are known to be implemented in a way that makes them fail on Windows (or any system that does not use *nix-like path syntax).
Pysftp 对远程 SFTP 路径使用 os.sep
和 os.path
函数,这是错误的,因为 SFTP 路径总是使用正斜杠.
Pysftp uses os.sep
and os.path
functions for remote SFTP paths, what is wrong, as SFTP paths always use a forward slash.
但您可以轻松实现便携式替换:
But you can easily implement a portable replacement:
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
类 也有 put
方法.唯一的区别是 Paramiko 的 put
没有 preserve_mtime
参数/功能(但如果需要,可以轻松实现).
Note that the above code can be easily modified to work with Paramiko directly, in case you do not want to use pysftp. The Paramiko SFTPClient
class also has the put
method. The only difference is that the Paramiko's put
does not have the preserve_mtime
parameter/functionality (but it can be implemented easily, if you need it).
有关 get_r
的类似问题,请参阅:
来自 Linux 的 Python pysftp get_r 在 Linux 上运行良好,但在 Windows 上却不行
For a similar question about get_r
, see:
Python pysftp get_r from Linux works fine on Linux but not on Windows
这篇关于Python pysftp put_r 在 Windows 上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!