linux可使用expect来实现自动交互,windows想要写出同样的功能脚本,只能使用python或者安装ActiveTcl
1、安装python
- Microsoft Store搜索python直接安装,默认会直接添加到环境变量
- https://www.python.org/官网下载,点击安装时会提示是否添加到环境变量
2、添加检查环境变量
检查是否配置了多个,多个会按顺序查找使用,对后期出现问题不好排查
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
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 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('hostName', username='userName', password='password')
uploadJar(sshClient)
restart(sshClient)
sshClient.close()
print("部署成功")
5、使用
放入项目中
打开terminal窗口
python publish.py 测试环境名