Python 實(shí)現(xiàn)一鍵發(fā)布項(xiàng)目

這是 Stephen 的第 87 篇原創(chuàng)文章
由于公司業(yè)務(wù)項(xiàng)目所需,要每天頻繁發(fā)布版本,高達(dá)幾個(gè)小時(shí)一個(gè)版本,甚至一個(gè)小時(shí)多個(gè)版本,雖是小需求,小改動,但急用?;旧鲜沁呴_發(fā)邊發(fā)布的工作節(jié)奏。
說到這,不禁眼眶有點(diǎn)濕潤……羨慕每周發(fā)一版,每兩周發(fā)一版,甚至更長時(shí)間發(fā)版周期的公司項(xiàng)目組。
因這種高頻次的發(fā)布需要,發(fā)布操作就顯得格外繁瑣,包括同步代碼,打包,連接 Linux 服務(wù)器,備份舊版本,上傳新版本 jar 包,重啟項(xiàng)目等。如果把這個(gè)繁瑣的工作“外包”出去,是不是就省事很多了。
說干就干,招“外包”!
剛好最近學(xué)了點(diǎn) Python ,那就招 Python 吧,讓 Python 替我把這繁瑣的發(fā)布操作工作給干了。
我只需要簡單地通知下它就好。
“通知” 長啥樣,怎么通知;Python 具體又怎么干呢?
---------代碼實(shí)戰(zhàn)分割線-------------
“通知” 就是我雙擊這個(gè) publish-dashboard.bat 批處理文件,讓它去執(zhí)行另外一個(gè) Python 文件 publishdashboard.py,Python 幫我做完同步代碼,打包,連接 Linux 服務(wù)器,備份舊版本,上傳新版本 jar 包,重啟項(xiàng)目這些工作。
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# 相關(guān)文件,路徑,命令的配置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-打包發(fā)布 && d: && git pull'command_mvnpackage = 'cd D:\dashboard-打包發(fā)布 && d: && mvn package -Dmaven.test.skip=true'command_restart = 'sh /root/dashboard/restart-dashboard.sh'local_file = 'D:\\dashboard-打包發(fā)布\\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 成功 !')# 執(zhí)行遠(yuǎn)程命令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)# 函數(shù)入口if __name__ == '__main__':#去備份項(xiàng)目exe(command_cp)#去同步代碼打包buildjar()#去上傳項(xiàng)目jaruploadfile(local_file, remote_file)#去重啟服務(wù)exe(command_restart)#來通知我這些事情你做成功了沒有print('publish-dashboard successfully %s ' % datetime.datetime.now())

-- end --
喜歡就三連呀
推薦閱讀:
Windows 下 Python 開發(fā)環(huán)境搭建
TIOBE 7 月編程語言排行榜:C、Java 和 Python 爭奪第一
點(diǎn)擊"閱讀原文"可跳轉(zhuǎn)至我的博客。
關(guān)注 Stephen,一起學(xué)習(xí),一起成長。
