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、延展性
进行不同的服务器,不同的环境部署,只需要复制一套配置,修改好配置即可