Python 实现一键发布项目

Stephen

共 3341字,需浏览 7分钟

 ·

2021-07-28 11:18


这是 Stephen 的第 87 篇原创文章


由于公司业务项目所需,要每天频繁发布版本,高达几个小时一个版本,甚至一个小时多个版本,虽是小需求,小改动,但急用。基本上是边开发边发布的工作节奏。


说到这,不禁眼眶有点湿润……羡慕每周发一版,每两周发一版,甚至更长时间发版周期的公司项目组。


因这种高频次的发布需要,发布操作就显得格外繁琐,包括同步代码,打包,连接 Linux 服务器,备份旧版本,上传新版本 jar 包,重启项目等。如果把这个繁琐的工作“外包”出去,是不是就省事很多了。


说干就干,招“外包”!


刚好最近学了点 Python ,那就招 Python 吧,让 Python 替我把这繁琐的发布操作工作给干了。


我只需要简单地通知下它就好。



通知” 长啥样,怎么通知;Python 具体又怎么干呢?


---------代码实战分割线-------------


“通知” 就是我双击这个 publish-dashboard.bat 批处理文件,让它去执行另外一个 Python 文件 publishdashboard.py,Python 帮我做完同步代码,打包,连接 Linux 服务器,备份旧版本,上传新版本 jar 包,重启项目这些工作。


publish-dashboard.bat

python publishdashboard.pypause


publishdashboard.py

# coding=utf-8import osimport timeimport datetimeimport paramiko
# ssh 配置hostname = '192.168.1.126'username = 'root'password = 'root'port = 22
# 相关文件,路径,命令的配置jar_name = 'dashboard-0.0.1-SNAPSHOT'command_cp = 'cp /root/dashboard/' + jar_name + '.jar /root/dashboard/back/' + jar_name + '-$(date +%Y%m%d-%H%M%S).jar'command_gitpull = 'cd D:\dashboard-打包发布 && d: && git pull'command_mvnpackage = 'cd D:\dashboard-打包发布 && d: && mvn package -Dmaven.test.skip=true'command_restart = 'sh /root/dashboard/restart-dashboard.sh'local_file = 'D:\\dashboard-打包发布\\target\\' + jar_name + '.jar'remote_file = '/root/dashboard/' + jar_name + '.jar'
# 同步代码,打包def buildjar():    time.sleep(1)    os.system(command_gitpull)   print("git pull 成功 !")    time.sleep(1)    os.system(command_mvnpackage)   print('package 成功 !')
# 执行远程命令def exe(command):    ssh = paramiko.SSHClient()    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    ssh.connect(hostname, username=username, password=password)    stdin, stdout, stderr = ssh.exec_command(command)    result = stdout.read().decode()    print(result)    result = stderr.read().decode()    print(result)
# 上传文件def uploadfile(local_file, remote_file):    try:        t = paramiko.Transport((hostname, port))        t.connect(username=username, password=password)        sftp = paramiko.SFTPClient.from_transport(t)        sftp.put(local_file, remote_file)        print("upload %s to remote %s" % (local_file, remote_file))    except Exception as e:        print("error", e)
# 函数入口if __name__ == '__main__':    #去备份项目    exe(command_cp)    #去同步代码打包    buildjar()    #去上传项目jar    uploadfile(local_file, remote_file)    #去重启服务    exe(command_restart)    #来通知我这些事情你做成功了没有    print('publish-dashboard successfully %s ' % datetime.datetime.now())



--  end  --


喜欢就三连

推荐阅读:

Windows 下 Python 开发环境搭建

只听说过用python做爬虫,java程序员笑了!

TIOBE 7 月编程语言排行榜:C、Java 和 Python 争夺第一



点击"阅读原文"可跳转至我的博客。


关注 Stephen,一起学习,一起成长。


浏览 31
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报