[英]How to create a zip file on SFTP server from files on the server using 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.我想编写一个 Python 脚本连接到远程 SFTP 服务器并在远程服务器中创建一个 ZIP 文件,该文件由远程服务器本身中存在的特定文件组成。 I have written the below script, I m using pysftp for this,
我编写了以下脚本,为此我使用 pysftp,
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)
But instead of creating a ZIP file in the remote server, an ZIP file gets created in the local.但不是在远程服务器中创建 ZIP 文件,而是在本地创建 ZIP 文件。 Can anyone please help me with this?
谁能帮我解决这个问题?
Indeed, you code compresses local files to local ZIP archive.实际上,您的代码将本地文件压缩到本地ZIP 存档。 Note how your code never uses the
sftp
variable.请注意您的代码如何从不使用
sftp
变量。
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. 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.
You can do that all that "in-memory" without actually storing the remote files or the ZIP file physically to the local system.您可以在不实际将远程文件或 ZIP 文件物理存储到本地系统的情况下完成所有“内存中”操作。 But you still need to do all the transfers.
但是您仍然需要进行所有转移。 So it will be terribly inefficient.
所以这将是非常低效的。
You better execute zip
command on the remote server using your SFTP (or SSH actually) connection.您最好使用您的 SFTP(或实际上是 SSH)连接在远程服务器上执行
zip
命令。
Related question: How to decode Zip file from sftp file using paramiko python相关问题:如何使用 paramiko python 从 sftp 文件中解码 Zip 文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.