我是靠谱客的博主 等待未来,最近开发中收集的这篇文章主要介绍Jenkins连接python脚本打包(包含更换网络环境,发邮件),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

        现在的公司之前,在项目的测试阶段每天都要打包,重复的工作天天干,当然就没热情了,听着Android_studio互斥互斥的跑一次编译打包浪费1分钟多的时间,还要打好几个环境的安装包,实在耽误下班时间。就借助测试的自动化测试的机器,跑了一个jenkins打包机。
        好景不长,自动化构建被领导作为公司级别的战略要做,so 进入了按照服务技术的业务需求的 打包2.0时代。为了可以响应各种各样的领导和团队要求,把所有的打包动作,以python脚本形式放在外部。jenkins只作为触发器使用。非常远离我当初的CI 设想,不过 whatever 老板要求,我一般都懒得去争论,就想我最近看到的,每个公司的层级和位置,都有位置和视觉的优势和劣势。老板领导会搞点php和后台的东西,所以把前端的各种实现和想法,包括更换网络环境,发邮件,编译预警,自定义网络环境(公司每个后台都有一个dock,一个外网地址),更换git的开发分支等等,用后台的思想和感觉去套。有些可笑,也让我们有点苦逼。
        发钱的就是上帝。最终利用加班中的闲暇时间,和公司小伙伴,流水式编程,也算是实现了。中间在交流和打包各种task,项目路径,git路径和git状态等,浪费了大量的时间,我这算是支持QA工作,功劳算不上,全他妈是苦劳,还不难耽误工作。

不说了,直接上代码吧。

