# -*- coding:utf-8 -*-# !/usr/bin/env python3# name : alenx## pip3 install paramiko, pymysql#from datetime import datetimeimport fnmatch, os, paramiko, pymysql, requests# ------------------------------------------------------------------------------------------------------------# 賬戶資訊# branchbranch = 'cz1.0.5'# 自己的靜態伺服器帳號hosts = "10.10.0.11"username = "admin"passwd = "Demo2088@@"# 360加固帳號user = 'demo'pawd = 'Demo2088@@'# build modeconfDebug = "assembleDebug"confRelease = "apkRelease"# ------------------------------------------------------------------------------------------------------------# 項目根目錄project_path = "/opt/admin/android-fund/MainModule"# 匯出apk路徑APK_PATH = "/opt/admin/android-fund/MainModule/build/apks"# ------------------------------------------------------------------------------------------------------------# 靜態伺服器存放檔案路徑apppath = "/var/www/app/android_app"# ------------------------------------------------------------------------------------------------------------# 修改資訊projectNamepath = "/opt/admin/android-fund/MainModule/app/src/main/res/values/strings.xml"schemepath = "/opt/admin/android-fund/MainModule/config.gradle"exportOptionspath = "/opt/admin/android-fund/MainModule/commonlibrary/src/main/java/com/financeyun/demo" \ "/commonlibrary/config/DataConfig.java "# ------------------------------------------------------------------------------------------------------------# APP URLTestURL = "https://static.test.com/android_app/demotest-release.apk"ProURL = "https://static.test.com/android_app/demo-release.apk"# 蒲公英KeyPGY_key = "9c86dd6fb80a0dc8286d7xxxxx841d91"# 蒲公英APIKeyPGY_APIkey = "220fd5e840f4756axxxxxxbdb80e2e80"# 蒲公英URLPGY_URL = "https://www.pgyer.com/apiv2/app/upload"# 版本更新描述UpdateDescriptionTest = "Test Version"UpdateDescriptionPro = "Production Version"# 0:不更新, 1:更新, 2:強制更新update_agrs = 2# 更新描述update_note = """V0.8.14更新說明\r\n1、修改bug\r\n2、修改基金顯示樣式"""# ------------------------------------------------------------------------------------------------------------baseDir = '/opt/admin/tpc/key'keystorePath = os.path.join(baseDir, "demo.jks")keystore_alias = "financeyun"keystore_pass = "demo123456"key_pass = "demo123456"app_path = os.path.join(APK_PATH, '*-demo.apk')# ------------------------------------------------------------------------------------------------------------# SQLINSTER = "INSERT INTO basic_app_version_info (`app_code`, `update_type`, `version`, `app_url`, `update_note`,`create_time`,`modify_time`) " \ "VALUES('%s', '%s', '%s', '%s', '%s','%s', '%s')"# 360加固def exec_360_jiagu(): os.chdir('/opt/admin/tpc/jiagu') # os.system('java -jar jiagu.jar -login %s %s' % (user, pawd)) # os.system('java -jar jiagu.jar -importsign %s %s %s %s' % (keystorePath, keystore_pass, keystore_alias, key_pass)) os.system('java -jar jiagu.jar -config -crashlog -x86 -showsign') os.system('java -jar jiagu.jar -jiagu %s %s -autosign' % (app_path, APK_PATH))# 搜尋檔案def fnmat(sets): for file_name in os.listdir('%s' % APK_PATH): if sets == "test": fnmatch.fnmatch(file_name, '*-test.apk') return file_name else: fnmatch.fnmatch(file_name, '*_jiagu_sign.apk') return file_name# 連結資料庫插入資料def connet(var, url): __Instime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') InsterData = ('04', '%s' % update_agrs, '%s' % var, '%s' % url, '%s' % update_note, __Instime, __Instime) try: conn = pymysql.connect( host='10.30.0.42', port=3306, user='test', passwd='test@2088', db='basic', charset='utf8', cursorclass=pymysql.cursors.DictCursor) cur = conn.cursor() cur.execute(INSTER % InsterData) except pymysql.MySQLError as e: print("資料庫連結異常請檢查。", e) finally: conn.commit() cur.close()# Git projectdef Git_project(): try: print("\033[1;35m==========>> Start Git! <<==========\033[0m") os.chdir(project_path) # bran = os.popen('git branch --merged').read() os.system('git checkout . || exit\n') os.system('git fetch') os.system('git checkout -b %s origin/%s' % (branch, branch)) os.system('git pull || exit\n') os.system('git branch --merged || exit') print("\n\033[1;32m==========>> Git Log <<==========\033[0m") os.system('git log -3 --pretty=format:"%h - %cd, %an : %s" || exit') print("\n\033[1;32m==========>> Git success! <<==========\033[0m") except: exit(0)# Build Projectdef Build_project(setg): try: print("\033[1;35m==========>> Start Build! <<==========\033[0m") os.chdir(project_path) if setg == 'test': # ./gradlew clean apkRelease -Pchannels=test os.system('./gradlew clean %s -Pchannels=test || exit' % confRelease) else: os.system('./gradlew clean %s -Pchannels=financeyun || exit' % confRelease) print("\033[1;32m==========>> Build success! <<==========\033[0m") except: exit(0)# 備份檔案def ssh2(seting, version): __Date = datetime.now().strftime('%Y%m%d%H%M%S') try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hosts, 22, username, passwd, timeout=30) if seting == 'test': ssh.exec_command('cd %s && mv demotest-release.apk demotest-release.apk-%s-%s || exit' % (apppath, version, __Date), get_pty=False) else: ssh.exec_command('cd %s && mv demo-release.apk demo-release.apk-%s-%s || exit' % (apppath, version, __Date), get_pty=False) except paramiko.SSHException as e: print('Connet error:', e)# 上傳檔案到靜態伺服器def put_file(ps): try: transport = paramiko.Transport(hosts, 22) transport.connect(username=username, password=passwd) sftp = paramiko.SFTPClient.from_transport(transport) if ps == "test": remote_testfile = fnmat(ps) testfile = "demotest-release.apk" sftp.put(APK_PATH + '/' + remote_testfile, apppath + '/' + testfile) print("\033[1;32m====>> 當前環境為: %s <<====\033[0m" % UpdateDescriptionTest) else: remote_file = fnmat(ps) file = "demo-release.apk" sftp.put(APK_PATH + '/' + remote_file, apppath + '/' + file) print("\033[1;32m====>> 當前環境為: %s <<====\033[0m" % UpdateDescriptionPro) transport.close() except paramiko.SFTPError as e: print('upload error:', e)# 上傳IPA包至蒲公英def UploadIpaTo(remote_testfile, setting): file = (APK_PATH + '/' + remote_testfile) try: print("\033[1;35m==========>> 上傳app到蒲公英 <<==========\033[0m") file = {'file': open(file, 'rb')} param = {'_api_key': PGY_APIkey, 'buildUpdateDescription': setting} req = requests.post(url=PGY_URL, files=file, data=param) code = req.status_code if code == 200: print("\033[1;32m============>> 上傳蒲公英成功 <<============\033[0m") else: print("\033[1;35m==========>> 上傳蒲公英失敗請手動上傳 <<==========\033[0m") except Exception as e: exit(e)# 更改資訊def Sed(sed): print("\033[1;35m==========>> Sed File! <<==========\033[0m") # 環境變更檔 __envm = "/opt/admin/android-fund/MainModule/commonlibrary/src/main/assets/config.json" _dev = ''' sed -i "s/%s/%s/g" %s ''' % ('dev', 'test', __envm) _devs = ''' sed -i "s/%s/%s/g" %s ''' % ('dev', 'pro', __envm) _test = ''' sed -i "s/%s/%s/g" %s ''' % ('pro', 'test', __envm) _pro = ''' sed -i "s/%s/%s/g" %s ''' % ('test', 'pro', __envm) if sed == "test": os.system(_dev) os.system(_test) else: os.system(_devs) os.system(_pro)# 主函數def main(seting, *args): os.chdir(project_path) try: # 時間 BeginDate = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 清理工程 Git_project() Sed(seting) # 編譯項目 Build_project(seting) # 上傳到蒲公英 if seting == "test": remote_testfile = fnmat(seting) UploadIpaTo(remote_testfile, UpdateDescriptionTest) print("\033[1;32m====>> 正在修改資料庫...... <<====\033[0m") file_name = fnmat(seting) file_version = file_name[:-9] connet(file_version, TestURL) print("\033[1;32m====>> 正在備份檔案...... <<====\033[0m") ssh2(seting, file_version) print("\033[1;32m====>> 當前環境為: %s <<====\033[0m" % UpdateDescriptionTest) else: exec_360_jiagu() remote_testfile = fnmat(seting) UploadIpaTo(remote_testfile, UpdateDescriptionPro) print("\033[1;32m====>> 正在修改資料庫...... <<====\033[0m") file_name = fnmat(seting) # file_version = file_name[:-15] file_version = file_name[:5] connet(file_version, ProURL) print("\033[1;32m====>> 正在備份檔案...... <<====\033[0m") ssh2(seting, file_version) print("\033[1;32m====>> 當前環境為: %s <<====\033[0m" % UpdateDescriptionPro) print("\033[1;32m====>> 正在上傳檔案...... <<====\033[0m") # print("\033[1;32m====>> APP URL : %s <<====\033[0m" % URL) # 上傳至靜態伺服器 put_file(seting) EndDate = datetime.now().strftime('%Y-%m-%d %H:%M:%S') BeginTime = datetime.strptime(BeginDate, '%Y-%m-%d %H:%M:%S') EndTime = datetime.strptime(EndDate, '%Y-%m-%d %H:%M:%S') ExportTime = (EndTime - BeginTime) print("\033[1;32m====>> 目前的版本為: %s <<====\033[0m" % file_version) print("\033[1;32m====>> 當前分支為: %s \033[0m" % branch) print("\033[1;32m====>> 總用時為: %s <<====\033[0m" % ExportTime) except EOFError as e: exit('Build Error, Please check!', e)if __name__ == "__main__": sets = input("Please input Build Setting(test,pro):") if sets == "test" or sets == "pro": main(sets) else: exit("\033[1;31m-*-*-*-*-*- 輸入錯誤請重新輸入... -*-*-*-*-*-\033[0m")