问题
I want to write a python script that connects to the remote 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 :
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect('15.100.1.1', username='user', password='123')
sftp=c.open_sftp()
c.exec_command("cd 'C:\\Program Files\\temp'")
filenames = ['a.txt','b.txt','c.txt']
zf = zipfile.ZipFile('files.zip', mode='w')
for fname in filenames:
zf.write(fname)
zf.close()
sftp.close()
c.close()
But instead of creating zip file in remote server, the zip file gets created in the local machine itself. Can anyone please help me in this.....
回答1:
When you create the zip-file you refer to a local file files.zip
:
zf = zipfile.ZipFile('files.zip', mode='w')
You never tell it to create the file remotely. But you could probably (haven't tried it myself) create a remote file and send the handle to ZipFile. The issue with that is that you will run the zipping on you local machine instead of on the remote machine. That will have all your files be moved over network back and forth to no use other than creating the remote file. Try to do the zipping directly on the remote machine instead!
回答2:
As UlfR says, "Try to do the zipping directly on the remote machine". Since he (she?) didn't say how to do that, I suggest something like
c.exec_command("zip files.zip a.txt b.txt c.txt")
来源:https://stackoverflow.com/questions/33406850/python-script-for-creating-zip-file-in-remote-server