如何使用 pysftp 从服务器上的文件在 SFTP 服务器上创建 zip 文件 [英] How to create a zip file on SFTP server from files on the server using pysftp

查看:78
本文介绍了如何使用 pysftp 从服务器上的文件在 SFTP 服务器上创建 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 Python 脚本,该脚本连接到远程 SFTP 服务器并在远程服务器中创建一个 ZIP 文件,该文件由远程服务器本身中存在的特定文件组成.我已经编写了以下脚本,为此我使用了 pysftp,

I want to write a Python script that connects to the remote SFTP server and creates a ZIP file in the remote server which consists of specific files present in remote server itself. I have written the below script, I m using pysftp for this,

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
    print("Connection succesfully stablished ... ")
    files = ['user/1.csv','user/2.csv','user/test.csv', 'user/test1.csv']
    with zipfile.ZipFile('zipfile.zip', 'w') as zipMe:
        for file in files:
            zipMe.write(file, file.split('/')[-1], compress_type=zipfile.ZIP_DEFLATED)

但不是在远程服务器中创建 ZIP 文件,而是在本地创建 ZIP 文件.任何人都可以帮我解决这个问题吗?

But instead of creating a ZIP file in the remote server, an ZIP file gets created in the local. Can anyone please help me with this?

推荐答案

实际上,您的代码将 local 文件压缩到 local ZIP 存档.请注意您的代码如何从不使用 sftp 变量.

Indeed, you code compresses local files to local ZIP archive. Note how your code never uses the sftp variable.

如果您想使用本地 Python脚本将远程文件压缩到远程 ZIP存档,您必须下载远程文件,zip它们在本地并上传 ZIP 存档.

If you want to compress remote files to remote ZIP archive using a local Python script, you have to download the remote files, zip them locally and upload the ZIP archive.

您可以在内存中"完成所有这些操作无需将远程文件或 ZIP 文件实际存储到本地系统.但是您仍然需要进行所有转移.所以效率会非常低.

You can do that all that "in-memory" without actually storing the remote files or the ZIP file physically to the local system. But you still need to do all the transfers. So it will be terribly inefficient.

您最好使用 SFTP(实际上是 SSH)连接在远程服务器上执行 zip 命令.

You better execute zip command on the remote server using your SFTP (or SSH actually) connection.

相关问题:如何使用paramiko python从sftp文件解码Zip文件

这篇关于如何使用 pysftp 从服务器上的文件在 SFTP 服务器上创建 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