如何压缩远程linux服务器中的文件,压缩为gzp格式,传输到本机并解压。

用paramiko.sshclient()链接的远程服务器,如何实现把远程服务器中的文件压缩为gzp格式并传输到本地后解压,不懂得的是使用sftp中的那个方法可以实现压缩,用那个方法可以实现解压。

这是之前我写的一个小脚本,win上执行py远程linux执行命令,host.info里包含IP和账密,可以把执行结果下载到本地,根据实际情况修改下就可用

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import paramiko
server_path = '/root/'
local_path = 'D:/'
###################执行命令####################
def sftp_exec_command(host,port,username,password,command):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, port=port, username=username, password=password)
    stdin, stdout, stderr= ssh.exec_command(command)
    list = []
    for item in stdout.readlines():
        list.append(item.strip())
    return list
    ssh.close()
###################获取####################
def sftp_down_file(host,port,username,password,server_path, local_path):
    try:
        t = paramiko.Transport((host, port))
        t.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.get(server_path , local_path)
        t.close()
    except Exception as e:
        print(e)
###################主程序####################
if __name__ == '__main__':
    hosts_file = open('D:/host.info', 'r')
    for line in hosts_file.readlines():
        if line[0:1] == '#': continue
        line = line.strip('\n')
        items = line.split()
        port = 22
        host = items[0]
        username = items[1]
        password = items[2]
        sftp_exec_command(host,port,username,password,'linux命令')
        n = sftp_exec_command(host,port,username,password,"ls -t /root/log/ | head -1 ")
        filename = "/root/log/%s" % (n[0])
        print(filename)
        sftp_down_file(host,port,username,password,filename, "D:/server-log/%s"%(n[0]))

或者在本地把sh脚本写好用sftp.put把脚本上传到目标服务器执行,然后再拉取结果