【Python、运维】zip_file_deploy-向服务器上传 zip并解压

101 阅读1分钟

自己封装好的工具类

import os
import sys

import paramiko
from scp import SCPClient


class zip_file_deploy:
    def __init__(self):
        """
        """
        # 创建一个ssh的客户端,用来连接服务器
        ssh_client = paramiko.SSHClient()
        # 创建一个ssh的白名单
        know_host = paramiko.AutoAddPolicy()
        # 加载创建的白名单
        ssh_client.set_missing_host_key_policy(know_host)
        # 连接服务器
        ssh_client.connect(
            hostname=hostname,
            port=port,
            username=username,
            password=password
        )
        self.ssh_client = ssh_client

    def upload_file(self):
        """
            指定文件传送服务器
        :return:
        """

        print("【拖拽文件到此处】")
        local_path = input()
        # 如果没有数据则退出
        if not local_path:
            sys.exit()

        remote_path = '/data/workdir/ftp/'

        print("\r", '正在上传 · · · ', end='', flush=True)
        client = SCPClient(self.ssh_client.get_transport(),buff_size=1024 * 64, socket_timeout=15.0)
        try:
            client.put(local_path, remote_path)
            print("\r", "文件 [%s] 上传完成" % local_path.split(os.sep)[-1], end='', flush=True)
            print()
            remote_path += local_path.split(os.sep)[-1]
            self.unzip_file(remote_path)
        except FileNotFoundError as e:
            print(e)
            print("系统找不到指定文件" + local_path)

    def unzip_file(self, remote_path):
        """
        -d  extract files into exdir
        :param remote_path:
        :return:
        """

        extract_files_into = '/data/workdir/nginx-data/'

        print("\r", '正在解压 · · · ', end='', flush=True)
        # 执行命令
        print("\r", '清理文件 · · · ', end='', flush=True)
        self.ssh_client.exec_command("rm -rf %s*" % extract_files_into)
        stdin, stdout, stderr = self.ssh_client.exec_command("unzip -d %s %s" % (extract_files_into, remote_path))
        # stdin  标准格式的输入,是一个写权限的文件对象
        # stdout 标准格式的输出,是一个读权限的文件对象
        # stderr 标准格式的错误,是一个写权限的文件对象
        print(stdout.read().decode())
        print("解压完成")

    def __del__(self):
        """
        当对象释放时,关闭链接
        :return:
        """
        self.ssh_client.close()


if __name__ == '__main__':
    zfd = zip_file_deploy()
    while True:
        zfd.upload_file()