美文网首页
使用Python部署Vue打包文件

使用Python部署Vue打包文件

作者: 一个小前端程序员 | 来源:发表于2021-08-12 10:19 被阅读0次

    注:放在项目的根目录下

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    import os
    import sys
    import zipfile
    import time
    import paramiko
    
    servers = [
        {
            "name": 'xxx',
            "domain": '',
            "host": 'xxx.xxx.xxx.xxx',#服务器地址
            "port": 22,#服务器端口
            "username": 'xxx',#用户名
            "password": 'xxx',#密码
            "path": 'xxxx'#前端代码路径
        }
    ]
    
    def build_dist():
        os.system("cd "+project_path+"&npm run build")
    
    def zip_files(dirpath,outFullName):
        """
        压缩指定文件夹
        :param dirpath: 目标文件夹路径
        :param outFullName: 压缩文件保存路径+xxxx.zip
        :return: 无
        """
        zip = zipfile.ZipFile(outFullName,"w",zipfile.ZIP_DEFLATED)
        for path,dirnames,filenames in os.walk(dirpath):
            # 去掉目标根路径,只对目标文件夹下边的文件及文件夹进行压缩
            fpath = path.replace(dirpath,'')
    
            for filename in filenames:
                zip.write(os.path.join(path,filename),os.path.join(fpath,filename))
        zip.close()
    
    # 上传文件
    def upload_file(client,server):
        sftp = client.open_sftp()
        sftp.put(local_dist_path+"dist.zip", server["path"]+"/dist.zip",callback=progress_bar)#将本地的Windows.txt文件上传至服务器/root/Windows.txt
        print("文件上传完成")
    
    # 下载文件
    def download_file(client,server,file_name):
        sftp = client.open_sftp()
        sftp.get(server["path"]+file_name,local_backup_path+file_name,callback=progress_bar)#将本地的Windows.txt文件上传至服务器/root/Windows.txt
        print("文件下载完成")
    
    #远程登陆操作系统
    def ssh_exec_command(client,cmd):
        stdin, stdout, stderr = client.exec_command(cmd)
        #获取命令执行结果,返回的数据是一个list
        result = stdout.readlines()
        print("[%s]执行成功"%(cmd))
        return result
    
    # 文件传输进度条
    def progress_bar(transferred, toBeTransferred, suffix=''):
        percents = round(100.0 * transferred / float(toBeTransferred), 1)
        sys.stdout.write('文件传输进度:%s%s %s\r' % (percents, '%', suffix))
        sys.stdout.flush()
        
    def main(server):
        print("*******正在操作环境:%s[%s:%s]**********"%(server["name"],server["host"], server["port"]))
        try:
            #创建ssh客户端
            client = paramiko.SSHClient()
            #第一次ssh远程时会提示输入yes或者no
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            #密码方式远程连接
            client.connect(server["host"], server["port"], username=server["username"], password=server["password"], timeout=20)
    
            # 服务器压缩文件名称
            back_up_file_name = server["name"]+ os.getcwd().split("\\")[-1] +time.strftime("%Y%m%d%H%M%S", time.localtime())+".zip"
            try:
                # 服务器文件压缩
                ssh_exec_command(client,"cd %s;zip -r %s *"%(server["path"],back_up_file_name))
                # 下载压缩的文件备份
                download_file(client,server,back_up_file_name)
                # 删除掉文件夹内的文件
                ssh_exec_command(client,"cd %s;rm -rf *"%(server["path"]))
            except IOError:
                print("服务器没有文件")
            # 上传打包文件
            upload_file(client,server)
            # 解压上传打包文件
            ssh_exec_command(client,"cd %s;unzip -o dist.zip -d ./"%(server["path"]))
            # 删除压缩文件
            ssh_exec_command(client,"cd %s;rm -rf ./dist.zip"%(server["path"]))
        except Exception as e:
            print(e)
        finally:
            client.close()
    
    if __name__ == "__main__":
        
        # 本地存储备份包的路径
        local_backup_path = "D:/YinYan/Project/hrmp-backup/"
        # 本地打包文件存储路径
        local_dist_path = "D:/YinYan/Project/hrmp-backup/"
        # 项目路径
        project_path = os.getcwd()
    
        for idx,server in enumerate(servers):
            print("环境:%s      值:%d"%(server["name"],idx))
        print("所有环境      值:999")
        print("----------选择发包环境-----------")
        
        index = int(input("请输入:"))
    
        print("----是否要重新打包[0:否][1:是]----")
        flag = int(input("请输入:"))
        
        # 执行打包命令
        if(flag):
            build_dist()
        # 压缩打包文件
        zip_files(project_path+"\dist",local_dist_path+"dist.zip")
    
        if index != 999:
            server = servers[index]
            main(server)
        else:
            for server in servers:
                 main(server)
        
    

    相关文章

      网友评论

          本文标题:使用Python部署Vue打包文件

          本文链接:https://www.haomeiwen.com/subject/khzkbltx.html