python打包部署脚本

linux可使用expect来实现自动交互,windows想要写出同样的功能脚本,只能使用python或者安装ActiveTcl

1、安装python

  • Microsoft Store搜索python直接安装,默认会直接添加到环境变量
  • https://www.python.org/官网下载,点击安装时会提示是否添加到环境变量
    在这里插入图片描述

2、添加检查环境变量

在这里插入图片描述

python_home为python所在文件目录

检查是否配置了多个,多个会按顺序查找使用,对后期出现问题不好排查
cmd检查版本 python --version
cmd检查安装路径,确保当前使用的环境与环境变量的相匹配 :

which python
或
python  
import sys 
print(sys.executable) 

3、安装模块

pip install paramiko
pip install scp

如果是用pyCharm开发后再在cmd中执行报错,出现module not found,
导致这个问题的原因之一是pyCharm中创建项目时默认设置的为环境版本隔离,可修改默认选项
在这里插入图片描述

4、开发脚本

测试环境为k8s容器
命令可服务器source ~/.bash_profile中进行简化

import paramiko
import scp
import sys
import os
import shutil
import time

projectName = 'myproject'
env = sys.argv[1]
projectPath = os.getcwd()
# 本地编译jar的路径
localPath = r"{}\{}\\target\{}\lib".format(projectPath, projectName, projectName)
# 远程部署jar路径
remotePath = "/data/{}/{}/{}/".format(env, projectName, projectName)


def mvnPackage():
    os.chdir(projectPath)
    targetPath = projectPath + "\\" + projectName + "\\target"
    success = removeDir(targetPath)
    if (success):
        os.system("mvn clean package -Dmaven.test.skip=true")
        exist = verifyFileExist(targetPath)
        if (exist):
            print("package complete success=======")
            return True
        else:
            print("package complete error=======")

    return False


def removeDir(oldPath):
    if (verifyFileExist(oldPath)):
    	# remove只能删除无子文件目录
        shutil.rmtree(oldPath)
        print("删除本地文件成功" + oldPath)
    return True

def verifyFileExist(path):
    exist = os.path.exists(path)
    print(path + " exist is " + str(exist))
    return exist


def restart(sshClient):
    print("======restart pod start===============")
    podCmd = "kubectl get pods -n {} | grep {} | awk {}".format(env, projectName, "'{print $1}'")
    print(podCmd)
    stdin, stdout, stderr = sshClient.exec_command(podCmd)
        # 'kubectl get pods -n ' + env + ' | grep ' + projectName + ' | awk \'{print $1}\'')
    podId = stdout.read().decode()
    stderr = stderr.read().decode()
    # 输出命令执行结果
    print("======podId :" + podId + " " +  stderr)
    if len(podId) == 0:
        print(projectName + "查询不到podId,请检查是否部署")
    else:
        podId = podId.replace("\n", "")
        deleteCmd = "kubectl delete pod " + podId + " -n " + env
        print("===============" + deleteCmd)
        stdin, stdout, stderr = sshClient.exec_command(deleteCmd)
        error = stderr.read().decode()
        if (len(error) != 0):
            print("====restart 异常:" + error)
        else:
            print("======restart pod end===============" + stdout.read().decode())

def loopCheckStatus(sshClient):
    #time.sleep(120)
    for inner_loop in range(20):
        stat = getPodStatus(sshClient)
        if stat == '1':
            print("======restart 启动成功=====")
            return
        else:
            print("======restart 启动中=====")
            time.sleep(10)
    print("======restart 启动失败=====")

def getPodStatus(sshClient):
    print("======get pod id start===============")
    index = '{print $2}'
    podCmd = "kubectl get pods -n {} | grep {} | awk {}".format(env, projectName, "'{print $2}'")
    print(podCmd)
    stdin, stdout, stderr = sshClient.exec_command(podCmd)
    podStatus = stdout.read().decode()
    stderr = stderr.read().decode()
    # 输出命令执行结果
    start = podStatus.split("/")[0]
    print("======getPodStatus :" + start)
    return start


def uploadJar(sshClient):
    scpClient = scp.SCPClient(sshClient.get_transport())
    print("localPath:" + localPath + "\nremotePath:" + remotePath)
    scpClient.put(localPath, remotePath, recursive=True)
    scpClient.close()
    print("========上传成功")


if __name__ == '__main__':
    print("=====================" + projectName)
    success = mvnPackage()
    if (success == False):
        print("打包失败")
    else:
        sshClient = paramiko.SSHClient()
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        sshClient.connect('hostNamexxx', username='userNamexxx', password='passwordxxx')
        uploadJar(sshClient)
        restart(sshClient)
        loopCheckStatus(sshClient)
        sshClient.close()
        print("部署成功")

5、mvn配置

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-lib</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/project-name-xxx/lib</outputDirectory>
                            <excludeTransitive>false</excludeTransitive>
                            <stripVersion>false</stripVersion>
                            <includeScope>runtime</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

6、使用

放入项目中
打开terminal窗口
python publish.py 测试环境名

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值