說明 : 通過Python腳本生成shell腳本,執行shell腳本可以打包、上傳服務器、殺死進程和重新運行程序
依賴 :
- 可以執行shell的環境
- Python3
步驟
- 執行 init.py 文件
- 執行 one_key_deploy.sh 文件
該工具總共包含 config.conf 和 init.py 兩個文件,執行 init.py 會生成多個shell文件,執行其中的 one_key_deploy.sh 文件即可
注 : init.py 初始化一次就可以了
以下爲具體文件內容
config.conf
這是配置文件,需要配置java項目路徑、打包後文件路徑、打包後文件名、服務器ip、服務器ssh密碼和服務器工作路徑
[config]
package_path=/Users/leyili/test
jar_name=ctest.jar
jar_path=/test/target
server_ip=1.1.1.1
server_password=123
server_work_path=/usr/test
init.py
生成shell的Python腳本
import configparser
import os
# 讀取配置文件
cp = configparser.ConfigParser()
cp.read('config.conf')
package_path = cp.get('config', 'package_path')
jar_name = cp.get('config', 'jar_name')
jar_path = cp.get('config', 'jar_path')
server_ip = cp.get('config', 'server_ip')
server_password = cp.get('config', 'server_password')
server_work_path = cp.get('config', 'server_work_path')
# 生成打包腳本
sh_package = open('package.sh', 'w')
sh_package.write('#!/bin/sh\ncd ' + package_path + '\nmvn clean package')
os.system('chmod +x package.sh')
# 生成上傳打包腳本
sh_upload = open('upload.sh', 'w')
upload_content = '#!/usr/bin/expect\n' + 'spawn scp ' + \
jar_path + '/' + jar_name + ' root@' + server_ip + \
':/root\nexpect "*password:"\n' \
'send "' + server_password + '\\r"\n' \
'expect "*#"\n' \
'interact'
sh_upload.write(upload_content)
os.system('chmod +x upload.sh')
# 生成部署腳本
sh_deploy = open('deploy.sh', 'w')
deploy_content = '#!/usr/bin/expect\nspawn ssh root@' + server_ip + '\n' + \
'expect "*password:"\n' + 'send "' + \
server_password + '\\r"\n' + \
'expect "*#"\n' + \
'send "cd ' + server_work_path + '\\r"\n' + \
'send "ps -efww|grep -w ' + jar_name + '|grep -v grep|cut -c 9-15|xargs kill -9\\r"\n' + \
'send "rm -rf backup\\r"\n' + \
'send "mkdir backup\\r"\n' + \
'send "mv ' + jar_name + ' backup\\r"\n' + \
'send "mv /root/' + jar_name + ' ./\\r"\n' + \
'send "nohup java -jar ' + jar_name + ' &\\r"\n' + \
'expect eof'
sh_deploy.write(deploy_content)
os.system('chmod +x deploy.sh')
# 生成一鍵執行腳本
sh_one_key_deploy = open('one_key_deploy.sh', 'w')
sh_one_key_deploy.write('#!/bin/sh\n./package.sh\n./upload.sh\n./deploy.sh')
os.system('chmod +x one_key_deploy.sh')
print('SUCCESS')
END。