使用Paramiko上传类似文件的对象?

Rei*_*ica 9 python paramiko

我有一堆看起来像这样的代码:

with tempfile.NamedTemporaryFile() as tmpfile:
    tmpfile.write(fileobj.read()) # fileobj is some file-like object
    tmpfile.flush()
    try:
        self.sftp.put(tmpfile.name, path)
    except IOError:
        # error handling removed for ease of reading
        pass
Run Code Online (Sandbox Code Playgroud)

是否可以像这样进行上传而无需将文件写出来?

小智 15

更新Paramiko 1.10起,您可以使用putfo:

self.sftp.putfo(fileobj, path)
Run Code Online (Sandbox Code Playgroud)

paramiko.SFTPClient.put您可以使用paramiko.SFTPClient.open,而不是使用,打开类似file对象.你可以写信给那个.像这样的东西:

f = self.sftp.open(path, 'wb')
f.write(fileobj.read())
f.close()
Run Code Online (Sandbox Code Playgroud)

请注意,以32 KiB块的形式提供paramiko数据可能是值得的,因为这是SSH协议可以处理的最大块,而不会将其分解为多个数据包.