Python - 通過Python 製作簡易的一鍵部署腳本
1、定義流程
部署的流程是一致的,只是服務器信息不一樣,服務器的部署形式,部署路徑不一樣,所以
1、創建標準的部署模版
2、創建服務器配置
3、創建部署配置
2、創建標準的部署模版
import paramiko
import time
def command(ssh_config, cmd, need_print=None):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ssh_config.hostname, port=ssh_config.port, username=ssh_config.username,
password=ssh_config.password)
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
if need_print:
print(result)
ssh.close()
def upload_new(ssh_config, local, server):
client, transport = sftp(ssh_config)
client.put(local, server)
transport.close()
def sftp(ssh_config):
transport = paramiko.Transport(ssh_config.hostname, ssh_config.port)
transport.connect(username=ssh_config.username, password=ssh_config.password)
client = paramiko.SFTPClient.from_transport(transport)
return client, transport
def auto_deploy(deploy_config, ssh_config):
print('Step 1 : stop application')
command(ssh_config, deploy_config.stop_cmd)
print('wait for application stop')
time.sleep(2)
print('Step 2 : delete old application file')
command(ssh_config, deploy_config.delete_cmd)
print('Step 3 : upload new application file to server')
upload_new(ssh_config, deploy_config.local, deploy_config.server)
print('Step 4 : run application')
command(ssh_config, deploy_config.start_cmd)
print('deploy application completed')
3、創建服務器配置
hostname = '47.114.***.**'
port = 22
username = 'root'
password = '****'
4、創建部署配置
# 停止命令
stop_cmd = 'pkill -f nsbd.jar'
# 刪除命令
delete_cmd = 'rm -f /usr/local/spring-service/nsbd/nsbd.jar'
# 本地jar 包位置
local = 'C:/Users/A-PC/Desktop/nsbd.jar'
# 服務器jar 包位置
server = '/usr/local/spring-service/nsbd/nsbd.jar'
# 啓動服務命令
start_cmd = '''
nohup java -jar \
/usr/local/spring-service/nsbd/nsbd.jar \
--server.port=30001 \
> /usr/local/spring-service/nsbd/console-30001.log 2>&1 &
'''
5、創建運行腳本
from auto_deploy.nsbd import ssh_config
from auto_deploy.nsbd import deploy_config
from auto_deploy import auto_template
if __name__ == '__main__':
auto_template.auto_deploy(deploy_config, ssh_config)
6、延展性
進行不同的服務器,不同的環境部署,只需要複製一套配置,修改好配置即可