# coding=utf-8
import os
import subprocess
import time
import sys
import requests
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
reload(sys)
sys.setdefaultencoding('gb2312')
'''
args
'''
gitPath=sys.argv[1]
gitVersion=sys.argv[2]
env=sys.argv[3]
appurl=sys.argv[4]
jobName = sys.argv[5]
# Testpack2.py $WORKSPACE $branch_name $env $appurl $JOB_NAME
os.system('echo ***********************参数列表*****************')
os.system('echo git打包的仓库代码路径:' + gitPath)
os.system('echo git打包的分支:' + gitVersion)
os.system('echo git打包的环境:' + env)
os.system('echo git—jenkins打包的制定url:' + appurl)
os.system('echo git-jenkins打包的task:' + jobName)
sendor = 'andy@chope.net.cn'
emailPwd = 'Mandy@123456'
receiver = 'b2ce-commerce@chope.co'
fromBody = 'PackingAutoMachine'
envMark = "Test"
branchMark = "ChopeShop_V4.7.2_8A"
bundleId = "5b62dbf1ca87a87c1140ece1"
api_token = "caa241448cb526621e5b5b822e8be85e"
firDownloadPageUrl = "https://fir.im/zv89?release_id="
packagesDirecotry = '/Users/chope/.jenkins/workspace/' + jobName + '/ChopeAndroid/app/build/outputs/apk/debug'
'''
git operation
'''
os.system('echo *********************git operation*******************')
os.chdir(gitPath)
gitbranch = gitVersion.replace("origin/","")
os.system("git branch -D {}". format(gitbranch))
os.system("git checkout -b "+ gitbranch + " " + gitVersion )
os.system("git checkout {}". format(gitbranch))
os.system("git pull")
print "brach success"
# 替换测试,仿真,线上生产环境
httpCode = "/Users/chope/.jenkins/workspace/" + jobName + "/ChopeAndroid/app/src/main/java/com/chope/gui/network/ChopeHTTPRequestHelper.java"
def replaceEnv():
if env == "dev":
os.system("sed -i '' 's#public static boolean isDebug = true, isSimulation = false;#public static boolean isDebug = true, isSimulation = false;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = true, isSimulation = ture;#public static boolean isDebug = true, isSimulation = false;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = false, isSimulation = ture;#public static boolean isDebug = true, isSimulation = false;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = false, isSimulation = false;#public static boolean isDebug = true, isSimulation = false;#' '" + httpCode + "'")
elif env == "simulation":
os.system("sed -i '' 's#public static boolean isDebug = true, isSimulation = false;#public static boolean isDebug = false, isSimulation = true;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = true, isSimulation = ture;#public static boolean isDebug = false, isSimulation = true;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = false, isSimulation = ture;#public static boolean isDebug = false, isSimulation = true;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = false, isSimulation = false;#public static boolean isDebug = false, isSimulation = true;#' '" + httpCode + "'")
else:
os.system("sed -i '' 's#public static boolean isDebug = true, isSimulation = false;#public static boolean isDebug = false, isSimulation = false;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = true, isSimulation = ture;#public static boolean isDebug = false, isSimulation = false;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = false, isSimulation = ture;#public static boolean isDebug = false, isSimulation = false;#' '" + httpCode + "'")
os.system("sed -i '' 's#public static boolean isDebug = false, isSimulation = false;#public static boolean isDebug = false, isSimulation = false;#' '" + httpCode + "'")
def replaceEnvParam():
if env == "dev":
os.system("sed -i '' 's#simulation_environment#test_environment#' '" + httpCode + "'")
os.system("sed -i '' 's#production_environment#test_environment#' '" + httpCode + "'")
elif env == "simulation":
os.system("sed -i '' 's#test_environment#simulation_environment#' '" + httpCode + "'")
os.system("sed -i '' 's#production_environment#simulation_environment#' '" + httpCode + "'")
else:
os.system("sed -i '' 's#test_environment#production_environment#' '" + httpCode + "'")
os.system("sed -i '' 's#simulation_environment#production_environment#' '" + httpCode + "'")
#使用apprUrl 参数
if appurl != "":
replaceEnv()
replaceEnvParam()
# appUrl
os.system("sed -i '' 's#https://geo-entry.chope.co#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://geo-entry.dingzhuo8.cn#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://api.yong.chope.cc#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://api.app.chope.cc#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://api.anurup.chope.info#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://api.commerceapp.chope.cc#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://api.jiayuan.chope.info#"+appurl+"#' '" + httpCode + "'")
os.system("sed -i '' 's#http://api.mark.chope.info#"+appurl+"#' '" + httpCode + "'")
else:
replaceEnv()
replaceEnvParam()
#删除apk目录
try:
os.chdir(packagesDirecotry)
os.system('echo %s|sudo -S %s'%('123456','rm -rf *'))
except BaseException:
print("目录不存在")
#开始打包
os.chdir(gitPath)
print("环境替换完毕,开始运行打包。。。。。env is OK , run packing program.")
os.system("cp -f /Users/chope/Documents/Android/autoCI/local.properties /Users/chope/.jenkins/workspace/" + jobName)
os.system("cp -f /Users/chope/Documents/Android/autoCI/local.properties /Users/chope/.jenkins/workspace/" + jobName + "/ChopeAndroid")
os.system("echo ********************************* gradle start **********************")
os.system('echo local.properties cp ok.')
os.system("pwd")
build = 'sudo /Users/chope/.gradle/wrapper/dists/gradle-4.4-all/9br9xq1tocpiv8o6njlyu5op1/gradle-4.4/bin/gradle assemble'
os.system('echo %s|sudo -S %s'%('123456',build))
isSuccess = False
#判断是否打包成功,成功则为存在apk文件
filelist = os.listdir(packagesDirecotry)
for i in range(0, len(filelist)):
fileTemp = os.path.join(packagesDirecotry, filelist[i])
if (fileTemp.endswith('.apk')):
isSuccess = True
print("打包是否成功: " + str(isSuccess))
if not isSuccess:
message = MIMEMultipart('alternative')
message['From'] = fromBody
# 发送者
message['To'] = receiver
# 接收者
message['Reply-to'] = receiver
message['Message-id'] = email.utils.make_msgid()
message['Date'] = email.utils.formatdate()
subject = jobName + '打包失败,请开发快速检查'
message['Subject'] = subject
# 邮件内容组织
resultBody = jobName + '打包失败,请开发快速检查'
textHtml = MIMEText(resultBody, _subtype='html', _charset='UTF-8')
# textHtml = "texttext"
message.attach(textHtml)
smtpJenkins = smtplib.SMTP()
smtpJenkins.connect("smtp.chope.net.cn", 25)
smtpJenkins.set_debuglevel(0)
smtpJenkins.login(sendor, emailPwd)
try:
smtpJenkins.sendmail(sendor, receiver, message.as_string())
print("Success,邮件发送成功")
except smtplib.SMTPConnectError:
print('邮件发送失败,连接失败:')
except smtplib.SMTPAuthenticationError:
print('邮件发送失败,认证错误:')
except smtplib.SMTPSenderRefused:
print('邮件发送失败,发件人被拒绝:')
except smtplib.SMTPRecipientsRefused:
print('邮件发送失败,收件人被拒绝:')
except smtplib.SMTPDataError:
print('邮件发送失败,数据接收拒绝:')
except smtplib.SMTPException:
print('邮件发送失败, ')
except Exception:
print('邮件发送异常, ')
smtpJenkins.quit()
else:
print('Package Success')
##################
# fir 请求token
firParam = {"type": "android", "bundle_id": bundleId, "api_token": api_token}
r = requests.post('http://api.fir.im/apps', data=firParam)
print("请求fir,token,url.")
tokenResponse = r.json()
iconKey = tokenResponse["cert"]["icon"]["key"]
iconUrl = tokenResponse["cert"]["icon"]["upload_url"]
icontoken = tokenResponse["cert"]["icon"]["token"]
print("上传icon.")
print('apk_Key', iconKey)
print('apk_Url', iconUrl)
print('apk_Token', icontoken)
print()
# 发送 icon
files = {'file': ('file', open('/Users/chope/Documents/Android/autoCI/fir_icon.png', 'rb'))}
iconParams = {'key': iconKey,
'token': icontoken}
iconParams.update(firParam)
iconR = requests.post(iconUrl, data=iconParams, files=files)
iconRJson = iconR.json()
print("Icon 上传完毕")
print(iconR.status_code)
if iconR.status_code == 200:
print("Icon 上传成功")
else:
print("Icon 上传失败")
print(iconR.content)
print()
apkKey = tokenResponse["cert"]["binary"]["key"]
apkUrl = tokenResponse["cert"]["binary"]["upload_url"]
apkToken = tokenResponse["cert"]["binary"]["token"]
print("上传apk.")
print('apk_Key', apkKey)
print('apk_Url', apkUrl)
print('apk_Token', apkToken)
print()
# 上传 APK
filelist = os.listdir(packagesDirecotry)
lastApkFileIndex = 0
lastApkFileTime = 0
lastApkFile = ""
for i in range(0, len(filelist)):
fileTemp = os.path.join(packagesDirecotry, filelist[i])
lastApkFileTimeTemp = os.path.getmtime(fileTemp)
if (lastApkFileTimeTemp > lastApkFileTime) and (fileTemp.endswith('.apk')):
lastApkFile = fileTemp
lastApkFileTime = lastApkFileTimeTemp
lastApkFileIndex = i
print("上传包的路径 : " + lastApkFile)
print("上传包的创建时间 : " + str(lastApkFileTime))
apkFiles = {'file': ('file', open(lastApkFile, 'rb'))}
apkParams = {'key': apkKey,
'token': apkToken,
'x:name': 'Chope',
'x:version': '8.8.8',
'x:build': '88',
'x:changelog': 'Chope Beijing Tech . Automatic Packing Machine does.n' + lastApkFile.split("\")[
lastApkFile.count("\")]}
apkR = requests.post(apkUrl, data=apkParams, files=apkFiles)
apkRJson = apkR.json()
print("apk 上传完毕")
print(apkR.status_code)
if apkR.status_code == 200:
print("apk 上传成功")
else:
print("apk 上传失败")
print(apkRJson)
print()
emailTemplate = open('/Users/chope/work/Tools/CI/AppPackage/Test/email_CI_template.html', 'rw');
emailBody = emailTemplate.read()
# print(emailBody)
releaseId = apkRJson['release_id']
downloadId = apkRJson['download_url']
print "##########################################"
print ("Download App here {}".format(firDownloadPageUrl + releaseId))
print "##########################################"
# 邮件内容发送
message = MIMEMultipart('alternative')
message['From'] = fromBody
# 发送者
message['To'] = receiver
# 接收者
message['Reply-to'] = receiver
message['Message-id'] = email.utils.make_msgid()
message['Date'] = email.utils.formatdate()
subject = jobName + '打包成功,请扫描二维码开始测试'
message['Subject'] = subject
# 邮件内容组织
resultBody = emailBody.replace("PACKAGE_DOWN_URL", downloadId). 
replace("PACKAGE_DOWNLOAD_PAGE_URL", firDownloadPageUrl + releaseId). 
replace("$Env", envMark). 
replace("$Branch", branchMark). 
replace("$InnerBuildVersion", lastApkFile.split("\")[lastApkFile.count("\")]). 
replace("$BuildPackingTime", time.strftime("%a %b %d %H:%M:%S %Y", time.localtime(lastApkFileTime)))
textHtml = MIMEText(resultBody, _subtype='html', _charset='UTF-8')
message.attach(textHtml)
smtpJenkins = smtplib.SMTP()
smtpJenkins.connect("smtp.chope.net.cn", 25)
smtpJenkins.set_debuglevel(0)
smtpJenkins.login(sendor, emailPwd)
try:
smtpJenkins.sendmail(sendor, receiver, message.as_string())
print("Success,邮件发送成功")
except smtplib.SMTPConnectError:
print('邮件发送失败,连接失败:')
except smtplib.SMTPAuthenticationError:
print('邮件发送失败,认证错误:')
except smtplib.SMTPSenderRefused:
print('邮件发送失败,发件人被拒绝:')
except smtplib.SMTPRecipientsRefused:
print('邮件发送失败,收件人被拒绝:')
except smtplib.SMTPDataError:
print('邮件发送失败,数据接收拒绝:')
except smtplib.SMTPException:
print('邮件发送失败, ')
except Exception:
print('邮件发送异常, ')
smtpJenkins.quit()

        技术含量没多少。就是一个动作加一个动作。注意点也没啥说的,看需要吧。发在博客里,有需要的直接拷贝吧。算是偷懒的轮子方法。

最后

以上就是等待未来为你收集整理的Jenkins连接python脚本打包(包含更换网络环境,发邮件)的全部内容,希望文章能够帮你解决Jenkins连接python脚本打包(包含更换网络环境,发邮件)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部